diff --git a/.github/workflows/tend.yml b/.github/workflows/tend.yml
index 4590fc8..f4aa10e 100644
--- a/.github/workflows/tend.yml
+++ b/.github/workflows/tend.yml
@@ -8,6 +8,7 @@ on:
permissions:
contents: write
pull-requests: write
+ issues: write
concurrency:
group: tend
diff --git a/README.md b/README.md
index 0d9c27e..7f43cb5 100644
--- a/README.md
+++ b/README.md
@@ -22,11 +22,23 @@ with the evidence. When an update touches nothing, it stays quiet.
model: groq/openai/gpt-oss-120b
```
-Merge the workflow and tend runs once right away. Its first pull request is a
-tidy-up with a short welcome: it removes dependencies nothing in the project
-uses and moves the code off deprecated libraries, proven by your own tests.
+Merge the workflow and tend runs once right away. It catches the project
+up in at most four pull requests, one after another, each proven by your
+own build and tests:
+
+1. Fixes: security fixes, changes to the APIs your code calls, moves off
+ deprecated libraries, and the removal of dependencies nothing uses. When
+ your tests are too thin to prove the rest, this one first adds tests that
+ pin down how the code behaves today.
+2. Runtimes and build tooling: runtime pins past their end of life, base
+ images, Actions, compilers and bundlers.
+3. Major upgrades, a major at a time when the jump fails.
+4. Migrations and replacements: wide migrations, and deprecated libraries
+ with no single replacement, where tend picks one itself and proves it.
+
After that, tend runs on a schedule and opens one PR at a time, only for
-changes that touch your code.
+changes that touch your code. What it could not do on its own it lists in
+one tracking issue.
## What a pull request looks like
@@ -69,11 +81,13 @@ the first one.
uses get a PR. Plain version bumps do not, unless you turn them on.
- There is never more than one tend PR open, and it holds the whole change:
manifest, lockfile, every call site, and the tests that had to move.
-- Security comes first, then API changes that break your code, then
+- The catch-up comes first and carries what it can of the rest. After it,
+ security comes first, then API changes that break your code, then
deprecations, then breaking releases.
-- When there is no single replacement, the PR changes nothing and lists the
- options. Comment `tend apply 2` to pick one, `tend skip` to say no, or
- `tend retry` to try again.
+- When there is more than one way off something, tend takes the first its
+ rule allows that passes the proof, and says why. Comment `tend apply 2` to
+ have another, `tend skip` to say no, or `tend retry` to try again. Only
+ when none passes does the PR change nothing and list the options.
- Releases younger than three days wait, except security fixes, deprecations
and API changes.
@@ -90,7 +104,9 @@ deliver: {automerge: security}
```
[docs/config.md](docs/config.md) describes every key. `deliver: {mode: commit}`
-commits to the branch instead of opening PRs.
+commits to the branch instead of opening PRs, and keeps a repo current with
+no one watching: it pushes only what passed its proof, waits for your CI on
+each commit, and reverts its own commit when CI fails on it.
## Running it locally
diff --git a/action/install.sh b/action/install.sh
index a25145e..261c71a 100755
--- a/action/install.sh
+++ b/action/install.sh
@@ -25,7 +25,8 @@ tags() {
}
# An explicit version wins. Then a full tag in the action ref. Then the newest
-# release inside the ref's major (uses: ...@v1), else the newest release.
+# release inside the ref's major (uses: ...@v1), followed by the one before
+# it, else the newest release.
resolve() {
local major list
if [ -n "${1:-}" ]; then
@@ -40,7 +41,7 @@ resolve() {
v[0-9]*)
major=${ref%%.*}
list=$(api_get "$api/repos/$repo/releases?per_page=100" | tags) || die "could not list releases of $repo"
- { echo "$list" | grep -E "^${major}\.[0-9]+\.[0-9]+\$" || true; } | sort -t. -k2,2n -k3,3n | tail -n 1
+ { echo "$list" | grep -E "^${major}\.[0-9]+\.[0-9]+\$" || true; } | sort -t. -k2,2nr -k3,3nr | head -n 2
return
;;
esac
@@ -66,8 +67,17 @@ sha256_of() {
fi
}
-tag=$(resolve "${1:-}")
+tags=$(resolve "${1:-}")
+tag=$(echo "$tags" | sed -n 1p)
[ -n "$tag" ] || die "no release of $repo matches ${1:-${ref:-the latest release}}"
+# The newest release of a major may still be uploading its files when a
+# scheduled run starts; the one before it is installed instead. Either is
+# checked the same way below.
+older=$(echo "$tags" | sed -n 2p)
+if [ -n "$older" ] && ! curl -fsSL --retry 2 -o /dev/null "$dl/$repo/releases/download/$tag/checksums.txt.sig" 2>/dev/null; then
+ echo "tend install: $tag has no signed checksums yet; installing $older" >&2
+ tag=$older
+fi
version=${tag#v}
case "${RUNNER_OS:-$(uname -s)}" in
diff --git a/docs/config.md b/docs/config.md
index 42ce601..f48f7ce 100644
--- a/docs/config.md
+++ b/docs/config.md
@@ -60,23 +60,28 @@ schedule: 6h
`pr`, `quiet` or `off`, default `pr`. What tend's first run on a repo does.
-- `pr`: the first PR is a tidy-up that opens with a short welcome. It removes
- the dependencies nothing in the project uses and moves the code off
- deprecated libraries where the move can be proven, and lists what only
- looks unused and what it could not move. A repo with nothing to tidy gets
- a `tend.yml` with every key commented out, so the PR is not empty.
-- `quiet`: no first PR. tend starts its usual work and says once, in its
+- `pr`: tend catches the repo up in a few PRs, a stage each: fixes, then
+ runtimes and build tooling, then major upgrades, then migrations and
+ replacements. The first opens with a short welcome, removes the
+ dependencies nothing in the project uses, adds a test baseline when the
+ project's tests are too thin to prove the rest, and lists the stages to
+ come. A repo with nothing to catch up on gets a `tend.yml` with every key
+ commented out, so the PR is not empty.
+- `quiet`: no catch-up. tend starts its usual work and says once, in its
output, which dependencies nothing uses.
-- `off`: no first PR, and no look for unused dependencies.
+- `off`: no catch-up, and no look for unused dependencies.
The first run is the first on a repo where tend has never opened a PR, open,
-closed or merged; the forge says so even when tend's state is lost. The first
-PR is the one open PR like any other: only a security fix goes ahead of it,
-and it comes back once that fix merges. Closing it unmerged is final: tend
-does not open it again and goes on with its usual work. Setting `quiet` or
-`off` while it is open closes it on the next run. In commit mode there is no
-first PR. [docs/pr-anatomy.md](pr-anatomy.md#the-first-pull-request)
-shows one and how tend decides what nothing uses.
+closed or merged; the forge says so even when tend's state is lost. A
+catch-up PR is the one open PR like any other, and nothing goes ahead of it:
+a security fix goes in it, and a tend PR left open from before is closed and
+folded in. Once it merges, the next stage opens. Closing one unmerged is
+final: tend ends the catch-up and goes on with its usual work. Setting
+`quiet` or `off` while one is open closes it on the next run. In commit mode
+each stage is a commit.
+[docs/how-it-works.md](how-it-works.md#the-catch-up) says what goes in each
+stage, and [docs/pr-anatomy.md](pr-anatomy.md#the-first-pull-request) shows
+the PRs and how tend decides what nothing uses.
```yaml
onboarding: quiet
@@ -242,7 +247,8 @@ deps:
Optional. Without a model, tend applies version bumps and codemods, and opens
a decision PR when a change needs real code edits. With one, it also writes the
-migration for call sites no codemod covers. [how-it-works.md](how-it-works.md#what-leaves-the-machine) says what is sent.
+migration for call sites no codemod covers, and the tests a catch-up's
+baseline needs. [how-it-works.md](how-it-works.md#what-leaves-the-machine) says what is sent.
The whole entry can be one line naming the provider and the model it serves:
@@ -258,14 +264,16 @@ model: groq/openai/gpt-oss-120b
| `key_env` | string | `""` | name of the env var holding the API key. Empty tries `TEND_MODEL_KEY`, then the provider's usual variable (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GROQ_API_KEY`). `ollama` needs none, and sends `TEND_MODEL_KEY` when it is set. `GITHUB_TOKEN`, `GH_TOKEN` and tend's own `TEND_*` variables are refused |
| `command` | string | `""` | for `provider: command`: a shell line that reads the prompt on stdin and writes the reply on stdout. It runs without tokens and keys in its environment; name the one it needs in `key_env` |
| `attempts` | int | `2` | tries at a usable diff, for the `command` provider |
-| `turns` | int | `30` | tool calls a model with tool calling may make on one change |
-| `tokens` | int | `400000` | tokens it may spend on one change, prompts and replies together. `0` means no limit |
+| `turns` | int | `30` | tool calls a model with tool calling may make on one change, once more for every 10 call sites the change moves, up to five times |
+| `tokens` | int | `400000` | tokens it may spend on one change, prompts and replies together, scaled as `turns` is. `0` means no limit |
A provider with tool calling (all but `command`) works the change itself: it
reads and searches the worktree, edits the files the change explains and their
tests, and runs the project's own install, build and test commands. It is done
when every command passes, not when it says so. Running out of `turns` or
-`tokens` turns the PR into a decision with what was tried.
+`tokens` turns the PR into a decision with what was tried. A catch-up of a
+large or old project is a lot of migration; a stronger model than the
+example's gets further with it.
The `command` provider writes one diff instead; a reply that holds no diff, or
one that does not apply, is sent back with the reason, up to `attempts` times.
@@ -308,7 +316,7 @@ How the result leaves your machine.
| key | type | default | meaning |
|---|---|---|---|
-| `mode` | `pr`, `commit` | `pr` | `commit` pushes straight to `branch`. Opt in only; it skips review |
+| `mode` | `pr`, `commit` | `pr` | `commit` pushes straight to `branch`, only what passed its proof, and reverts it when the repository's CI fails on it. Opt in only; it skips review |
| `branch` | string | `""` | commit mode: the branch to push to. Empty means `base` |
| `labels` | list of strings | `[tend]` | added to every PR. Missing labels are created with color `0e8a16` |
| `draft` | bool | `false` | open every PR as a draft. A PR is a draft anyway when vetting flags something or the tests already fail on the base |
@@ -348,7 +356,13 @@ deliver:
In commit mode the push must fast-forward. If the branch moved, nothing is
pushed, since the tree on top of the new tip was never proven, and the next run
-does the change again from there.
+does the change again from there. A change with no build or test command to
+prove it, or one that ends as a decision, is never pushed. The next run waits
+for the repository's CI on the commit, and reverts the commit when CI fails
+on it and did not fail on the one before; the tracking issue lists what was
+reverted and why. CI runs on tend's commits only when the token can start
+workflows, which the default token cannot.
+[How it works](how-it-works.md#commit-mode) has the details.
## Environment
diff --git a/docs/github-actions.md b/docs/github-actions.md
index 1869c7f..00150d3 100644
--- a/docs/github-actions.md
+++ b/docs/github-actions.md
@@ -15,7 +15,7 @@ on:
paths: [.github/workflows/tend.yml]
schedule: [{cron: "17 6 * * *"}]
workflow_dispatch:
-permissions: {contents: write, pull-requests: write}
+permissions: {contents: write, pull-requests: write, issues: write, checks: read, statuses: read}
concurrency: {group: tend, cancel-in-progress: false}
jobs:
tend:
@@ -27,7 +27,9 @@ jobs:
with: {model-key: "${{ secrets.TEND_MODEL_KEY }}"}
```
-The `model-key` line is only needed if `tend.yml` names a model. On a private
+The `model-key` line is only needed if `tend.yml` names a model. `issues:
+write` lets tend keep its one tracking issue; `checks: read` and
+`statuses: read` let commit mode read your CI on the commits it pushed. On a private
repository every run uses Actions minutes. To run weekly, set `schedule: 7d`
before `tend init --ci`, or change the cron to `"17 6 * * 1"`.
@@ -40,7 +42,9 @@ The default `GITHUB_TOKEN` has two more limits. PRs it opens do not start
your other workflows, so your CI and auto-merge never run on them. It also
cannot push changes to `.github/workflows`, so Action bumps fail. Pass a
fine-grained token with the workflows permission, or a GitHub App token from
-`actions/create-github-app-token`, as `token:` to lift both.
+`actions/create-github-app-token`, as `token:` to lift both. In commit mode
+this matters more: a push with the default token starts no CI, so tend has no
+CI result to revert by.
## Inputs
@@ -53,5 +57,7 @@ fine-grained token with the workflows permission, or a GitHub App token from
| `version` | newest release of the action's major | the tend version to install |
| `model-key` | none | the key for the model `tend.yml` names |
-`@v1` moves to the newest `v1.x.y`; pin `@v1.2.3` to stay put. The action
+`@v1` moves to the newest `v1.x.y`, or to the one before it while the
+newest release's files are still being uploaded, so a scheduled run never
+fails on a release in progress; pin `@v1.2.3` to stay put. The action
checks the release signature before it puts the binary on the path.
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index d2020d0..20903f6 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -49,35 +49,124 @@ For the change it picked, tend:
2. makes the fix: a version bump through the native tool, lockfile included,
locked at exactly the release tend chose, and nothing else moved (a Go
bump keeps the requires `go mod tidy` would drop as unused); codemods for
- renames; and, with a model configured, a migration for the rest,
+ renames; and, with a model configured, a migration for the rest. For a
+ security fix the release tend chose is the least one that fixes it; a
+ dependency only the lockfile names may land on a later release of the
+ same major, which the PR names,
3. runs your install, build and tests on the base commit and on the patch,
+ and when the patch fails, tries what it may do by itself: a major at a
+ time, then each option its rule allows
+ ([choosing on its own](#choosing-on-its-own)),
4. vets the patch,
-5. opens or updates the one pull request.
-
-## The first run
-
-The first run on a repo where tend has never opened a PR carries one
-tidy-up before anything else; only a security fix goes ahead of it. It has
-two kinds of part:
-
-- each direct dependency nothing in the project uses, removed through the
- native tool so the lockfile follows (npm, pnpm and yarn; Go modules; pip,
- Poetry and uv); a deprecated one is removed rather than moved off;
-- each deprecated library the code calls, moved off the way its own PR would
- move it: the bump, then codemods, then the model. A move goes in only when
- it is made in full; one that needs code edits nobody can make here waits
- for a decision PR of its own.
-
-All the parts are built on the base commit together and proven by one run.
-When that run fails, tend splits the parts in halves and keeps what passes
-of each, the second half on top of what the first kept, until every part
-that fails is left out with the step that failed. The model is not asked
-again: each move's edits are kept from the first time it was made and
-applied again next to the other parts. What passes is vetted like any patch.
-A repo with nothing to tidy gets a PR that adds a commented `tend.yml`.
-[docs/pr-anatomy.md](pr-anatomy.md#the-first-pull-request) shows the PR and
+5. opens or updates the one pull request, or in commit mode pushes the
+ commit.
+
+## The catch-up
+
+A repo tend has never opened a PR on is caught up first, in a few PRs, one
+stage each, before tend opens PRs one change at a time. Every change in the
+queue belongs to one stage, by the first of these rules that matches:
+
+| stage | what goes there |
+|---|---|
+| 4. migrations and replacements | a change that moves more than 10 call sites; a deprecated package with no single replacement |
+| 1. fixes | a security fix; a change to an API the code calls |
+| 2. runtimes and build tooling | runtime pins and the oldest runtime the project supports, base images, Actions, and dev dependencies nothing outside the tests calls (compilers, bundlers, test runners) |
+| 3. major upgrades | a release that is only new, a major above all |
+| 1. fixes | any other move off something deprecated: a deprecated version or package with one target |
+
+The stages run in that order. Fixes come first because they fix what is
+wrong now, and the first PR carries the test baseline the rest is proven
+against. Runtimes and build tools come before majors, since new majors need
+new runtimes; the majors are then proven on the runtime they will ship on.
+Migrations come last, written against current libraries.
+
+Each catch-up PR carries its stage and whatever is left of the stages
+before it: a change that failed in an earlier stage, or a new advisory, is
+tried again there, on the newer base. Stages with nothing in them are
+skipped, so a repo is current after at most four PRs. The first one also
+removes the direct dependencies nothing uses (npm, pnpm and yarn; Go
+modules; pip, Poetry and uv), through the native tool so the lockfile
+follows; a deprecated or vulnerable one is removed rather than fixed. It
+lists the stages to come under Next stages; once it merges, the next stage
+opens, and so on. A repo with nothing to catch up on gets a PR that adds a
+commented `tend.yml`.
+
+Each change that needs more than its bump is made once on its own, so a
+model is asked only once; then every change and removal is built on the
+base commit together and proven by one run. When that run fails, tend
+splits the parts in halves and keeps what passes of each, the second half on
+top of what the first kept, until every part that fails is left out with
+the step that failed. A change whose own making fails is left out at once,
+without a run. A catch-up PR runs the project's commands at least 8 times
+and twice per part when it has more; what is still unsettled then waits for
+the next stage, and the log names every part left out. A part left out of
+the last stage is listed under Not done and in the tracking issue, and comes
+back as a PR of its own after the catch-up. What passes is vetted like any
+patch.
+
+Closing a catch-up PR unmerged ends the catch-up: tend goes on one change at
+a time, what that PR carried included. An open tend PR from before the
+first PR, as an earlier tend left on a repo where a security fix went ahead
+of its first PR, is closed with a line saying the first PR folds it in. A
+change that joins the queue while a catch-up PR is open, a new advisory say,
+rebuilds that PR rather than going ahead of it.
+[docs/pr-anatomy.md](pr-anatomy.md#the-first-pull-request) shows the PRs and
how tend decides that nothing uses a dependency.
+### Choosing on its own
+
+Where there is more than one way off something, tend takes one itself and
+proves it: only options that move are tried, a replacement only when it has
+a release that is neither yanked nor deprecated, one the project already
+depends on first, then the catalog's order, recommended first and then by
+how widely each is used. The first of at most three that passes its proof
+is taken, and the PR says which rule picked it; `tend apply N` on the PR
+takes another. Staying put is the outcome only when none passes.
+
+### Climbing majors
+
+A major two or more behind that fails its proof as one jump is climbed a
+major at a time: tend bumps to the newest release of the next major, has
+the model migrate the code with the release notes for that range only,
+proves it, and goes on from there. Each step is proven. The climb stops at
+the first step that fails, and the PR ships the highest step that passed,
+saying which failed; the rest comes in the next stage or a later PR.
+Runtimes and base images are not climbed: the lines in between are past
+their end of life too.
+
+### A baseline for weak tests
+
+The first catch-up PR looks at whether the project's tests can prove the
+catch-up at all. They are weak when there is no test command, or when a
+file the catch-up will change, a call site of any queued change outside the
+tests, is reached by no test: no JavaScript or TypeScript test names a
+relative path that resolves to it, no Python test imports its module, no Go
+test sits in its package, and elsewhere no test file carries its name.
+
+When they are weak, and the ecosystem can run generated tests (npm, pip
+and Go), the PR adds a baseline before anything else:
+
+1. A smoke test. tend lists the project's modules (code outside tests,
+ vendored and generated code and tool config, at most 50), loads each in a
+ child process on the base commit, and writes a test from a fixed template
+ that loads again exactly those that loaded; a module that starts a server
+ is loaded and the process exits. Go's build already loads every package.
+2. A typecheck, `tsc --noEmit`, for a TypeScript project without a build
+ script, when it passes on the base.
+3. With a model, tests of how the files the catch-up changes behave now,
+ written to one file (`test/tend/characterization.js`,
+ `tests/tend/test_characterization.py`, `tend_characterization_test.go`).
+ They must pass on the base commit; a failure goes back to the model while
+ its budget lasts, and tests that never pass are left out.
+4. The line that runs them, added to `verify.test` in `tend.yml` after the
+ project's own test lines, so every later proof runs them too.
+
+The baseline is part of every set the batch proves and is never split out,
+and the base column of the proof is the base commit with the baseline
+added. The PR's Baseline section says why the tests were weak and what was
+added.
+
## The proof
The fix is built in a git worktree of the base commit under tend's state
@@ -128,8 +217,9 @@ again.
## Model providers
A model is optional. Without one, tend does version bumps, lockfile updates,
-renames and path swaps that a codemod can express, and opens a decision PR for
-the rest, saying once that it is running without one.
+renames and path swaps that a codemod can express, takes such an option
+itself when it passes the proof, and opens a decision PR for the rest, saying
+once that it is running without one.
With one, the call sites no codemod covers are the model's work. A model with
tool calling works the change the way a person would: it reads and searches
@@ -141,6 +231,13 @@ says so. A failed run goes back to it, and running out of `model.turns` or
tool call is logged in the state directory, and the PR says how many steps it
took.
+The budget grows with the work: a change gets `model.turns` and
+`model.tokens` once, and once more for every 10 call sites it moves, up to
+five times; each step of a climb gets its own; writing a baseline's tests
+gets one more share for every five files it covers, up to five. A catch-up
+of a large, old project asks a lot of a model, and a stronger one than the
+demo's `groq/openai/gpt-oss-120b` gets further on it.
+
It starts from the evidence for the change (release notes, advisory text, spec
diff lines, the deprecation notice), the known ways to migrate, and each call
site with 25 lines of context. Whatever it reads after that comes from the
@@ -185,13 +282,48 @@ state a problem are reported, as flagged findings, with the model's sentence
as the reason. An answer that hedges ("may", "might"), says a line is fine or
unchanged, or repeats the code on its line is dropped.
+## Commit mode
+
+With `deliver: {mode: commit}` tend pushes to the branch instead of opening
+PRs, and keeps a repo current with no one watching:
+
+- Only what passed its proof is pushed. A change with no build or test
+ command to prove it, or one that ends as a decision, is not, and the
+ tracking issue says why. The catch-up runs the same way, a commit per
+ stage.
+- The next run reads the repository's own CI on the commit tend pushed,
+ its check runs and commit statuses. While CI runs, tend waits and does
+ nothing else, for up to six hours; no answer by then counts as no CI.
+- When CI fails on tend's commit and did not fail on the commit before it,
+ tend reverts its commit on the branch's tip, with a message that names the
+ commit, the checks that failed and the change, and pushes the revert. A
+ revert onto commits someone pushed since is proven first; one that puts
+ back the tree tend started from is not. The change is not tried again at
+ that release; a newer one starts over. A reverted catch-up commit ends the
+ catch-up, and its changes come back one at a time, so CI can tell which one
+ it was.
+- Pushes made with the workflow's default token start no other workflows,
+ so CI never runs on them and tend sees no CI. Pass a fine-grained or App
+ token for CI to check tend's commits.
+
+## The tracking issue
+
+tend keeps one issue on the repo, found by a marker in its body, that lists
+what it could not do on its own, each with why: changes it could not make or
+prove on the current base, commits it reverted after CI failed, deprecated
+packages it knows no replacement for, and parts the last catch-up stage left
+out. It opens the issue when there is something to list, edits it when the
+list changes, closes it when the list empties and opens it again when it
+fills. A run with nothing new does not touch it. Both modes keep it; the
+workflow `tend init --ci` writes asks for `issues: write`.
+
## State
tend remembers things in `$TEND_HOME`, by default `~/.cache/tend` on Linux,
`~/Library/Caches/tend` on macOS and `%LocalAppData%\tend` on Windows: a cache
of HTTP responses, pruned after a week; one `state.json` per repository (what
-was seen, what you rejected, which PR is open, whether the first PR is behind
-it); spec snapshots; the logs of the
+was seen, what you rejected, which PR is open, how far the catch-up got, the
+tracking issue); spec snapshots; the logs of the
last run of each change; and the worktree while a run is in progress. Nothing
is written inside your repository.
@@ -204,7 +336,8 @@ with `actions/cache`.
Requests to public registries and advisory databases (package names and
versions), `endoflife.date`, the providers' spec and changelog URLs, the
APIs.guru directory and, for a host outside the catalog, `GET` requests for
-its spec at the usual paths; the GitHub API and `git push` of the branch; and,
+its spec at the usual paths; the GitHub API, including the CI results of the
+commits tend pushed and its tracking issue, and `git push` of the branch; and,
if you configured a model, the model requests described above. Also sent: the
failing output of your commands when a run fails, to the model and in the PR
body, with the values of `verify.env` variables masked. Never sent: tokens,
diff --git a/docs/limitations.md b/docs/limitations.md
index c7683c4..0f14c27 100644
--- a/docs/limitations.md
+++ b/docs/limitations.md
@@ -29,20 +29,60 @@
such as a package loaded by a name built at run time with no part of the
name written out, is caught only by the proof, and only if the tests reach
it.
-- A security fix that goes ahead of the first PR marks it as still owed in
- its own marker. A state lost after that fix merged, before the next run,
- no longer finds the mark, and the first PR is not opened.
-- Without a model, a real code migration becomes a decision PR. With one, the
- result is as good as your tests: if they do not cover a call site, a passing
- proof proves little. The PR says what ran, and vetting flags what it cannot
- verify.
+- A PR that went ahead of the first PR, as an earlier tend let a security
+ fix do, marks the first PR as owed in its own marker. If that PR merges and
+ tend's state is lost before the next run, the mark is gone and the first
+ PR is not opened.
+- A catch-up PR's proof covers its whole batch. A part that fails only next
+ to another is found by splitting, which takes more runs; past its budget of
+ runs, the parts not yet settled wait for the next stage even when they would
+ pass.
+- Without a model, a real code migration becomes a decision PR, and so does a
+ choice between replacements, unless a rename a codemod makes passes the
+ proof. With one, the result is as good as your tests: if they do not cover
+ a call site, a passing proof proves little. The PR says what ran, and
+ vetting flags what it cannot verify.
+- The test baseline is only as good as what it can see. Weak tests are told
+ by whether a test file names or imports the files the catch-up changes, not
+ by coverage, so a test that imports a file and checks nothing counts. The
+ smoke test proves a module still loads, not that it works. Tests a model
+ writes pin down behavior it noticed, and pass on the base by construction;
+ they miss what it did not read. Generated tests are written for npm (as
+ `node --test` files, which need Node 18 or later where the proof runs), pip
+ and Go only; elsewhere a project with weak tests is caught up on whatever
+ its own commands prove.
+- Stages are fixed by rules, not by what a project needs: a runtime that
+ only a major upgrade requires still moves in stage 2, and a deprecation
+ that needs a new runtime fails in stage 1 and is tried again in stage 2.
+ A major is climbed only through the majors a registry lists; a library
+ whose own migration guide skips majors, or needs two packages to move in
+ step that no group or peer links, may still not get there.
+- tend chooses among options by a fixed order, not by what fits the code
+ best. The catalog of replacements is short and curated; a deprecated
+ package it does not list and whose registry names none stays where it is,
+ and the tracking issue says so.
+- Unattended commit mode trusts the repository's CI to catch what the
+ project's own commands do not. With no CI, or with pushes made by a token
+ that starts no workflows, a commit that passed tend's proof stays. A revert
+ onto commits someone pushed since is proven only by the project's commands.
+ A reverted catch-up commit is not split further: its changes come back one
+ at a time.
+- A project whose base commit no longer installs on a current runtime, with
+ an old native addon say, or a registry that is gone, has nothing to prove
+ a change against; the catch-up gets only as far as its proof does. A
+ provider's rate or daily token limit stops a model midway as well, and the
+ part it was on waits for the next stage, with the error as its reason.
+- A runtime pin moves the file that names it, not the runtime CI or the
+ container uses; the proof runs on whatever runtime the runner has, unless
+ `verify.container` names an image.
- The proof runs your tests on your runner. Tests that need services, secrets
or hardware need those provided, or a `verify.test` that avoids them.
- A transitive dependency is moved alone only where the native tool can do
that; elsewhere tend says to declare it directly. npm, pnpm, yarn and
- Poetry move one only to the newest release its ranges allow; when that is
- not the release tend chose, the bump fails with a note instead of landing
- a version nobody picked.
+ Poetry move one only to the newest release its ranges allow. tend takes
+ that release when it is the one it asked for or a later one of the same
+ major, proves it and names it in the PR; a release on another major fails
+ the bump with a note instead of landing a version nobody picked.
- A Maven dependency whose version comes from `dependencyManagement`, in its
own pom or a parent, is not swapped for another artifact: renaming it
would leave the new one without a version. One whose version comes from a
diff --git a/docs/pr-anatomy.md b/docs/pr-anatomy.md
index d222e06..6808551 100644
--- a/docs/pr-anatomy.md
+++ b/docs/pr-anatomy.md
@@ -74,8 +74,8 @@ ok 1 - payment intents
`Replace X with Y`, `Migrate off deprecated X 14.x`, `Migrate off deprecated GET /path`,
`Handle removed field F on GET /path`, `Bump node base image to 24-alpine`,
`Bump actions/checkout to v7`, `Move nodejs to 24.22.0`, `Fix deprecation warnings from X`,
-`Pin X to V` and `Decide: migrate off X 14.x`, and for the first PR on a repo
-`Tidy up: ...` or `Set up tend: nothing to tidy up`. `deliver.title_prefix` goes in front.
+`Pin X to V` and `Decide: migrate off X 14.x`, and for a catch-up PR
+`Catch up: ...` or `Set up tend: nothing to catch up on`. `deliver.title_prefix` goes in front.
**Heading and Why.** The package and the move, then the reason in one line:
the kind of change, the advisory and its severity, the fixed version, the
@@ -126,17 +126,38 @@ because the native tool is not installed, or auto-merge that GitHub refused.
**Footer and marker.** The last line is a comment GitHub does not show:
``. It holds the change id, the base
commit the patch was built on and a revision that grows by one each time tend
-updates the PR. A PR that went ahead of tend's first PR also carries
-`tidy="due"`, so a lost state still owes the tidy-up. tend reads it back on the
-next run to know which change this PR carries. Do not edit it.
-
-## When the PR is a decision
-
-A deprecation with no single replacement, or a change that needs code edits no
-codemod covers when there is no model to make them, opens a PR that changes
-nothing. Its body lists where the code uses the thing, the output of the plain
-bump tend tried when one was worth trying, and the options. An option tend
-cannot prove without help is marked `not mechanical`.
+updates the PR. A PR that went ahead of tend's first PR, which happens only
+while the first PR cannot be proven on the base, also carries `tidy="due"`, so
+a lost state still owes the first PR, which folds that PR in when it opens. A
+catch-up PR carries `stage="N"`, so a lost state still knows how far the
+catch-up got. tend reads the marker back on the next run to know which change
+this PR carries. Do not edit it.
+
+## When tend chooses
+
+A deprecation with no single replacement, or a move that the bump alone
+does not carry, has options. tend takes one itself, by a fixed rule, and
+proves it:
+
+1. Only options that move are tried: a replacement package, a rename a
+ codemod makes, a release past the deprecated one. Pinning is never tried.
+2. A replacement must have a release to move to that is neither yanked nor
+ deprecated.
+3. A package the project already depends on comes first. Then the catalog's
+ order, which lists the recommended replacement first and the rest by how
+ widely each is used.
+4. Each is made (the swap or bump, codemods, the model) and proven in turn,
+ at most three, and the first that passes is taken.
+
+The PR applies it, says which rule picked it (`tend took option 1 on its
+own: the catalog's recommended replacement`), names any option that failed
+before it, and lists the others with the comment that applies each instead.
+
+When none of them passes, tend stays put, and the PR is a decision: it
+changes nothing, and its body lists where the code uses the thing, the output
+of the plain bump tend tried when one was worth trying, and the options. An
+option tend cannot prove without help is marked `not mechanical`. In commit
+mode nothing is pushed for it, and the tracking issue lists it instead.
````markdown
## moment: choose a replacement
@@ -171,7 +192,8 @@ Nothing was applied. Comment on this PR with the number you want.
````
-Comment on the PR to choose. The newest matching comment from someone with the
+Comment on the PR to choose, on a decision or to have another option than the
+one tend took. The newest matching comment from someone with the
`OWNER`, `MEMBER` or `COLLABORATOR` role wins. Comments from bots (logins
ending in `[bot]`) are never commands, whatever their role.
@@ -181,51 +203,85 @@ ending in `[bot]`) are never commands, whatever their role.
| `tend skip` | tend closes the PR and does not propose the same target again |
| `tend retry` | tend throws away its worktree and redoes the change, once |
-When one option is mechanical (a rename, a path swap), tend applies it, proves
-it, and lists the others below. If the proof fails, the PR becomes a decision
-PR. A deprecation notice that names a rename (`charges.* was replaced by
+A deprecation notice that names a rename (`charges.* was replaced by
paymentIntents.*`) gives an option to apply it; staying on the version in use
is an option too, and applying it writes the `ignore` entry into `tend.yml` in
the same PR, so the decision is reviewed and recorded like any other change.
## The first pull request
-The first run on a repo opens a tidy-up before any other change; only a
-security fix goes ahead of it. Its body starts with a short welcome instead
-of a heading: what tend does, what this PR does, what tend does from now on,
-and how to steer it. The usual sections follow. The golden file behind this
+The first run on a repo opens the first of a few catch-up PRs, before any
+other change; nothing goes ahead of it. Its body starts with a short
+welcome instead of a heading: what tend does, what this PR does, how many
+catch-up PRs follow, and how to steer it. Its own sections follow, then the
+proof and the vetting of the whole patch. The golden file behind this
example is `internal/deliver/testdata/tidy.golden.md`.
````markdown
-Thanks for adding tend: it looks after the packages this repository depends on and the APIs its code calls. This first pull request tidies up: it removes 2 dependencies nothing in the project uses and moves the code off 1 deprecated library. What it found and left alone is listed below, for you to decide. From now on it opens one pull request at a time, only for changes that touch your code, and each one shows the build and test runs that prove it. Steer it with `tend.yml`, or comment `tend skip`, `tend retry` or `tend apply N` on its pull requests.
+Thanks for adding tend: it looks after the packages this repository depends on and the APIs its code calls. This first pull request starts catching the repository up: a test baseline, 3 security fixes, 1 API change, 1 deprecated library and 2 unused dependencies. The rest comes in 3 more pull requests, one stage at a time, listed under Next stages and each proven the same way. Once the catch-up is done it opens one pull request at a time, only for changes that touch your code, and each one shows the build and test runs that prove it. Steer it with `tend.yml`, or comment `tend skip`, `tend retry` or `tend apply N` on its pull requests.
-### What changed
+Part of this pull request was written by a model, in 4 steps: 1 read, 2 edits, 1 run; the commands passed the one time they ran. The vetting section below covers it.
-Removed, since nothing in the project uses them:
+### Baseline
-- `@acme/colors` 1.2.0 in `package.json`
-- `left-pad` 1.3.0 in `package.json`
+This project's tests are too thin to prove the catch-up by: there is no test command. So this pull request first adds tests that pin down how the code behaves on main@abc1234, and every proof from here on runs them:
+
+- `test/tend/characterization.js`: tests a model wrote of the current behavior
+- `test/tend/smoke.js`: loads each of the 4 modules that load on the base commit, and exits
+- `node --test test/tend/characterization.js test/tend/smoke.js` in `verify.test` in `tend.yml`, after the project's own test lines
+
+They pass on main@abc1234: the base column of the proof below is that commit with these tests added.
+
+### Security
+
+npm:
+
+- `lodash` 4.17.20 → 4.17.21: GHSA-35jh-r3h4-6jhm (high)
+- `tar` 7.5.20 → 7.5.22 (transitive): GHSA-8qq5-rm4j-mr97 (moderate); 7.5.21 fixes it, and the lockfile took the newest release its ranges allow
+
+go:
+
+- `golang.org/x/net` v0.36.0 → v0.38.0: GO-2025-3595 (moderate)
+
+### Stripe API
+
+- `GET /v1/charges`: response field deprecated (source)
-Moved off a deprecated library:
+### Deprecated
- `stripe` 14.2.0 → 16.0.0: 14.x is deprecated: charges.* was replaced by paymentIntents.*
- `src/billing.js:42` `const c = await stripe.charges.create({ amount: order.total })` → `const c = await stripe.paymentIntents.create({ amount: order.total })`
- `src/billing.js:88` `return stripe.charges.retrieve(id)` → `return stripe.paymentIntents.retrieve(id)`
+### Unused
+
+Removed, since nothing in the project uses them:
+
+- `@acme/colors` 1.2.0 in `package.json`
+- `left-pad` 1.3.0 in `package.json`
+
Possibly unused, kept: these look unused, but tend cannot prove it, so they are yours to decide.
- `eslint-plugin-acme` 2.0.0 in `package.json`: a plugin eslint loads by a name its config gives
- `chalk` 5.3.0 in `package.json`: with it removed, `npm test` fails (exit 1)
-Deprecated, not moved: each gets a pull request of its own after this one.
+### Next stages
+
+Each comes as a pull request of its own once this one is merged, proven the same way.
-- `moment` 2.30.1: no model is configured to move the 3 call sites. `tend apply N` on its pull request picks one of:
- 1. Migrate to `dayjs`
- 2. Pin to 2.30.1 and ignore
+2. Runtimes and build tooling
+ - `nodejs` 18.20.4 → 22.20.0 in `.nvmrc`: Node.js 18 reached end of life on 2025-04-30.
+ - `axios` 0.27.2 → 1.12.0: with it in the batch, `npm test` fails (exit 1).
+3. Major upgrades
+ - `vitest` 1.6.0 → 3.2.4: a new major release.
+4. Migrations and replacements
+ - `moment` 2.30.1: deprecated, with no single replacement. tend takes the first of `dayjs` and `luxon` its proof passes, in that order.
-Files: `package-lock.json`, `package.json`, `src/billing.js`.
+### Not done
-Part of this change was written by a model, in 4 steps: 1 read, 2 edits, 1 run; the commands passed the one time they ran. The vetting section below covers it.
+These could not be made or proven here. Each comes back as a pull request of its own after the catch-up, and tend's tracking issue keeps the list.
+
+- `uuid` 3.4.0 → 9.0.1: making it changes no files.
### Proof
@@ -246,40 +302,107 @@ ok 1 - payment intents
### Vetting
-- scope: 3 files, all explained by this change
+- scope: 6 files, all explained by this change
- symbols: 2/2 changed calls resolve
- lockfile: only the bumped packages and their dependencies changed
- debug: nothing added
- comments: nothing added
tend · comment `tend skip` or `tend retry`
-
+
````
-**Title.** `Tidy up: remove 4 unused dependencies, move off 1 deprecated
-library`, naming only what the PR does. A repo with nothing to tidy gets
-`Set up tend: nothing to tidy up`, and a PR that adds a `tend.yml` with every
-key commented out, so it changes nothing. A repo that has a `tend.yml`
-already, committed or only written to the checkout tend runs in, as
-`tend init --now` does, gets no such PR.
+**Title.** `Catch up: 12 security fixes, 1 deprecated library, 6 unused
+dependencies`, counting only what the PR does, in the order of its sections.
+A title past 80 characters counts every deprecation as one kind, and past
+that the changes as one number. A repo with nothing to catch up on gets
+`Set up tend: nothing to catch up on`, and a PR that adds a `tend.yml` with
+every key commented out, so it changes nothing. A repo that has a
+`tend.yml` already, committed or only written to the checkout tend runs in,
+as `tend init --now` does, gets no such PR.
+
+**Sections.** In this order, each left out when it is empty:
+
+- Baseline: when the project's tests are too thin to prove the catch-up,
+ why, and the tests the PR adds first: a smoke test of the modules that
+ load on the base commit, tests a model wrote of how the code behaves now,
+ and the line in `verify.test` that runs them.
+ [How it works](how-it-works.md#a-baseline-for-weak-tests) says how tend
+ decides the tests are thin.
+- Security: each advisory the PR fixes by a bump or a lockfile update,
+ under its ecosystem. A dependency only the lockfile names says
+ `(transitive)`; when the lockfile took a later release than the one that
+ fixes it, as npm does, the line names both.
+- One section per API provider, such as `Stripe API`: each breaking or
+ deprecated change to an API the code calls that the PR handles.
+- Deprecated: each deprecated library the code calls, moved as its own PR
+ would move it (the bump, then codemods, then the model), with every call
+ site it changed, before and after, and the option tend took when it chose.
+- Runtimes and tooling, and Upgrades: what a later stage moves, when this
+ is that stage.
+- Unused: the dependencies nothing in the project uses, removed through the
+ native tool so the lockfile follows, with the manifest that declared each;
+ then what looks unused but tend cannot prove is, and why, with a removal
+ whose proof failed and the step that failed.
+- Next stages: the catch-up PRs still to come, stage by stage, with what
+ each will carry, and anything this PR left out, under the stage that tries
+ it again, with why.
+- Not done: what this PR left out with no later stage to go to. Each comes
+ back as a PR of its own after the catch-up, and the tracking issue lists
+ it.
+
+**Proof and vetting.** Everything the PR does is proven by one run on the
+patched tree. When it fails, tend leaves parts out until the rest passes
+([how it works](how-it-works.md#the-catch-up)), and lists each under Next
+stages, Not done or Unused with why. Vetting reads the patch like any other.
-**What changed.** Four lists, each left out when it is empty:
+### The stages after it
-- Removed: the dependencies nothing in the project uses, with the manifest
- that declared each. Each goes out through the native tool, so the lockfile
- follows.
-- Moved off: each deprecated library the code calls, moved as its own PR
- would move it (the bump, then codemods, then the model), with every call
- site before and after.
-- Possibly unused, kept: what looks unused but tend cannot prove is, and
- why; also a removal whose proof failed, with the step that failed.
-- Deprecated, not moved: a library whose move could not be made or proven
- here, with its options. Each gets a decision PR of its own after this one.
+Each later catch-up PR opens once the one before it merged, and carries one
+stage and whatever is left of the stages before it. It opens with a line
+saying which stage it is instead of the welcome. The golden file behind this
+example is `internal/deliver/testdata/catch_up_stage.golden.md`.
-**Proof and vetting.** Every removal and move is proven by one run on the
-patched tree. When it fails, tend leaves parts out until the rest passes
-([how it works](how-it-works.md#the-first-run)), and what it left out is
-listed with why. Vetting reads the patch like any other.
+````markdown
+This pull request carries on tend's catch-up with migrations and replacements: 1 replaced library and 1 major upgrade. It is the last stage; after it, tend opens one pull request at a time, only for changes that touch your code.
+
+Part of this pull request was written by a model. The vetting section below covers it.
+
+### Deprecated
+
+- `request` 2.88.2 → `axios` 1.12.2, picked from 2 options: the project already depends on axios
+
+### Upgrades
+
+- `express` 3.21.2 → 5.1.0, by way of 4.21.2, each proven: a new major release
+
+### Proof
+
+| step | base (main@abc1234) | patched |
+|---|---|---|
+| `npm ci` | ok · 12s | ok · 13s |
+| `npm test` | ok · 30s | ok · 31s |
+
+npm test (patched), end of its output
+
+```
+TAP version 13
+ok 1 - payment intents
+1..1
+# pass 1
+```
+
+
+### Vetting
+
+- scope: 4 files, all explained by this change
+
+tend · comment `tend skip` or `tend retry`
+
+````
+
+A major that the jump to its target failed is climbed a major at a time,
+each step proven; the line says which releases it climbed through.
### How tend decides that nothing uses a dependency
@@ -358,18 +481,18 @@ put back.
### After the first pull request
It is the one open PR until it is merged or closed. A re-run refreshes it
-when the base moves, and `tend skip` and `tend retry` work as on any PR.
-Closing it unmerged is final: tend does not open it again, and goes on with
-its usual work, the deprecated libraries it held back included. A security
-fix that arrives while it is open closes it and takes its place, and it
-comes back once the fix merges; a comment left on it after tend closed it
-does not change that. The fix's marker says the first PR is still owed, so
-a state lost while the fix is open still brings it back. `onboarding: quiet` in `tend.yml` skips the first PR,
-and `off` also skips the look for unused dependencies. Set either while the
-first PR is open, or let the base reach a point with nothing left to tidy,
-and the next run closes it with a comment saying why. `tend check` shows
-whether the first PR is due but, since it reads the checkout with any local
-edits, does not decide it.
+when the base moves, or when a change joins the queue, such as a new
+advisory, which goes in it rather than ahead of it. `tend skip` and
+`tend retry` work as on any PR. Once it merges, the next stage opens, and so
+on until no stage has anything left; then tend opens one PR at a time again,
+security first. Closing a catch-up PR unmerged is final: tend does not open
+it again, ends the catch-up, and goes on with its usual work, what that PR
+carried included. `onboarding: quiet` in `tend.yml` skips the first PR and
+the stages, and `off` also skips the look for unused dependencies. Set either
+while the first PR is open, or let the base reach a point with nothing left
+to catch up on, and the next run closes it with a comment saying why.
+`tend check` shows whether the first PR is due but, since it reads the
+checkout with any local edits, does not decide it.
## Re-runs
@@ -381,6 +504,6 @@ tend's state: a PR on a `tend/` branch with tend's marker in its body, whose
branch is one commit on the base the marker names, is tend's to update. A
commit pushed on top of it, or a merge of the base branch, is someone else's;
tend says so once on the PR and leaves it until it is merged or closed. A
-security fix that appears while another PR is open closes that
-PR with a comment and takes its place; the closed change returns to the queue
-after the fix merges.
+security fix that appears while another PR is open closes that PR with a
+comment and takes its place; the closed change returns to the queue after the
+fix merges. The first PR is the exception: the fix goes into it instead.
diff --git a/docs/self-update.md b/docs/self-update.md
index 48a5063..2f81bcc 100644
--- a/docs/self-update.md
+++ b/docs/self-update.md
@@ -15,8 +15,9 @@ print one line on stderr when there is one; they never update by themselves.
A binary built by `go install` reports the module version it was built from.
The Action does the same check with `openssl` before it puts the binary on
-the path. `@v1` is a moving tag that points at the newest `v1.x.y`; pin
-`@v1.2.3` to stay put.
+the path. `@v1` is a moving tag that points at the newest `v1.x.y`; while that
+release's files are still being uploaded, the Action installs the one before
+it. Pin `@v1.2.3` to stay put.
## Installing by hand
diff --git a/internal/api/catalog.go b/internal/api/catalog.go
index 1630682..8a42386 100644
--- a/internal/api/catalog.go
+++ b/internal/api/catalog.go
@@ -3,6 +3,7 @@ package api
import (
_ "embed"
"slices"
+ "sync"
"gopkg.in/yaml.v3"
@@ -19,6 +20,7 @@ type SDK struct {
type Provider struct {
Name string `yaml:"name"`
+ Title string `yaml:"title"` // the name as the provider writes it: "GitHub"
Hosts []string `yaml:"hosts"`
Spec string `yaml:"spec"` // URL, or a path relative to the repo root
Changelog string `yaml:"changelog"` // RSS, Atom or HTML page, for a provider without a spec
@@ -37,6 +39,19 @@ func Catalog() []Provider {
return res
}
+var catalog = sync.OnceValue(Catalog)
+
+// Title is the name a provider goes by in a PR: the catalog's spelling, or the
+// name as tend.yml gives it.
+func Title(name string) string {
+ for _, p := range catalog() {
+ if p.Name == name && p.Title != "" {
+ return p.Title
+ }
+ }
+ return name
+}
+
// Merge applies the apis entries of tend.yml to the catalog: an entry with a
// known name replaces that provider's hosts and spec, any other is appended.
func Merge(cat []Provider, cfg []config.API) []Provider {
diff --git a/internal/api/providers.yml b/internal/api/providers.yml
index 9b23af4..8a88e61 100644
--- a/internal/api/providers.yml
+++ b/internal/api/providers.yml
@@ -1,41 +1,50 @@
- name: stripe
+ title: Stripe
hosts: [api.stripe.com]
spec: https://raw.githubusercontent.com/stripe/openapi/master/openapi/spec3.json
sdks: [{eco: npm, name: stripe}, {eco: pip, name: stripe}, {eco: go, name: github.com/stripe/stripe-go}, {eco: rubygems, name: stripe}, {eco: composer, name: stripe/stripe-php}, {eco: maven, name: "com.stripe:stripe-java"}, {eco: nuget, name: stripe.net}]
base: /v1
verbs: {create: POST, retrieve: "GET/{id}", update: "POST/{id}", del: "DELETE/{id}", list: GET, cancel: "POST/{id}/cancel", capture: "POST/{id}/capture"}
- name: github
+ title: GitHub
hosts: [api.github.com]
spec: https://raw.githubusercontent.com/github/rest-api-description/main/descriptions/api.github.com/api.github.com.json
sdks: [{eco: npm, name: "@octokit/rest"}, {eco: go, name: github.com/google/go-github}, {eco: pip, name: PyGithub}, {eco: rubygems, name: octokit}]
sunset: x-github.removalDate
- name: openai
+ title: OpenAI
hosts: [api.openai.com]
spec: https://raw.githubusercontent.com/openai/openai-openapi/main/openapi.yaml
sdks: [{eco: npm, name: openai}, {eco: pip, name: openai}, {eco: go, name: github.com/openai/openai-go}]
base: /v1
verbs: {create: POST, retrieve: "GET/{id}", list: GET, del: "DELETE/{id}", cancel: "POST/{id}/cancel"}
- name: twilio
+ title: Twilio
hosts: [api.twilio.com]
spec: https://raw.githubusercontent.com/twilio/twilio-oai/main/spec/json/twilio_api_v2010.json
sdks: [{eco: npm, name: twilio}, {eco: pip, name: twilio}, {eco: go, name: github.com/twilio/twilio-go}, {eco: rubygems, name: twilio-ruby}]
- name: sendgrid
+ title: SendGrid
hosts: [api.sendgrid.com]
spec: https://raw.githubusercontent.com/twilio/sendgrid-oai/main/spec/json/tsg_mail_v3.json
sdks: [{eco: npm, name: "@sendgrid/mail"}, {eco: pip, name: sendgrid}]
- name: plaid
+ title: Plaid
hosts: [production.plaid.com, sandbox.plaid.com]
spec: https://raw.githubusercontent.com/plaid/plaid-openapi/master/2020-09-14.yml
sdks: [{eco: npm, name: plaid}, {eco: pip, name: plaid-python}, {eco: go, name: github.com/plaid/plaid-go}]
- name: digitalocean
+ title: DigitalOcean
hosts: [api.digitalocean.com]
spec: https://api-engineering.nyc3.digitaloceanspaces.com/spec-ci/DigitalOcean-public.v2.yaml
sdks: [{eco: go, name: github.com/digitalocean/godo}, {eco: pip, name: pydo}]
- name: cloudflare
+ title: Cloudflare
hosts: [api.cloudflare.com]
spec: https://raw.githubusercontent.com/cloudflare/api-schemas/main/openapi.json
sdks: [{eco: npm, name: cloudflare}, {eco: go, name: github.com/cloudflare/cloudflare-go}, {eco: pip, name: cloudflare}]
- name: datadog
+ title: Datadog
hosts: [api.datadoghq.com]
spec: https://raw.githubusercontent.com/DataDog/datadog-api-client-go/master/.generator/schemas/v1/openapi.yaml
sdks: [{eco: go, name: github.com/DataDog/datadog-api-client-go}, {eco: pip, name: datadog-api-client}]
diff --git a/internal/cli/baseline.go b/internal/cli/baseline.go
new file mode 100644
index 0000000..f6acfe8
--- /dev/null
+++ b/internal/cli/baseline.go
@@ -0,0 +1,240 @@
+package cli
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/mohsensc/tend-cli/internal/core"
+ "github.com/mohsensc/tend-cli/internal/gitx"
+ "github.com/mohsensc/tend-cli/internal/model"
+ "github.com/mohsensc/tend-cli/internal/patch"
+ "github.com/mohsensc/tend-cli/internal/scan"
+ "github.com/mohsensc/tend-cli/internal/verify"
+)
+
+// probeTimeout bounds loading one module or running one check on the base.
+const probeTimeout = 2 * time.Minute
+
+// groundwork gives the first catch-up PR a test baseline when the project's
+// tests are too thin to prove the catch-up by, before anything else is
+// made: the modules that load on the base commit, loaded again by a smoke
+// test; the typecheck its ecosystem offers when it passes on the base; and
+// tests a model writes of how the files the catch-up changes behave now.
+// Whatever does not pass on the base is left out. The baseline goes into
+// the trial's commands and becomes the base the patch is proven against.
+// It is nil when the tests are not thin, or tend cannot add a baseline.
+func (r *runner) groundwork(ctx context.Context, ch *core.Change, t *trial) (*part, error) {
+ s, wt := r.s, r.wt
+ files := touched(ch.Batch)
+ why := weak(t.cmds, r.inv.Index, files)
+ if why == "" || len(ch.Batch.Changes)+len(ch.Batch.Next) == 0 {
+ return nil, nil
+ }
+ su := r.suite()
+ if su == nil {
+ s.logf("the tests are thin (%s), and tend has no way to add a baseline for this project", why)
+ return nil, nil
+ }
+ s.logf("the tests are thin (%s); adding a baseline first", why)
+ if err := reset(ctx, wt); err != nil {
+ return nil, err
+ }
+ if _, err := r.prove(ctx, core.Commands{Install: t.cmds.Install, Build: t.cmds.Build}, "baseline"); err != nil {
+ return nil, err
+ }
+ bl := &core.Baseline{Why: why}
+ pt := &core.Patch{}
+ var loaded []string
+ if su.Smoke != "" {
+ for _, m := range su.Modules {
+ if r.probe(ctx, su.Load(m)) {
+ loaded = append(loaded, m)
+ }
+ }
+ }
+ for _, c := range su.Checks {
+ if r.probe(ctx, c) {
+ bl.Checks = append(bl.Checks, c)
+ }
+ }
+ if len(loaded) > 0 {
+ if err := write(wt.Dir, su.Smoke, su.Code(loaded)); err != nil {
+ return nil, err
+ }
+ bl.Files, bl.Modules = append(bl.Files, su.Smoke), len(loaded)
+ }
+ if r.model != nil && len(files) > 0 {
+ cmds := withTest(t.cmds, runLine(su, bl, su.Tests))
+ o := r.options(nil, cmds, t.proof)
+ o.Commands = cmds
+ o.Prove = func(ctx context.Context, c core.Commands) (*core.Run, error) { return r.prove(ctx, c, "baseline") }
+ if _, ok := r.model.(model.Agent); ok {
+ o.Turns, o.Tokens = s.cfg.Model.Turns, s.cfg.Model.Tokens
+ o.Transcript = filepath.Join(s.dir, "logs", "baseline", "agent.jsonl")
+ scale(&o, min(1+len(files)/5, shareMax))
+ }
+ cpt, err := patch.Characterize(ctx, wt.Dir, patch.Bench{Path: su.Tests, Lang: su.Lang, Files: files}, o)
+ switch {
+ case err != nil && ctx.Err() != nil:
+ return nil, ctx.Err()
+ case err != nil:
+ s.logf("the model wrote no tests that pass on the base, so the baseline goes without them: %v", err)
+ if err := os.Remove(filepath.Join(wt.Dir, filepath.FromSlash(su.Tests))); err != nil && !os.IsNotExist(err) {
+ return nil, err
+ }
+ default:
+ bl.Files, bl.Model = append(bl.Files, su.Tests), true
+ pt.Model, pt.Edited, pt.Note = true, cpt.Edited, cpt.Note
+ }
+ }
+ if len(bl.Files) == 0 && len(bl.Checks) == 0 {
+ s.logf("nothing that would make a baseline passes on the base")
+ return nil, reset(ctx, wt)
+ }
+ slices.Sort(bl.Files)
+ written := slices.Clone(bl.Files)
+ line := runLine(su, bl)
+ if line != "" {
+ f, err := patch.Test(wt.Dir, t.cmds.Test, line)
+ if err != nil {
+ s.logf("cannot add the baseline to tend.yml, so there is none: %v", err)
+ return nil, reset(ctx, wt)
+ }
+ bl.Command, written = line, append(written, f)
+ }
+ pt.Applied = []string{"added a test baseline (" + strings.Join(written, ", ") + ")"}
+ cmds := withTest(t.cmds, line)
+ if _, err := gitx.Run(ctx, wt.Dir, "add", "-A"); err != nil {
+ return nil, err
+ }
+ run, err := r.prove(ctx, cmds, "base")
+ if err != nil {
+ return nil, err
+ }
+ if !run.Pass {
+ s.logf("the baseline does not pass on the base, so there is none: %s", broke(run))
+ return nil, reset(ctx, wt)
+ }
+ code, _, err := patch.Diff(ctx, wt.Dir, wt.Base)
+ if err != nil {
+ return nil, err
+ }
+ t.cmds, t.proof.Base, t.proof.Nothing = cmds, run, false
+ if line != "" {
+ r.tests = []string{line}
+ }
+ return &part{n: -1, base: bl, pt: pt, code: code}, reset(ctx, wt)
+}
+
+// weak says why the project's tests cannot prove changes to files, or ""
+// when they can: there is no test command, or a file is reached by no test.
+func weak(cmds core.Commands, idx core.ScanIndex, files []string) string {
+ if len(cmds.Test) == 0 {
+ return "there is no test command"
+ }
+ x, ok := idx.(*scan.Index)
+ if !ok {
+ return ""
+ }
+ var bare []string
+ for _, f := range files {
+ if !x.Reached(f) {
+ bare = append(bare, f)
+ }
+ }
+ switch len(bare) {
+ case 0:
+ return ""
+ case 1:
+ return "no test reaches `" + bare[0] + "`, which the catch-up changes"
+ }
+ return fmt.Sprintf("no test reaches %d of the %d files the catch-up changes", len(bare), len(files))
+}
+
+// touched lists the code files outside tests that the changes in b, made
+// now or in a later stage, call into.
+func touched(b *core.Batch) []string {
+ var res []string
+ add := func(ch *core.Change) {
+ for _, s := range core.Calls(ch) {
+ if scan.Lang(s.File) != "" && !scan.IsTest(s.File) && !slices.Contains(res, s.File) {
+ res = append(res, s.File)
+ }
+ }
+ }
+ for i := range b.Changes {
+ add(&b.Changes[i])
+ }
+ for i := range b.Next {
+ add(&b.Next[i].Change)
+ }
+ slices.Sort(res)
+ return res
+}
+
+// suite is where the project's generated tests go: the manifest nearest
+// the root whose ecosystem can run any, an example's or a fixture's
+// package.json never ahead of the project's own.
+func (r *runner) suite() *core.Suite {
+ ms := slices.Clone(r.inv.Manifests)
+ slices.SortStableFunc(ms, func(a, b core.Manifest) int {
+ return strings.Count(a.Path, "/") - strings.Count(b.Path, "/")
+ })
+ for _, m := range ms {
+ if b, ok := r.ecos[m.Ecosystem].(core.Baseliner); ok {
+ if su := b.Suite(r.wt.Dir, m); su != nil {
+ return su
+ }
+ }
+ }
+ return nil
+}
+
+// runLine is the test line that runs the baseline's files and those in
+// more, after its checks, "" when the project's own test lines run them.
+func runLine(su *core.Suite, bl *core.Baseline, more ...string) string {
+ var lines []string
+ lines = append(lines, bl.Checks...)
+ if files := append(slices.Clone(bl.Files), more...); len(files) > 0 {
+ if l := su.Run(files); l != "" {
+ lines = append(lines, l)
+ }
+ }
+ return strings.Join(lines, " && ")
+}
+
+func withTest(cmds core.Commands, line string) core.Commands {
+ if line != "" {
+ cmds.Test = append(slices.Clone(cmds.Test), line)
+ }
+ return cmds
+}
+
+// probe runs one line on the worktree as it is and says whether it passed.
+func (r *runner) probe(ctx context.Context, line string) bool {
+ cfg := r.s.cfg.Verify
+ run, err := verify.Run(ctx, r.wt, verify.Options{
+ Commands: core.Commands{Test: []string{line}},
+ Timeout: probeTimeout,
+ Container: cfg.Container,
+ Env: cfg.Env,
+ LogDir: r.logs("probe"),
+ })
+ if err == nil {
+ err = discard(ctx, r.wt)
+ }
+ return err == nil && run.Pass
+}
+
+func write(dir, rel, body string) error {
+ p := filepath.Join(dir, filepath.FromSlash(rel))
+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
+ return err
+ }
+ return os.WriteFile(p, []byte(body), 0o644)
+}
diff --git a/internal/cli/catchup_test.go b/internal/cli/catchup_test.go
new file mode 100644
index 0000000..8acb295
--- /dev/null
+++ b/internal/cli/catchup_test.go
@@ -0,0 +1,204 @@
+package cli
+
+import (
+ "bytes"
+ "context"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/mohsensc/tend-cli/internal/config"
+ "github.com/mohsensc/tend-cli/internal/core"
+ "github.com/mohsensc/tend-cli/internal/deliver"
+ "github.com/mohsensc/tend-cli/internal/gitx"
+ "github.com/mohsensc/tend-cli/internal/plan"
+ "github.com/mohsensc/tend-cli/internal/scan"
+ "github.com/mohsensc/tend-cli/internal/state"
+ "github.com/mohsensc/tend-cli/internal/verify"
+)
+
+// Tests are weak with no test command, or when a file the catch-up changes
+// is reached by no test; a test of every such file is enough.
+func TestWeak(t *testing.T) {
+ root := t.TempDir()
+ for name, body := range map[string]string{
+ "src/app.js": "module.exports = {}\n",
+ "src/client.js": "module.exports = {}\n",
+ "test/app.test.js": "require('../src/app')\n",
+ } {
+ p := filepath.Join(root, filepath.FromSlash(name))
+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ idx, err := scan.Build(scan.Options{Root: root})
+ if err != nil {
+ t.Fatal(err)
+ }
+ tests := core.Commands{Test: []string{"npm test"}}
+ for _, tt := range []struct {
+ name string
+ cmds core.Commands
+ files []string
+ want string
+ }{
+ {"no test command", core.Commands{}, []string{"src/app.js"}, "there is no test command"},
+ {"every file reached", tests, []string{"src/app.js"}, ""},
+ {"one not reached", tests, []string{"src/app.js", "src/client.js"}, "no test reaches `src/client.js`, which the catch-up changes"},
+ {"nothing changes", tests, nil, ""},
+ } {
+ if got := weak(tt.cmds, idx, tt.files); got != tt.want {
+ t.Errorf("%s: %q, want %q", tt.name, got, tt.want)
+ }
+ }
+ b := &core.Batch{
+ Changes: []core.Change{{Deps: []core.Dep{{Manifest: core.Manifest{Path: "package.json"}}}, Sites: []core.Site{{File: "package.json", Line: 3}, {File: "src/app.js", Line: 1}, {File: "test/app.test.js", Line: 1}}}},
+ Next: []core.Later{{Change: core.Change{Sites: []core.Site{{File: "src/client.js", Line: 2}, {File: "Dockerfile", Line: 1}}}}},
+ }
+ if got := touched(b); strings.Join(got, " ") != "src/app.js src/client.js" {
+ t.Errorf("touched = %q", got)
+ }
+}
+
+// Once the first PR merged, each run opens the next stage, and the one that
+// finds none left ends the catch-up. A state from before stages, or one
+// whose catch-up is over, opens none.
+func TestStaged(t *testing.T) {
+ major := core.Change{ID: "npm/b@3.0.0", Kind: core.Breaking, Level: "major", Deps: []core.Dep{{Ecosystem: core.Npm, Name: "b", Version: "1.0.0"}}, To: "3.0.0"}
+ p := &plan.Plan{Queue: []core.Change{major}}
+ for _, tt := range []struct {
+ name string
+ stage int
+ queue *plan.Plan
+ want string
+ stageThen int
+ }{
+ {"next stage", plan.Fixes, p, core.StageID(plan.Majors), plan.Fixes},
+ {"nothing left", plan.Majors, p, "", plan.Last},
+ {"before stages", 0, p, "", 0},
+ {"over", plan.Last, p, "", plan.Last},
+ } {
+ s := &session{e: Env{Stderr: &bytes.Buffer{}}, st: state.New()}
+ s.st.Stage = tt.stage
+ ch := s.staged(tt.queue)
+ got := ""
+ if ch != nil {
+ got = ch.ID
+ }
+ if got != tt.want || s.st.Stage != tt.stageThen {
+ t.Errorf("%s: %q, stage %d; want %q, %d", tt.name, got, s.st.Stage, tt.want, tt.stageThen)
+ }
+ }
+}
+
+// The tracking issue lists what failed on this base, what was reverted and
+// what has no known replacement; it is opened, left alone while nothing
+// changes, and closed once the list is empty.
+func TestTrack(t *testing.T) {
+ ctx := context.Background()
+ f := deliver.NewFake("acme", "shop", "main")
+ var errs bytes.Buffer
+ s := &session{e: Env{Stderr: &errs}, cfg: config.Default(), st: state.New(), forge: f}
+ now := time.Now()
+ s.st.Fail("npm/a@2.0.0", "npm test failed (exit 1)\nmore", "base1", now)
+ s.st.Fail("npm/old@2.0.0", "npm test failed", "base0", now)
+ s.st.Parked["npm/b@3.0.0"] = state.Parked{Reason: "reverted", Detail: "reverted in abc1234: CI failed on def5678 (test)"}
+ s.st.Parked["npm/c@1.0.0"] = state.Parked{Reason: "rejected"}
+ p := &plan.Plan{Queue: []core.Change{{ID: "npm/moment@", Kind: core.Deprecation, Deps: []core.Dep{{Name: "moment"}}}}}
+
+ s.track(ctx, p, "base1")
+ is := f.Issues()
+ if len(is) != 1 || !is[0].Open {
+ t.Fatalf("issues = %+v", is)
+ }
+ for _, want := range []string{
+ "- `npm/a@2.0.0`: could not be made or proven on base1: npm test failed (exit 1)\n",
+ "- `npm/b@3.0.0`: reverted in abc1234: CI failed on def5678 (test)\n",
+ "- `moment`: deprecated, and tend knows no replacement for it, so it stays\n",
+ trackMarker,
+ } {
+ if !strings.Contains(is[0].Body, want) {
+ t.Errorf("the issue lacks %q:\n%s", want, is[0].Body)
+ }
+ }
+ if strings.Contains(is[0].Body, "npm/old") || strings.Contains(is[0].Body, "npm/c@") {
+ t.Errorf("the issue lists what failed on another base or a maintainer closed:\n%s", is[0].Body)
+ }
+
+ // Nothing new: the forge is not asked, so its failing goes unnoticed.
+ f.Err = context.Canceled
+ s.track(ctx, p, "base1")
+ f.Err = nil
+ if strings.Contains(errs.String(), "cannot") {
+ t.Errorf("a run with nothing new asked the forge: %s", errs.String())
+ }
+
+ delete(s.st.Seen, "npm/a@2.0.0")
+ delete(s.st.Parked, "npm/b@3.0.0")
+ s.track(ctx, &plan.Plan{}, "base1")
+ if is := f.Issues(); len(is) != 1 || is[0].Open || !strings.HasPrefix(is[0].Body, "Everything tend listed here is done") {
+ t.Errorf("after the list emptied: %+v", is)
+ }
+ if !strings.Contains(errs.String(), "closed #1000") {
+ t.Errorf("logged %q", errs.String())
+ }
+
+ // Lost state finds the issue by its marker and opens it again.
+ s.st = state.New()
+ s.st.Fail("npm/a@2.0.0", "npm test failed", "base2", now)
+ s.track(ctx, &plan.Plan{}, "base2")
+ if is := f.Issues(); len(is) != 1 || !is[0].Open || !strings.Contains(is[0].Body, "npm/a@2.0.0") {
+ t.Errorf("after losing state: %+v", is)
+ }
+}
+
+// Each part of a catch-up PR is made on top of the baseline the PR adds, so
+// the baseline's test line finds its files; and the baseline is staged, so
+// the clean-up after a run leaves it.
+func TestRestart(t *testing.T) {
+ need := func(tool string) {
+ if _, err := exec.LookPath(tool); err != nil {
+ t.Skip(tool + " not found")
+ }
+ }
+ need("git")
+ ctx := context.Background()
+ dir := t.TempDir()
+ t.Setenv("GIT_CONFIG_GLOBAL", os.DevNull)
+ for _, args := range [][]string{{"init", "-q"}, {"commit", "-q", "--allow-empty", "-m", "base"}} {
+ if _, err := gitx.Run(ctx, dir, append([]string{"-c", "user.name=t", "-c", "user.email=t@example.com"}, args...)...); err != nil {
+ t.Fatal(err)
+ }
+ }
+ base, err := gitx.Run(ctx, dir, "rev-parse", "HEAD")
+ if err != nil {
+ t.Fatal(err)
+ }
+ r := &runner{wt: &verify.Worktree{Dir: dir, Base: base}}
+ floor := "diff --git a/test/tend/smoke.js b/test/tend/smoke.js\nnew file mode 100644\n--- /dev/null\n+++ b/test/tend/smoke.js\n@@ -0,0 +1 @@\n+require('node:test')\n"
+ if err := os.WriteFile(filepath.Join(dir, "left-over.js"), []byte("x\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := r.restart(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(filepath.Join(dir, "left-over.js")); err == nil {
+ t.Error("restart left a file behind")
+ }
+ r.floor = floor
+ if err := r.restart(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if err := discard(ctx, r.wt); err != nil {
+ t.Fatal(err)
+ }
+ if b, err := os.ReadFile(filepath.Join(dir, "test", "tend", "smoke.js")); err != nil || string(b) != "require('node:test')\n" {
+ t.Errorf("the baseline is not there after a run's clean-up: %q, %v", b, err)
+ }
+}
diff --git a/internal/cli/ci.go b/internal/cli/ci.go
new file mode 100644
index 0000000..0167888
--- /dev/null
+++ b/internal/cli/ci.go
@@ -0,0 +1,182 @@
+package cli
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/mohsensc/tend-cli/internal/core"
+ "github.com/mohsensc/tend-cli/internal/deliver"
+ "github.com/mohsensc/tend-cli/internal/gitx"
+ "github.com/mohsensc/tend-cli/internal/plan"
+ "github.com/mohsensc/tend-cli/internal/state"
+ "github.com/mohsensc/tend-cli/internal/verify"
+)
+
+// ciWait is how long tend waits for the repository's CI on a commit it
+// pushed before it takes no answer as no CI.
+const ciWait = 6 * time.Hour
+
+// settleCommit closes the books on a change delivered as a commit: it is on
+// the branch and the repository's CI passed it or has none, or someone took
+// it off again. While that CI still runs, the run waits on it. When it
+// failed on the commit and not on the one before, tend reverts its commit.
+// It returns the run's outcome when there is nothing more for it to do.
+func (s *session) settleCommit(ctx context.Context) (*outcome, error) {
+ o := s.st.Open
+ if o == nil || o.PR != 0 || s.o.dryRun {
+ return nil, nil
+ }
+ if s.remote == "" || o.Commit == "" {
+ s.st.Open = nil
+ return nil, nil
+ }
+ if err := s.push.Fetch(ctx, o.Branch); err != nil {
+ s.logf("cannot fetch %s to look for %s: %v", o.Branch, core.Short(o.Commit), err)
+ return nil, nil
+ }
+ ref := "refs/remotes/" + s.remote + "/" + o.Branch
+ if _, err := gitx.Run(ctx, s.root, "merge-base", "--is-ancestor", o.Commit, ref); err != nil {
+ s.st.Open = nil
+ s.st.Parked[o.ID] = state.Parked{Reason: "rejected", To: core.TargetOf(o.ID), At: s.e.Now()}
+ if core.CatchUp(o.ID) {
+ s.st.Stage = plan.Last
+ }
+ return nil, nil
+ }
+ ci, err := s.checks(ctx, o.Commit)
+ waited := s.e.Now().Sub(o.At)
+ switch {
+ case err != nil && waited < ciWait:
+ s.logf("cannot read CI on %s: %v", core.Short(o.Commit), err)
+ return &outcome{Action: "waiting", line: fmt.Sprintf("waiting to read CI on %s, which tend pushed to %s", core.Short(o.Commit), o.Branch)}, nil
+ case err != nil:
+ s.logf("cannot read CI on %s after %s, so tend takes it as passed: %v", core.Short(o.Commit), ciWait, err)
+ case ci.State == "pending" && waited < ciWait:
+ return &outcome{Action: "waiting", line: fmt.Sprintf("waiting on CI for %s, which tend pushed to %s", core.Short(o.Commit), o.Branch)}, nil
+ case ci.State == "pending":
+ s.logf("CI on %s has not finished after %s, so tend takes it as passed", core.Short(o.Commit), ciWait)
+ case ci.State == "failure":
+ before, err := s.checks(ctx, o.Commit+"^")
+ if err == nil && before.State == "failure" {
+ s.logf("CI fails on %s, as it did on the commit before it, so tend's change is not what broke it", core.Short(o.Commit))
+ break
+ }
+ return s.revert(ctx, o, ci)
+ }
+ s.st.Open = nil
+ s.st.See(o.ID, "delivered", "", s.e.Now())
+ s.landed(o)
+ return nil, nil
+}
+
+// landed moves the catch-up on once a catch-up commit is in.
+func (s *session) landed(o *state.OpenPR) {
+ if !core.CatchUp(o.ID) {
+ return
+ }
+ if o.ID == core.FirstID {
+ s.st.Onboard = "merged"
+ }
+ s.st.Stage = max(s.st.Stage, o.Stage)
+}
+
+// checks is what the repository's CI made of a commit, none when the forge
+// cannot say.
+func (s *session) checks(ctx context.Context, rev string) (core.CI, error) {
+ c, ok := s.forge.(core.Checks)
+ if !ok {
+ return core.CI{State: "none"}, nil
+ }
+ sha, err := gitx.Run(ctx, s.root, "rev-parse", "--verify", rev+"^{commit}")
+ if err != nil {
+ return core.CI{}, err
+ }
+ return c.Checks(ctx, sha)
+}
+
+// revert takes back the commit tend pushed for o, which CI failed: a revert
+// on the branch's tip, proven first unless it puts back the very tree the
+// commit started from, and pushed with a message that says why. The change
+// is parked at its target, so a newer release starts over; a catch-up
+// commit ends the catch-up, and its changes come back one at a time.
+func (s *session) revert(ctx context.Context, o *state.OpenPR, ci core.CI) (*outcome, error) {
+ short := core.Short(o.Commit)
+ failed := strings.Join(ci.Failed, ", ")
+ tip, err := gitx.Run(ctx, s.root, "rev-parse", "--verify", "refs/remotes/"+s.remote+"/"+o.Branch+"^{commit}")
+ if err != nil {
+ return nil, err
+ }
+ wt, err := verify.Checkout(ctx, s.root, filepath.Join(s.dir, "wt", "revert-"+dirName(tip)), tip)
+ if err != nil {
+ return nil, fmt.Errorf("cannot create the worktree: %w", err)
+ }
+ defer func() {
+ if err := wt.Remove(context.WithoutCancel(ctx)); err != nil {
+ s.logf("cannot remove the worktree %s: %v", wt.Dir, err)
+ }
+ }()
+ park := func(detail string) {
+ s.st.Parked[o.ID] = state.Parked{Reason: "reverted", To: core.TargetOf(o.ID), At: s.e.Now(), Detail: detail}
+ s.st.See(o.ID, "parked", detail, s.e.Now())
+ if core.CatchUp(o.ID) {
+ s.landed(o)
+ s.st.Stage = plan.Last
+ }
+ s.st.Open = nil
+ }
+ if _, err := gitx.Run(ctx, wt.Dir, "revert", "--no-commit", o.Commit); err != nil {
+ park(fmt.Sprintf("CI failed on %s (%s), and reverting it does not apply cleanly; revert it by hand", short, failed))
+ return &outcome{Action: "unproven", line: fmt.Sprintf("CI fails on %s and tend cannot revert it cleanly", short), code: exitUnproven}, nil
+ }
+ if _, err := gitx.Run(ctx, wt.Dir, "add", "-A"); err != nil {
+ return nil, err
+ }
+ tree, err := gitx.Run(ctx, wt.Dir, "write-tree")
+ if err != nil {
+ return nil, err
+ }
+ before, err := gitx.Run(ctx, wt.Dir, "rev-parse", o.Commit+"^^{tree}")
+ if err != nil {
+ return nil, err
+ }
+ // Commits landed on top of tend's since: the revert is a new tree, and
+ // is proven like any other.
+ if tree != before {
+ inv, _, err := plan.Inventory(wt.Dir, s.cfg)
+ if err != nil {
+ return nil, err
+ }
+ r := &runner{s: s, wt: wt, inv: inv, ecos: ecosFor(s.cfg), slug: "revert"}
+ run, err := r.prove(ctx, r.detect(), "revert")
+ if err != nil {
+ return nil, err
+ }
+ if !run.Pass {
+ park(fmt.Sprintf("CI failed on %s (%s), and the revert does not pass the project's commands either: %s; revert it by hand", short, failed, broke(run)))
+ return &outcome{Action: "unproven", line: fmt.Sprintf("CI fails on %s and its revert fails too", short), code: exitUnproven}, nil
+ }
+ }
+ subject, err := gitx.Run(ctx, s.root, "log", "-1", "--format=%s", o.Commit)
+ if err != nil {
+ return nil, err
+ }
+ msg := fmt.Sprintf("Revert %q\n\nCI failed on %s: %s. tend proved that commit with the project's own\ncommands, but the repository's CI did not pass it, so tend takes it back\nand will not try %s again; a newer release starts over.\n\nThis reverts commit %s.",
+ subject, short, failed, o.ID, o.Commit)
+ if _, err := wt.Commit(ctx, msg, verify.AuthorFrom(s.root, s.e.Getenv), false); err != nil {
+ return nil, err
+ }
+ sha, err := deliver.Commit(ctx, wt, s.push, o.Branch)
+ switch {
+ case errors.Is(err, deliver.ErrMoved):
+ return &outcome{Action: "moved", line: err.Error() + "; the next run reverts on the new tip"}, nil
+ case err != nil:
+ return nil, err
+ }
+ park(fmt.Sprintf("reverted in %s: CI failed on %s (%s)", core.Short(sha), short, failed))
+ s.logf("CI failed on %s (%s); reverted it in %s", short, failed, core.Short(sha))
+ return &outcome{Action: "reverted", Commit: sha, Branch: o.Branch, line: fmt.Sprintf("reverted %s on %s: CI failed (%s)", short, o.Branch, failed)}, nil
+}
diff --git a/internal/cli/climb.go b/internal/cli/climb.go
new file mode 100644
index 0000000..7852e77
--- /dev/null
+++ b/internal/cli/climb.go
@@ -0,0 +1,237 @@
+package cli
+
+import (
+ "context"
+ "fmt"
+ "slices"
+ "strings"
+
+ "github.com/mohsensc/tend-cli/internal/core"
+ "github.com/mohsensc/tend-cli/internal/deliver"
+ "github.com/mohsensc/tend-cli/internal/gitx"
+ "github.com/mohsensc/tend-cli/internal/patch"
+ "github.com/mohsensc/tend-cli/internal/plan"
+ "github.com/mohsensc/tend-cli/internal/scan"
+ "github.com/mohsensc/tend-cli/internal/ver"
+ "github.com/mohsensc/tend-cli/internal/verify"
+)
+
+// shareMax caps how many times its configured budget a model gets for one
+// piece of work.
+const shareMax = 5
+
+// shares is the budget a change asks for: one share, and one more for each
+// Spread call sites it moves.
+func shares(ch *core.Change) int {
+ if ch == nil {
+ return 1
+ }
+ return min(1+len(core.Calls(ch))/plan.Spread, shareMax)
+}
+
+// scale multiplies a model's turns and tokens by n; no limit stays none.
+func scale(o *patch.Options, n int) {
+ o.Turns *= n
+ o.Tokens *= n
+}
+
+// decide makes ch by each option plan.Ranked lets tend take on its own, in
+// that order, and keeps the first its proof passes: the change with the
+// option it took and why, and its patch. Each option before it that failed
+// is named in the why. It returns nil when none passed, with the worktree
+// back on the base.
+func (r *runner) decide(ctx context.Context, ch *core.Change, cmds core.Commands, proof *core.Proof, left *int) (*core.Change, *core.Patch, error) {
+ var failed []string
+ for _, t := range plan.Ranked(ch, r.inv.Deps) {
+ if left != nil && *left <= 0 {
+ break
+ }
+ if err := r.restart(ctx); err != nil {
+ return nil, nil, err
+ }
+ c := *ch
+ c.Choice = &core.Choice{N: t.N, Why: t.Why}
+ r.s.logf("trying option %d of %s on its own: %s", t.N, name(&part{ch: ch}), c.Options[t.N-1].Title)
+ pt, err := r.attempt(ctx, &c, cmds, proof)
+ if left != nil && err == nil && !pt.Decision && !proof.Nothing {
+ *left--
+ }
+ switch {
+ case err != nil && ctx.Err() != nil:
+ return nil, nil, ctx.Err()
+ case err != nil:
+ first, _, _ := strings.Cut(err.Error(), "\n")
+ failed = append(failed, fmt.Sprintf("option %d could not be made (%s)", t.N, first))
+ case pt.Decision:
+ failed = append(failed, fmt.Sprintf("option %d could not be made (%s)", t.N, deliver.Clause(pt.Note)))
+ case len(pt.Files) == 0:
+ failed = append(failed, fmt.Sprintf("option %d changes no files", t.N))
+ case !proof.Nothing && !plan.Proven(proof):
+ failed = append(failed, fmt.Sprintf("with option %d, %s", t.N, broke(proof.Patched)))
+ default:
+ if len(failed) > 0 {
+ c.Choice.Why = "the first its proof passed, " + t.Why + "; " + strings.Join(failed, ", ")
+ }
+ return &c, pt, nil
+ }
+ }
+ return nil, nil, r.restart(ctx)
+}
+
+// climb moves ch up its steps a major at a time, for when the jump to its
+// target fails: each step is bumped on top of the last, migrated, proven,
+// and marked with a commit in the worktree, so the next step reads its
+// call sites from it. It stops at the first step that fails and returns
+// the change as far as it got, with the steps it climbed through in Via,
+// its patch staged against the base and the run that proved it, or a nil
+// change when not even the first step passed. why says where it stopped.
+func (r *runner) climb(ctx context.Context, ch *core.Change, cmds core.Commands, proof *core.Proof, left *int) (*core.Change, *core.Patch, *core.Run, string, error) {
+ wt := r.wt
+ if err := r.restart(ctx); err != nil {
+ return nil, nil, nil, "", err
+ }
+ var done []string
+ var run *core.Run
+ res := &core.Patch{}
+ why := ""
+ deps, sites, idx := ch.Deps, ch.Sites, r.inv.Index
+ for _, to := range append(slices.Clone(ch.Steps), ch.To) {
+ if left != nil && *left <= 0 {
+ why = "the proofs ran out"
+ break
+ }
+ c := rung(ch, deps, sites, to)
+ r.s.logf("climbing %s to %s", name(&part{ch: ch}), to)
+ o := r.options(&c, cmds, proof)
+ o.Index = idx
+ pt, err := patch.Apply(ctx, wt.Dir, &c, o)
+ switch {
+ case err != nil && ctx.Err() != nil:
+ return nil, nil, nil, "", ctx.Err()
+ case err != nil:
+ why, _, _ = strings.Cut(err.Error(), "\n")
+ case pt.Decision:
+ why = pt.Note
+ case len(pt.Files) == 0:
+ why = "the step changes no files"
+ }
+ if why != "" {
+ why = to + ": " + deliver.Clause(why)
+ break
+ }
+ rr, err := r.prove(ctx, cmds, "patched")
+ if err != nil {
+ return nil, nil, nil, "", err
+ }
+ if left != nil {
+ *left--
+ }
+ if !plan.Proven(&core.Proof{Base: proof.Base, Patched: rr}) {
+ why = "with " + to + ", " + broke(rr)
+ break
+ }
+ if _, err := wt.Commit(ctx, "climb to "+to, verify.Author{Name: "tend", Email: "tend@localhost"}, true); err != nil {
+ return nil, nil, nil, "", err
+ }
+ done, run = append(done, to), rr
+ res.Applied = append(res.Applied, pt.Applied...)
+ res.Model = res.Model || pt.Model
+ res.Edited = append(res.Edited, pt.Edited...)
+ res.Note = pt.Note
+ if deps, err = r.reread(deps); err != nil {
+ return nil, nil, nil, "", err
+ }
+ if x, err := scan.Build(scan.Options{Root: wt.Dir}); err == nil {
+ idx = x
+ sites = r.uses(x, deps)
+ }
+ }
+ // What failed goes; what climbed stays staged, on the base.
+ for _, args := range [][]string{{"reset", "--quiet", "--hard", "HEAD"}, {"clean", "--quiet", "--force", "-d"}, {"reset", "--quiet", "--soft", wt.Base}} {
+ if _, err := gitx.Run(ctx, wt.Dir, args...); err != nil {
+ return nil, nil, nil, "", err
+ }
+ }
+ if len(done) == 0 {
+ return nil, nil, nil, why, r.restart(ctx)
+ }
+ var err error
+ if res.Diff, res.Files, err = patch.Diff(ctx, wt.Dir, wt.Base); err != nil {
+ return nil, nil, nil, "", err
+ }
+ slices.Sort(res.Edited)
+ res.Edited = slices.Compact(res.Edited)
+ c := *ch
+ c.To, c.Via = done[len(done)-1], done[:len(done)-1]
+ c.Level = ver.Step(plan.Lowest(ch.Deps), c.To)
+ return &c, res, run, why, nil
+}
+
+// rung is ch as one step of a climb: from deps, as the last step left them,
+// to to, with the call sites as they read now and only the release notes of
+// the releases the step crosses.
+func rung(ch *core.Change, deps []core.Dep, sites []core.Site, to string) core.Change {
+ c := *ch
+ from := plan.Lowest(deps)
+ c.Deps, c.Sites, c.To, c.Steps = deps, sites, to, nil
+ c.Level = ver.Step(from, to)
+ c.Evidence = nil
+ for _, ev := range ch.Evidence {
+ if v, ok := noted(ev); !ok || ver.Less(from, v) && !ver.Less(to, v) {
+ c.Evidence = append(c.Evidence, ev)
+ }
+ }
+ return c
+}
+
+// noted is the release a piece of release notes is about, from its title:
+// "v16.0.0", "stripe@16.0.0 Big release".
+func noted(ev core.Evidence) (string, bool) {
+ if ev.Source != "releases" && ev.Source != "changelog" {
+ return "", false
+ }
+ f := strings.Fields(ev.Title)
+ if len(f) == 0 {
+ return "", false
+ }
+ v := f[0][strings.LastIndexByte(f[0], '@')+1:]
+ _, ok := ver.Parse(v)
+ return v, ok
+}
+
+// reread reads deps again from their manifests in the worktree, as a bump
+// left them.
+func (r *runner) reread(deps []core.Dep) ([]core.Dep, error) {
+ var res []core.Dep
+ for _, d := range deps {
+ e := r.ecos[d.Ecosystem]
+ if e == nil {
+ res = append(res, d)
+ continue
+ }
+ all, err := e.Deps(r.wt.Dir, d.Manifest)
+ if err != nil {
+ return nil, err
+ }
+ i := slices.IndexFunc(all, func(x core.Dep) bool { return x.Name == d.Name && x.Direct == d.Direct })
+ if i < 0 {
+ res = append(res, d)
+ continue
+ }
+ res = append(res, all[i])
+ }
+ return res, nil
+}
+
+// uses are the call sites of deps in idx.
+func (r *runner) uses(idx core.ScanIndex, deps []core.Dep) []core.Site {
+ var res []core.Site
+ for _, d := range deps {
+ if e := r.ecos[d.Ecosystem]; e != nil {
+ if imps := e.Imports(d); len(imps) > 0 {
+ res = append(res, idx.Uses(imps)...)
+ }
+ }
+ }
+ return res
+}
diff --git a/internal/cli/init.go b/internal/cli/init.go
index e9bda1d..387f67d 100644
--- a/internal/cli/init.go
+++ b/internal/cli/init.go
@@ -22,8 +22,9 @@ import (
// checkout keeps no token in the repository's config, where the project's
// own commands could read it; tend is handed the token itself. PRs opened
// with the default token do not trigger other workflows; a fine-grained or
-// App token changes that. TEND_MODEL_KEY holds the key for whichever model
-// provider tend.yml names.
+// App token changes that. Issues are for tend's tracking issue, and checks
+// and statuses for reading CI on what commit mode pushed. TEND_MODEL_KEY
+// holds the key for whichever model provider tend.yml names.
const workflow = `name: tend
on:
push:
@@ -31,7 +32,7 @@ on:
paths: [.github/workflows/tend.yml]
schedule: [{cron: %q}]
workflow_dispatch:
-permissions: {contents: write, pull-requests: write}
+permissions: {contents: write, pull-requests: write, issues: write, checks: read, statuses: read}
concurrency: {group: tend, cancel-in-progress: false}
jobs:
tend:
diff --git a/internal/cli/onboard.go b/internal/cli/onboard.go
index b5f6e29..1dadbef 100644
--- a/internal/cli/onboard.go
+++ b/internal/cli/onboard.go
@@ -1,6 +1,7 @@
package cli
import (
+ "cmp"
"context"
"errors"
"fmt"
@@ -17,14 +18,14 @@ import (
"github.com/mohsensc/tend-cli/internal/patch"
"github.com/mohsensc/tend-cli/internal/plan"
"github.com/mohsensc/tend-cli/internal/state"
- "github.com/mohsensc/tend-cli/internal/verify"
)
// due is st.Onboard while tend's first PR is coming or open.
const due = "due"
-// onboard puts tend's first PR on the repo, the tidy-up, into the queue when
-// this run should carry it. Only security work goes ahead of it.
+// onboard puts tend's first PR on the repo into the queue when this run
+// should carry it. Nothing goes ahead of it: it carries the security fixes
+// it can make, and the rest of the queue waits for it.
func (s *session) onboard(ctx context.Context, inv *core.Inventory, p *plan.Plan, base string) error {
ch, err := s.onboarding(ctx, inv, p, base)
if err != nil || ch == nil {
@@ -35,33 +36,39 @@ func (s *session) onboard(ctx context.Context, inv *core.Inventory, p *plan.Plan
return nil
}
-// onboarding returns the tidy-up when it is due, nil when not, and settles
-// st.Onboard once the first PR is behind the repo: it merged or was closed,
-// tend.yml asks for none, there was nothing to tidy, or tend had been at
-// work here before. The forge is the truth: a lost state still finds the PR.
+// onboarding returns the catch-up PR when one is due, nil when not: the
+// first PR, then once it merged the stages after it. It settles st.Onboard
+// once the first PR is behind the repo: it merged or was closed, tend.yml
+// asks for none, there was nothing to catch up on, or tend had been at work
+// here before. The forge is the truth: a lost state still finds the PR.
func (s *session) onboarding(ctx context.Context, inv *core.Inventory, p *plan.Plan, base string) (*core.Change, error) {
st := s.st
switch {
+ case st.Onboard == "merged":
+ return s.staged(p), nil
case st.Onboard != "" && st.Onboard != due:
return nil, nil
- case s.cfg.Onboarding != "pr" || s.cfg.Deliver.Mode != "pr":
+ case s.cfg.Onboarding != "pr":
if st.Onboard == "" {
s.quiet(inv, p)
}
st.Onboard = s.cfg.Onboarding
- if s.cfg.Onboarding == "pr" {
- st.Onboard = "commit"
- }
return nil, nil
}
- if f := st.Seen[core.TidyID]; f.Verdict == "unsupported" && base != "" && f.Base == base {
+ if f := st.Seen[core.FirstID]; f.Verdict == "unsupported" && base != "" && f.Base == base {
+ return nil, nil
+ }
+ commit := s.cfg.Deliver.Mode == "commit"
+ if commit && st.Open != nil && st.Open.PR != 0 {
+ // The first PR was opened before tend.yml asked for commits.
+ st.Onboard = "commit"
return nil, nil
}
var pr *core.PR
owed := false
- if s.forge != nil {
+ if s.forge != nil && !commit {
var err error
- if pr, err = s.forge.FindPR(ctx, deliver.TidyBranch); err != nil {
+ if pr, err = s.forge.FindPR(ctx, deliver.FirstBranch); err != nil {
return nil, fmt.Errorf("forge: %w", err)
}
if pr == nil && st.Onboard == "" {
@@ -83,7 +90,8 @@ func (s *session) onboarding(ctx context.Context, inv *core.Inventory, p *plan.P
case pr == nil || pr.State == "open":
case pr.State == "merged":
st.Onboard = "merged"
- return nil, nil
+ st.Stage = max(st.Stage, deliver.StageOf(pr.Body))
+ return s.staged(p), nil
default:
back, err := deliver.Displaced(ctx, s.forge, pr)
if err != nil {
@@ -101,7 +109,8 @@ func (s *session) onboarding(ctx context.Context, inv *core.Inventory, p *plan.P
st.Onboard = "before"
return nil, nil
}
- ch, err := plan.Tidy(inv, p, s.cfg, s.configured(inv.Root))
+ // A commit is no place for a tend.yml that changes nothing.
+ ch, err := plan.First(inv, p, s.cfg, commit || s.configured(inv.Root))
if err != nil {
return nil, err
}
@@ -111,35 +120,52 @@ func (s *session) onboarding(ctx context.Context, inv *core.Inventory, p *plan.P
}
// Without a forge to ask whether tend was here before, a run that has one
// must still ask: a tend check offline does not settle it.
- if s.forge != nil {
+ if commit && s.remote != "" || !commit && s.forge != nil {
st.Onboard = due
}
return ch, nil
}
+// staged is the catch-up PR for the next stage once the first PR has
+// merged, nil when there is none: the catch-up is over, or tend had begun
+// here before it had stages. A run that finds no stage left ends it.
+func (s *session) staged(p *plan.Plan) *core.Change {
+ st := s.st
+ if st.Stage == 0 || st.Stage >= plan.Last {
+ return nil
+ }
+ ch := plan.Next(p, st.Stage)
+ if ch == nil {
+ st.Stage = plan.Last
+ s.logf("the catch-up is done; from here on tend works one change at a time")
+ }
+ return ch
+}
+
// owed reports whether an open tend PR went ahead of the first PR, as its
-// marker says: a state lost meanwhile still owes the tidy-up.
+// marker says: a state lost meanwhile still owes the first PR, which folds
+// that PR in.
func (s *session) owed(ctx context.Context) (bool, error) {
prs, err := s.forge.OpenPRs(ctx, "tend/")
if err != nil {
return false, err
}
- return slices.ContainsFunc(prs, func(pr core.PR) bool { return deliver.TidyDue(pr.Body) }), nil
+ return slices.ContainsFunc(prs, func(pr core.PR) bool { return deliver.FirstDue(pr.Body) }), nil
}
-// untidy says why tend's first PR, open as id, is no longer wanted, or ""
-// while it is: tend.yml asks for none now, or nothing is left to tidy.
-func (s *session) untidy(p *plan.Plan, id string) string {
- if id != core.TidyID || slices.ContainsFunc(p.Queue, func(ch core.Change) bool { return ch.Kind == core.Tidy }) {
+// unwanted says why a catch-up PR, open as id, is no longer wanted, or ""
+// while it is: tend.yml asks for none now, or nothing is left to catch up on.
+func (s *session) unwanted(p *plan.Plan, id string) string {
+ if !core.CatchUp(id) || slices.ContainsFunc(p.Queue, func(ch core.Change) bool { return ch.Kind == core.First }) {
return ""
}
- switch s.st.Onboard {
- case "quiet", "off":
+ switch {
+ case s.st.Onboard == "quiet" || s.st.Onboard == "off":
return "tend.yml sets onboarding: " + s.st.Onboard + " now"
- case "commit":
+ case s.st.Onboard == "commit":
return "tend.yml delivers by commit now"
- case "clean":
- return "nothing is left to tidy up"
+ case s.st.Onboard == "clean", core.StageOf(id) > 0 && s.st.Stage >= plan.Last:
+ return "nothing is left to catch up on"
}
return ""
}
@@ -177,98 +203,141 @@ func (s *session) configured(root string) bool {
}
// quiet says once what a first PR would have removed, when tend.yml asks
-// for no first PR: the rest of the tidy-up comes as PRs of its own anyway.
+// for no first PR: the rest of what it carries comes as PRs of their own
+// anyway.
func (s *session) quiet(inv *core.Inventory, p *plan.Plan) {
if s.cfg.Onboarding != "quiet" {
return
}
- ch, err := plan.Tidy(inv, p, s.cfg, true)
- if err != nil || ch == nil || len(ch.Cleanup.Unused) == 0 {
+ ch, err := plan.First(inv, p, s.cfg, true)
+ if err != nil || ch == nil || len(ch.Batch.Unused) == 0 {
return
}
var names []string
- for _, d := range ch.Cleanup.Unused {
+ for _, d := range ch.Batch.Unused {
names = append(names, d.Name)
}
- s.logf("onboarding is quiet, so there is no tidy-up PR; nothing in the project uses %s", strings.Join(names, ", "))
+ s.logf("onboarding is quiet, so there is no first PR; nothing in the project uses %s", strings.Join(names, ", "))
}
-// part is one piece of a tidy-up that its proof keeps or drops: a dependency
-// nothing uses, to remove, or a deprecated library to move off.
+// part is one piece of a catch-up PR that its proof keeps or drops: a
+// dependency nothing uses, to remove, a queued change to make, or the test
+// baseline, which every set starts with and none drops.
type part struct {
n int // its place among the parts, for naming a set of them
gone *core.Dep
- move *core.Change
- pt *core.Patch // the move as it was first made
- code string // the move's edits on top of its bump, as a diff
+ ch *core.Change
+ pt *core.Patch // the change as it was first made, nil for one that is its bump alone
+ code string // the change's edits on top of its bump, or the baseline's files, as a diff
+ base *core.Baseline // set for the baseline
}
-// tidy carries tend's first PR: it makes each move once, then proves every
-// removal and move together, keeps what passes when the whole does not, and
-// vets and delivers the result like any patch.
-func (r *runner) tidy(ctx context.Context, ch *core.Change, preempt *core.PR) (*outcome, error) {
+// proofMax is the least number of times a catch-up PR runs the project's
+// commands to settle what it carries, the run of the whole batch included;
+// one with more parts gets two runs for each. What is still unsettled when
+// they run out waits for a later stage.
+const proofMax = 8
+
+// batch carries a catch-up PR: the first adds a test baseline when the
+// project's tests are weak; then it makes each change that needs more than
+// its bump once, on its own, proves every change and removal together,
+// keeps what passes when the whole does not, and vets and delivers the
+// result like any patch.
+func (r *runner) batch(ctx context.Context, ch *core.Change, preempt *core.PR) (*outcome, error) {
s, wt := r.s, r.wt
r.slug = core.Slug(ch.ID)
- cmds := verify.Detect(wt.Dir, r.inv.Manifests, r.ecos, s.cfg.Verify)
+ cmds := r.detect()
nothing := len(cmds.Install)+len(cmds.Build)+len(cmds.Test) == 0
proof := &core.Proof{Container: s.cfg.Verify.Container, Nothing: nothing}
if !nothing {
proof.Base = r.baseline(ctx, cmds)
}
- c := &core.Cleanup{Kept: slices.Clone(ch.Cleanup.Kept)}
- var parts []*part
- for i := range ch.Cleanup.Unused {
- parts = append(parts, &part{n: len(parts), gone: &ch.Cleanup.Unused[i]})
- }
- for i := range ch.Cleanup.Moves {
- m := &ch.Cleanup.Moves[i]
- x, why, err := r.first(ctx, m, cmds, proof)
+ runs := max(proofMax, 2*(len(ch.Batch.Changes)+len(ch.Batch.Unused)))
+ t := &trial{r: r, cmds: cmds, proof: proof, runs: map[string]*core.Run{}, left: runs, budget: runs}
+ t.check = t.try
+ b := &core.Batch{Stage: ch.Batch.Stage, Kept: slices.Clone(ch.Batch.Kept), Next: slices.Clone(ch.Batch.Next)}
+ var fixed []*part
+ if ch.ID == core.FirstID {
+ x, err := r.groundwork(ctx, ch, t)
if err != nil {
return nil, err
}
- if why != "" {
- c.Left = append(c.Left, core.Aside{Dep: m.Deps[0], Why: why, Options: m.Options})
- continue
+ if x != nil {
+ fixed, b.Baseline, r.floor = []*part{x}, x.base, x.code
+ }
+ }
+ nothing, r.cmds = proof.Nothing, t.cmds
+ next := plan.After(ch.Batch)
+ where := "the first PR"
+ if ch.ID != core.FirstID {
+ where = "this catch-up PR"
+ }
+ // What has no later stage to go to is recorded as tried, for the
+ // tracking issue, and comes back one change at a time.
+ leave := func(c core.Change, why string) {
+ s.logf("left %s out of %s: %s", name(&part{ch: &c}), where, why)
+ if next == 0 && c.Kind != core.Security {
+ s.st.Fail(c.ID, why, wt.Base, s.e.Now())
+ }
+ b.Next = append(b.Next, core.Later{Change: c, Why: why, Stage: next})
+ }
+ var parts []*part
+ for i := range ch.Batch.Changes {
+ c := &ch.Batch.Changes[i]
+ x := &part{ch: c}
+ if !patch.Bare(c) {
+ var why string
+ var err error
+ if x, why, err = r.once(ctx, c, t); err != nil {
+ return nil, err
+ }
+ if why != "" {
+ leave(*c, why)
+ continue
+ }
}
x.n = len(parts)
parts = append(parts, x)
}
+ for i := range ch.Batch.Unused {
+ parts = append(parts, &part{n: len(parts), gone: &ch.Batch.Unused[i]})
+ }
- t := &trial{r: r, cmds: cmds, proof: proof, runs: map[string]*core.Run{}}
- t.check = t.try
kept := parts
if !nothing {
var err error
- if kept, err = t.keep(ctx, nil, parts, nil); err != nil {
+ if kept, err = t.keep(ctx, fixed, parts, nil); err != nil {
return nil, err
}
}
for _, d := range t.dropped {
- s.logf("left %s out of the tidy-up: %s", name(d.x), d.why())
if d.x.gone != nil {
- c.Kept = append(c.Kept, core.Aside{Dep: *d.x.gone, Why: d.why()})
+ s.logf("left %s out of %s: %s", name(d.x), where, d.why())
+ b.Kept = append(b.Kept, core.Aside{Dep: *d.x.gone, Why: d.why()})
continue
}
- c.Left = append(c.Left, core.Aside{Dep: d.x.move.Deps[0], Why: d.why(), Options: d.x.move.Options})
+ leave(*d.x.ch, d.why())
}
for _, x := range kept {
if x.gone != nil {
- c.Unused = append(c.Unused, *x.gone)
+ b.Unused = append(b.Unused, *x.gone)
} else {
- c.Moves = append(c.Moves, *x.move)
+ b.Changes = append(b.Changes, *x.ch)
}
}
out := *ch
- out.Cleanup = c
+ out.Batch = b
plan.Refit(&out)
- pt, err := t.final(ctx, kept, !s.configured(wt.Dir))
+ pt, err := t.final(ctx, append(fixed, kept...), !s.configured(wt.Dir))
if err != nil {
return nil, err
}
if len(pt.Files) == 0 {
- s.st.Onboard = "clean"
- return &outcome{Action: "nothing", line: "nothing to tidy up: no removal or move passed its proof, and tend.yml is there already"}, nil
+ if ch.ID == core.FirstID {
+ s.st.Onboard = "clean"
+ }
+ return &outcome{Action: "nothing", line: "nothing to catch up on: no change or removal passed its proof, and tend.yml is there already"}, nil
}
vt, err := r.vet(ctx, &out, pt, proof)
if err != nil {
@@ -283,18 +352,61 @@ func (r *runner) tidy(ctx context.Context, ch *core.Change, preempt *core.PR) (*
return r.deliver(ctx, &out, pt, proof, vt, preempt)
}
-// first makes a move once, on the base commit, the way its own PR would make
-// it: the bump, the codemods, then the model. It learns whether the move can
-// be made at all, and what it edits on top of the bump, to build it again
-// next to the other parts without asking the model twice. why says what
-// stands in the way when it cannot be made.
-func (r *runner) first(ctx context.Context, m *core.Change, cmds core.Commands, proof *core.Proof) (*part, string, error) {
+// once makes a change on its own, on the base commit, the way its own PR
+// would make it: the bump, the codemods, then the model. It learns whether
+// the change can be made at all, and what it edits on top of the bump, to
+// build it again next to the other parts without asking the model twice. A
+// jump of more than one major is proven alone, and when it fails, or the
+// change cannot be made, tend tries what it may do by itself: up a major at
+// a time, then each option its rule allows, each proven. why says what
+// stands in the way when none of it works.
+func (r *runner) once(ctx context.Context, ch *core.Change, t *trial) (*part, string, error) {
defer func(slug string) { r.slug = slug }(r.slug)
- r.slug = core.Slug(m.ID)
- if err := reset(ctx, r.wt); err != nil {
+ r.slug = core.Slug(ch.ID)
+ x, why, err := r.made(ctx, ch, t)
+ if err != nil || x != nil && len(ch.Steps) == 0 {
+ return x, why, err
+ }
+ if x != nil {
+ if t.left <= 0 {
+ return x, "", nil
+ }
+ run, err := r.prove(ctx, t.cmds, "patched")
+ if err != nil {
+ return nil, "", err
+ }
+ t.left--
+ if plan.Proven(&core.Proof{Base: t.proof.Base, Patched: run}) {
+ return x, "", nil
+ }
+ why = "on its own, " + broke(run)
+ }
+ if len(ch.Steps) > 0 {
+ c, pt, _, stop, err := r.climb(ctx, ch, t.cmds, t.proof, &t.left)
+ if err != nil {
+ return nil, "", err
+ }
+ if c != nil {
+ r.s.logf("climbed %s to %s%s", name(&part{ch: ch}), c.To, strings.TrimSuffix("; "+stop, "; "))
+ y, err := r.piece(ctx, c, pt, t)
+ return y, "", err
+ }
+ why = cmp.Or(stop, why)
+ }
+ c, pt, err := r.decide(ctx, ch, t.cmds, t.proof, &t.left)
+ if err != nil || c == nil {
+ return nil, why, err
+ }
+ y, err := r.piece(ctx, c, pt, t)
+ return y, "", err
+}
+
+// made makes ch once, as once says, without proving it.
+func (r *runner) made(ctx context.Context, ch *core.Change, t *trial) (*part, string, error) {
+ if err := r.restart(ctx); err != nil {
return nil, "", err
}
- o := r.options(cmds, proof)
+ o := r.options(ch, t.cmds, t.proof)
o.Strict = true
bumped := ""
o.Bumped = func(ctx context.Context) error {
@@ -303,8 +415,8 @@ func (r *runner) first(ctx context.Context, m *core.Change, cmds core.Commands,
}
return nil
}
- r.s.logf("moving off %s on its own first", m.Deps[0].Name)
- pt, err := patch.Apply(ctx, r.wt.Dir, m, o)
+ r.s.logf("making %s on its own first", name(&part{ch: ch}))
+ pt, err := patch.Apply(ctx, r.wt.Dir, ch, o)
switch {
case err != nil && ctx.Err() != nil:
return nil, "", ctx.Err()
@@ -314,15 +426,47 @@ func (r *runner) first(ctx context.Context, m *core.Change, cmds core.Commands,
case pt.Decision:
return nil, pt.Note, nil
case len(pt.Files) == 0:
- return nil, "moving off it changes no files", nil
+ return nil, "making it changes no files", nil
}
code := ""
+ // With nothing to bump, the edits are all there is, from the base on.
+ bumped = cmp.Or(bumped, r.wt.Base)
if after := r.tree(ctx); after != "" && after != bumped {
- if code, err = gitx.Raw(ctx, r.wt.Dir, "diff", "--binary", "--no-renames", "--no-color", "--no-ext-diff", "--no-textconv", "--src-prefix=a/", "--dst-prefix=b/", bumped, after); err != nil {
+ if code, err = treeDiff(ctx, r.wt.Dir, bumped, after); err != nil {
return nil, "", err
}
}
- return &part{move: m, pt: pt, code: code}, "", nil
+ return &part{ch: ch, pt: pt, code: code}, "", nil
+}
+
+// piece turns the change c the worktree holds staged, as a climb or a
+// choice left it, into a part the trial can build again: the bump made
+// anew on the base, and the rest as edits on top of it.
+func (r *runner) piece(ctx context.Context, c *core.Change, pt *core.Patch, t *trial) (*part, error) {
+ final := r.tree(ctx)
+ if final == "" {
+ return nil, errors.New("cannot read the worktree")
+ }
+ if err := r.restart(ctx); err != nil {
+ return nil, err
+ }
+ if err := patch.Redo(ctx, r.wt.Dir, c, "", r.options(c, t.cmds, t.proof), &core.Patch{}); err != nil {
+ return nil, err
+ }
+ bumped := r.tree(ctx)
+ code := ""
+ if bumped != final {
+ var err error
+ if code, err = treeDiff(ctx, r.wt.Dir, bumped, final); err != nil {
+ return nil, err
+ }
+ }
+ return &part{ch: c, pt: pt, code: code}, nil
+}
+
+// treeDiff is the diff between two trees, for git apply.
+func treeDiff(ctx context.Context, dir, from, to string) (string, error) {
+ return gitx.Raw(ctx, dir, "diff", "--binary", "--no-renames", "--no-color", "--no-ext-diff", "--no-textconv", "--src-prefix=a/", "--dst-prefix=b/", from, to)
}
// trial builds sets of parts on the base commit and proves them, keeping
@@ -333,20 +477,26 @@ type trial struct {
proof *core.Proof
runs map[string]*core.Run
dropped []drop
+ left int // proofs it may still run
+ budget int // proofs it could run at the start
check func(context.Context, []*part) (*drop, error) // try, or a test's stand-in
}
-// drop is a part a tidy-up leaves out: the run that failed with it, or why
-// it could not be made at all.
+// drop is a part the first PR leaves out: the run that failed with it, why
+// it could not be made, or that the proofs ran out before it was settled.
+// x is set when the failure is the part's own.
type drop struct {
x *part
run *core.Run
build string
+ spent int // the proofs that ran out before it was settled, 0 when they did not
}
func (d drop) why() string {
build := strings.TrimPrefix(d.build, "patch: ")
switch {
+ case d.spent > 0:
+ return fmt.Sprintf("it was not proven: the pull request stops after %d runs of the project's commands", d.spent)
case build != "" && d.x.gone != nil:
if m := d.x.gone.Manifest.Path; m != "" {
if rest, ok := strings.CutPrefix(build, m+": "); ok {
@@ -355,11 +505,11 @@ func (d drop) why() string {
}
return "removing it fails: " + build
case build != "":
- return "the move cannot be made next to the rest: " + build
+ return "making it next to the rest fails: " + build
case d.x.gone != nil:
return "with it removed, " + broke(d.run)
}
- return "with the move made, " + broke(d.run)
+ return "with it in the batch, " + broke(d.run)
}
func key(set []*part) string {
@@ -374,17 +524,22 @@ func key(set []*part) string {
// keep finds the parts that pass on top of kept: all of them when they pass
// together, else what passes of each half, the second half on top of what
// the first kept. A part that fails on its own is dropped with the run that
-// showed it. failed, when set, is how kept and parts already failed
-// together, which is not proven twice.
+// showed it, and one whose own making fails is dropped as soon as it does.
+// failed, when set, is how kept and parts already failed together, which is
+// not proven twice.
func (t *trial) keep(ctx context.Context, kept, parts []*part, failed *drop) ([]*part, error) {
if len(parts) == 0 {
return nil, nil
}
if failed == nil {
- f, err := t.check(ctx, append(slices.Clone(kept), parts...))
+ f, err := t.settle(ctx, append(slices.Clone(kept), parts...))
if err != nil || f == nil {
return parts, err
}
+ if f.x != nil && slices.Contains(parts, f.x) {
+ t.dropped = append(t.dropped, *f)
+ return t.keep(ctx, kept, slices.DeleteFunc(slices.Clone(parts), func(x *part) bool { return x == f.x }), nil)
+ }
failed = f
}
if len(parts) == 1 {
@@ -408,15 +563,28 @@ func (t *trial) keep(ctx context.Context, kept, parts []*part, failed *drop) ([]
return append(a, b...), nil
}
+// settle checks set while proofs are left, and counts the proof it took. A
+// set that could not be built took none.
+func (t *trial) settle(ctx context.Context, set []*part) (*drop, error) {
+ if t.left <= 0 {
+ return &drop{spent: max(t.budget, proofMax)}, nil
+ }
+ f, err := t.check(ctx, set)
+ if err == nil && (f == nil || f.build == "") {
+ t.left--
+ }
+ return f, err
+}
+
// try builds set and proves it. It returns how the set failed, or nil when
// it passes.
func (t *trial) try(ctx context.Context, set []*part) (*drop, error) {
- if _, err := t.build(ctx, set); err != nil {
+ if _, x, err := t.build(ctx, set); err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
first, _, _ := strings.Cut(err.Error(), "\n")
- return &drop{build: first}, nil
+ return &drop{x: x, build: first}, nil
}
run, err := t.r.prove(ctx, t.cmds, "patched")
if err != nil {
@@ -429,55 +597,83 @@ func (t *trial) try(ctx context.Context, set []*part) (*drop, error) {
return nil, nil
}
-// build puts the worktree on the base commit plus set: each move's bump made
-// again and its edits applied, then the removals, one native run for each
-// manifest. Moves go first, while each manifest line is where it was read.
-func (t *trial) build(ctx context.Context, set []*part) (*core.Patch, error) {
+// build puts the worktree on the base commit plus set: each change's bump
+// made again and its edits applied, then the removals, one native run for
+// each manifest. Changes go first, while each manifest line is where it was
+// read. When building fails, x is the part that failed when that can be
+// told.
+func (t *trial) build(ctx context.Context, set []*part) (pt *core.Patch, x *part, err error) {
r := t.r
if err := reset(ctx, r.wt); err != nil {
- return nil, err
+ return nil, nil, err
}
- o := r.options(t.cmds, t.proof)
+ o := r.options(nil, t.cmds, t.proof)
if t.runs[key(set)] != nil {
// A set already proven is built again only to stage it; its steps
// were logged the first time.
o.Log = nil
}
p := &core.Patch{}
- var gone []core.Dep
+ var gone []*part
var notes []string
for _, x := range set {
+ if x.base != nil {
+ if err := patch.Put(ctx, r.wt.Dir, x.code); err != nil {
+ return nil, x, err
+ }
+ p.Applied = append(p.Applied, x.pt.Applied...)
+ p.Model = p.Model || x.pt.Model
+ p.Edited = append(p.Edited, x.pt.Edited...)
+ continue
+ }
if x.gone != nil {
- gone = append(gone, *x.gone)
+ gone = append(gone, x)
continue
}
- if err := patch.Redo(ctx, r.wt.Dir, x.move, x.code, o); err != nil {
- return nil, err
+ q := &core.Patch{}
+ if err := patch.Redo(ctx, r.wt.Dir, x.ch, x.code, o, q); err != nil {
+ return nil, x, err
+ }
+ if x.pt != nil {
+ q.Applied, q.Model, q.Edited, q.Note = x.pt.Applied, x.pt.Model, x.pt.Edited, x.pt.Note
}
- p.Applied = append(p.Applied, x.pt.Applied...)
- p.Model = p.Model || x.pt.Model
- p.Edited = append(p.Edited, x.pt.Edited...)
- if x.pt.Note != "" {
- notes = append(notes, x.pt.Note)
+ p.Applied = append(p.Applied, q.Applied...)
+ p.Model = p.Model || q.Model
+ p.Edited = append(p.Edited, q.Edited...)
+ if q.Note != "" {
+ notes = append(notes, q.Note)
+ }
+ for k, v := range q.Landed {
+ if p.Landed == nil {
+ p.Landed = map[string]string{}
+ }
+ p.Landed[k] = v
}
}
if len(notes) == 1 {
p.Note = notes[0]
}
if len(gone) > 0 {
- if err := patch.Remove(ctx, r.wt.Dir, gone, o, p); err != nil {
- return nil, err
+ var deps []core.Dep
+ for _, x := range gone {
+ deps = append(deps, *x.gone)
+ }
+ if err := patch.Remove(ctx, r.wt.Dir, deps, o, p); err != nil {
+ if len(gone) == 1 {
+ return nil, gone[0], err
+ }
+ return nil, nil, err
}
}
- return p, nil
+ return p, nil, nil
}
-// final builds the tidy-up's patch from set, adds the starter tend.yml when
+// final builds the first PR's patch from set, adds the starter tend.yml when
// nothing else changes and the repo asks for one, and stages and diffs it.
// The proof is the run that passed this very set when there was one.
func (t *trial) final(ctx context.Context, set []*part, starter bool) (*core.Patch, error) {
r, wt := t.r, t.r.wt
- pt, err := t.build(ctx, set)
+ pt, _, err := t.build(ctx, set)
if err != nil {
return nil, err
}
@@ -510,7 +706,13 @@ func name(x *part) string {
if x.gone != nil {
return x.gone.Name
}
- return x.move.Deps[0].Name
+ if a := x.ch.API; a != nil {
+ return strings.TrimSpace(a.Provider + " " + strings.ToUpper(a.Method) + " " + a.Path)
+ }
+ if len(x.ch.Deps) == 0 {
+ return x.ch.ID
+ }
+ return x.ch.Deps[0].Name
}
// broke says how a run failed, in a few words: "`npm test` fails (exit 1)".
diff --git a/internal/cli/onboard_test.go b/internal/cli/onboard_test.go
index d3ff365..ac46a7a 100644
--- a/internal/cli/onboard_test.go
+++ b/internal/cli/onboard_test.go
@@ -19,15 +19,19 @@ import (
)
// keep drops exactly the parts that fail, whichever they are, proves a set
-// that passes as a whole once, and never proves a set twice.
+// that passes as a whole once, never proves a set twice, and drops a part
+// whose own making fails without proving anything for it.
func TestKeep(t *testing.T) {
tests := []struct {
- name string
- n int
- bad []int
- pairs [][2]int // parts that fail only together; the later one goes
- tries int
+ name string
+ n int
+ bad []int
+ pairs [][2]int // parts that fail only together; the later one goes
+ broken []int // parts whose own making fails
+ tries int
}{
+ {name: "one that cannot be made", n: 5, broken: []int{3}, tries: 2},
+ {name: "two that cannot be made and one bad", n: 6, broken: []int{0, 4}, bad: []int{2}},
{name: "all pass", n: 5, tries: 1},
{name: "nothing to prove", n: 0, tries: 0},
{name: "one bad", n: 4, bad: []int{2}, tries: 4},
@@ -44,8 +48,13 @@ func TestKeep(t *testing.T) {
}
tries := 0
seen := map[string]bool{}
- tr := &trial{check: func(_ context.Context, set []*part) (*drop, error) {
+ tr := &trial{left: 100, check: func(_ context.Context, set []*part) (*drop, error) {
tries++
+ for _, x := range set {
+ if slices.Contains(tt.broken, x.n) {
+ return &drop{x: x, build: "cannot be made"}, nil
+ }
+ }
if k := key(set); seen[k] {
t.Errorf("proved %s twice", k)
} else {
@@ -80,7 +89,7 @@ func TestKeep(t *testing.T) {
}
want := []int{}
for i := range tt.n {
- if !slices.Contains(tt.bad, i) && !slices.ContainsFunc(tt.pairs, func(p [2]int) bool { return p[1] == i }) {
+ if !slices.Contains(tt.bad, i) && !slices.Contains(tt.broken, i) && !slices.ContainsFunc(tt.pairs, func(p [2]int) bool { return p[1] == i }) {
want = append(want, i)
}
}
@@ -95,20 +104,49 @@ func TestKeep(t *testing.T) {
}
}
+// The proofs run out before every part is settled: what passed stays, and
+// the rest waits, said to be unproven.
+func TestKeepSpent(t *testing.T) {
+ var parts []*part
+ for i := range 8 {
+ parts = append(parts, &part{n: i, gone: &core.Dep{Name: fmt.Sprint(i)}})
+ }
+ tries := 0
+ tr := &trial{left: 2, check: func(_ context.Context, set []*part) (*drop, error) {
+ tries++
+ if slices.ContainsFunc(set, func(x *part) bool { return x.n == 7 }) {
+ return &drop{run: &core.Run{}}, nil
+ }
+ return nil, nil
+ }}
+ kept, err := tr.keep(context.Background(), nil, parts, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(kept) != 4 || kept[3].n != 3 || len(tr.dropped) != 4 || tries != 2 {
+ t.Fatalf("kept %d, dropped %d, %d tries", len(kept), len(tr.dropped), tries)
+ }
+ for _, d := range tr.dropped {
+ if want := "it was not proven: the pull request stops after 8 runs of the project's commands"; d.why() != want {
+ t.Errorf("why = %q", d.why())
+ }
+ }
+}
+
func TestDropWhy(t *testing.T) {
failed := &core.Run{Steps: []core.Step{{Cmd: "npm ci"}, {Cmd: "npm test", Exit: 1}}}
gone := &part{gone: &core.Dep{Name: "left-pad"}}
inPkg := &part{gone: &core.Dep{Name: "left-pad", Manifest: core.Manifest{Path: "package.json"}}}
- move := &part{move: &core.Change{Deps: []core.Dep{{Name: "stripe"}}}}
+ move := &part{ch: &core.Change{Deps: []core.Dep{{Name: "stripe"}}}}
for _, tt := range []struct {
d drop
want string
}{
{drop{x: gone, run: failed}, "with it removed, `npm test` fails (exit 1)"},
- {drop{x: move, run: failed}, "with the move made, `npm test` fails (exit 1)"},
+ {drop{x: move, run: failed}, "with it in the batch, `npm test` fails (exit 1)"},
{drop{x: gone, build: "npm install failed"}, "removing it fails: npm install failed"},
{drop{x: inPkg, build: "patch: package.json: npm install --package-lock-only: exit status 1"}, "removing it from package.json fails: npm install --package-lock-only: exit status 1"},
- {drop{x: move, build: "patch: the edits to the code no longer apply: conflict"}, "the move cannot be made next to the rest: the edits to the code no longer apply: conflict"},
+ {drop{x: move, build: "patch: the edits to the code no longer apply: conflict"}, "making it next to the rest fails: the edits to the code no longer apply: conflict"},
{drop{x: gone, run: &core.Run{Steps: []core.Step{{Cmd: "go test ./..."}}}}, "with it removed, `go test ./...` does not finish"},
} {
if got := tt.d.why(); got != tt.want {
@@ -179,15 +217,15 @@ func TestOnboarding(t *testing.T) {
st.Seen["npm/a@1.0.0"] = state.Seen{Verdict: "delivered"}
}, settled: "before"},
{name: "the first PR is open", st: func(st *state.State) { st.Onboard = due }, forge: func(t *testing.T, f *deliver.FakeForge) {
- openPR(t, f, deliver.TidyBranch, marker(core.TidyID))
+ openPR(t, f, deliver.FirstBranch, marker(core.FirstID))
}, due: true, settled: due},
{name: "a lost state finds the open first PR", forge: func(t *testing.T, f *deliver.FakeForge) {
- openPR(t, f, deliver.TidyBranch, marker(core.TidyID))
+ openPR(t, f, deliver.FirstBranch, marker(core.FirstID))
}, due: true, settled: due},
{name: "a lost state that read the open first PR back", st: func(st *state.State) {
- st.Open = &state.OpenPR{PR: 1, ID: core.TidyID}
+ st.Open = &state.OpenPR{PR: 1, ID: core.FirstID}
}, forge: func(t *testing.T, f *deliver.FakeForge) {
- openPR(t, f, deliver.TidyBranch, marker(core.TidyID))
+ openPR(t, f, deliver.FirstBranch, marker(core.FirstID))
}, due: true, settled: due},
{name: "a lost state while a security fix went first", forge: func(t *testing.T, f *deliver.FakeForge) {
openPR(t, f, "tend/npm-a-1.0.1", ``)
@@ -201,24 +239,24 @@ func TestOnboarding(t *testing.T) {
openPR(t, f, "tend/npm-a-1.0.1", marker("npm/a@1.0.1"))
}, settled: "before"},
{name: "the first PR merged", st: func(st *state.State) { st.Onboard = due }, forge: func(t *testing.T, f *deliver.FakeForge) {
- if err := f.Merge(openPR(t, f, deliver.TidyBranch, marker(core.TidyID))); err != nil {
+ if err := f.Merge(openPR(t, f, deliver.FirstBranch, marker(core.FirstID))); err != nil {
t.Fatal(err)
}
}, settled: "merged"},
{name: "a person closed the first PR", forge: func(t *testing.T, f *deliver.FakeForge) {
- if err := f.CloseByHuman(openPR(t, f, deliver.TidyBranch, marker(core.TidyID))); err != nil {
+ if err := f.CloseByHuman(openPR(t, f, deliver.FirstBranch, marker(core.FirstID))); err != nil {
t.Fatal(err)
}
}, settled: "closed"},
{name: "tend closed it for security work", st: func(st *state.State) { st.Onboard = due }, forge: func(t *testing.T, f *deliver.FakeForge) {
- n := openPR(t, f, deliver.TidyBranch, marker(core.TidyID))
+ n := openPR(t, f, deliver.FirstBranch, marker(core.FirstID))
if err := deliver.Close(context.Background(), f, n, "Closing to make room for a security fix."); err != nil {
t.Fatal(err)
}
openPR(t, f, "tend/npm-a-1.0.1", marker("npm/a@1.0.1"))
}, due: true, settled: due},
{name: "someone commented after tend closed it", st: func(st *state.State) { st.Onboard = due }, forge: func(t *testing.T, f *deliver.FakeForge) {
- n := openPR(t, f, deliver.TidyBranch, marker(core.TidyID))
+ n := openPR(t, f, deliver.FirstBranch, marker(core.FirstID))
if err := deliver.Close(context.Background(), f, n, "Closing to make room for a security fix."); err != nil {
t.Fatal(err)
}
@@ -228,16 +266,18 @@ func TestOnboarding(t *testing.T) {
}, due: true, settled: due},
{name: "settled before", st: func(st *state.State) { st.Onboard = "merged" }, settled: "merged"},
{name: "quiet says what nothing uses", cfg: func(c *config.Config) { c.Onboarding = "quiet" }, settled: "quiet",
- log: "onboarding is quiet, so there is no tidy-up PR; nothing in the project uses left-pad"},
+ log: "onboarding is quiet, so there is no first PR; nothing in the project uses left-pad"},
{name: "off", cfg: func(c *config.Config) { c.Onboarding = "off" }, settled: "off"},
- {name: "commit mode opens no PRs", cfg: func(c *config.Config) { c.Deliver.Mode = "commit" }, settled: "commit"},
+ {name: "commit mode catches up by commit", cfg: func(c *config.Config) { c.Deliver.Mode = "commit" }, due: true},
+ {name: "commit mode with the first PR open from before", cfg: func(c *config.Config) { c.Deliver.Mode = "commit" },
+ st: func(st *state.State) { st.Onboard, st.Open = due, &state.OpenPR{ID: core.FirstID, PR: 1} }, settled: "commit"},
{name: "not proven on this base", st: func(st *state.State) {
st.Onboard = due
- st.Fail(core.TidyID, "npm test failed", "base1", time.Now())
+ st.Fail(core.FirstID, "npm test failed", "base1", time.Now())
}, settled: due},
- {name: "nothing to tidy and a tend.yml already", cfg: func(c *config.Config) { c.Ignore = []config.Ignore{{Name: "left-pad"}} },
+ {name: "nothing to catch up on and a tend.yml already", cfg: func(c *config.Config) { c.Ignore = []config.Ignore{{Name: "left-pad"}} },
more: map[string]string{"tend.yml": "cooldown: 3d\n"}, settled: "clean"},
- {name: "nothing to tidy and a tend.yml not yet committed", cfg: func(c *config.Config) { c.Ignore = []config.Ignore{{Name: "left-pad"}} },
+ {name: "nothing to catch up on and a tend.yml not yet committed", cfg: func(c *config.Config) { c.Ignore = []config.Ignore{{Name: "left-pad"}} },
local: "cooldown: 3d\n", settled: "clean"},
}
for _, tt := range tests {
@@ -271,8 +311,8 @@ func TestOnboarding(t *testing.T) {
if (ch != nil) != tt.due || s.st.Onboard != tt.settled {
t.Errorf("due = %v, settled %q; want %v, %q", ch != nil, s.st.Onboard, tt.due, tt.settled)
}
- if ch != nil && (ch.Kind != core.Tidy || len(ch.Cleanup.Unused) != 1) {
- t.Errorf("tidy-up = %+v", ch)
+ if ch != nil && (ch.Kind != core.First || len(ch.Batch.Unused) != 1) {
+ t.Errorf("first PR = %+v", ch)
}
if !strings.Contains(errs.String(), tt.log) {
t.Errorf("logged %q, want %q", errs.String(), tt.log)
@@ -290,7 +330,8 @@ func openPR(t *testing.T, f *deliver.FakeForge, branch, body string) int {
return pr.Number
}
-// The tidy-up goes into the queue after security work and ahead of the rest.
+// The first PR goes into the queue ahead of everything, security work
+// included, which it carries.
func TestOnboardQueue(t *testing.T) {
inv, root := onboardRepo(t, nil)
s := &session{e: Env{Stderr: &bytes.Buffer{}, Getenv: func(string) string { return "" }, Now: time.Now}, cfg: config.Default(), st: state.New(), root: root}
@@ -305,15 +346,15 @@ func TestOnboardQueue(t *testing.T) {
for _, ch := range p.Queue {
ids = append(ids, ch.ID)
}
- if want := []string{"npm/a@1.0.1", core.TidyID, "npm/b@2.0.0"}; !slices.Equal(ids, want) {
+ if want := []string{core.FirstID, "npm/a@1.0.1", "npm/b@2.0.0"}; !slices.Equal(ids, want) {
t.Errorf("queue %q, want %q", ids, want)
}
}
// An open first PR tend no longer means to carry is closed with why; one
// still due, or any other PR, is not.
-func TestUntidy(t *testing.T) {
- tidy := core.Change{ID: core.TidyID, Kind: core.Tidy}
+func TestUnwanted(t *testing.T) {
+ first := core.Change{ID: core.FirstID, Kind: core.First}
tests := []struct {
name string
onboard string
@@ -321,21 +362,21 @@ func TestUntidy(t *testing.T) {
queue []core.Change
want string
}{
- {"onboarding turned off", "off", core.TidyID, nil, "tend.yml sets onboarding: off now"},
- {"onboarding turned quiet", "quiet", core.TidyID, nil, "tend.yml sets onboarding: quiet now"},
- {"commit mode", "commit", core.TidyID, nil, "tend.yml delivers by commit now"},
- {"nothing left to tidy", "clean", core.TidyID, nil, "nothing is left to tidy up"},
- {"still due", due, core.TidyID, []core.Change{tidy}, ""},
- {"due, not proven on this base", due, core.TidyID, nil, ""},
- {"queued after all", "clean", core.TidyID, []core.Change{tidy}, ""},
+ {"onboarding turned off", "off", core.FirstID, nil, "tend.yml sets onboarding: off now"},
+ {"onboarding turned quiet", "quiet", core.FirstID, nil, "tend.yml sets onboarding: quiet now"},
+ {"commit mode", "commit", core.FirstID, nil, "tend.yml delivers by commit now"},
+ {"nothing left to catch up on", "clean", core.FirstID, nil, "nothing is left to catch up on"},
+ {"still due", due, core.FirstID, []core.Change{first}, ""},
+ {"due, not proven on this base", due, core.FirstID, nil, ""},
+ {"queued after all", "clean", core.FirstID, []core.Change{first}, ""},
{"another PR", "off", "npm/a@1.0.0", nil, ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := &session{st: state.New()}
s.st.Onboard = tt.onboard
- if got := s.untidy(&plan.Plan{Queue: tt.queue}, tt.id); got != tt.want {
- t.Errorf("untidy = %q, want %q", got, tt.want)
+ if got := s.unwanted(&plan.Plan{Queue: tt.queue}, tt.id); got != tt.want {
+ t.Errorf("unwanted = %q, want %q", got, tt.want)
}
})
}
diff --git a/internal/cli/output.go b/internal/cli/output.go
index bfd28cc..83b52b2 100644
--- a/internal/cli/output.go
+++ b/internal/cli/output.go
@@ -167,7 +167,10 @@ func dropCounts(ds []plan.Drop) string {
// subject is what a change is about, as a human names it.
func subject(ch *core.Change) string {
- if ch.Kind == core.Tidy {
+ if ch.Kind == core.First && ch.ID != core.FirstID {
+ return plan.StageName(ch.Batch.Stage)
+ }
+ if ch.Kind == core.First {
return "first PR"
}
if ch.API != nil {
@@ -189,7 +192,7 @@ func subject(ch *core.Change) string {
}
func target(ch *core.Change) string {
- if ch.Kind == core.Tidy {
+ if ch.Kind == core.First {
return ""
}
if a := ch.API; a != nil {
@@ -209,8 +212,8 @@ func target(ch *core.Change) string {
func detail(ch *core.Change, openID string, open *core.PR) string {
var parts []string
- if c := ch.Cleanup; c != nil {
- parts = append(parts, cleanup(c))
+ if b := ch.Batch; b != nil {
+ parts = append(parts, carries(b))
if open != nil && ch.ID == openID {
parts = append(parts, fmt.Sprintf("open PR #%d", open.Number))
}
@@ -243,21 +246,39 @@ func detail(ch *core.Change, openID string, open *core.PR) string {
return strings.Join(slices.DeleteFunc(parts, func(s string) bool { return s == "" }), " · ")
}
-// cleanup sums up a tidy-up: "remove 3 unused · move off 1 deprecated · 2
-// to look at", or that it only sets tend up.
-func cleanup(c *core.Cleanup) string {
- var parts []string
- if n := len(c.Unused); n > 0 {
- parts = append(parts, fmt.Sprintf("remove %d unused", n))
- }
- if n := len(c.Moves); n > 0 {
- parts = append(parts, fmt.Sprintf("move off %d deprecated", n))
+// carries sums up a catch-up PR: "fix 2 security · 1 API · move off 1
+// deprecated · remove 3 unused · 4 in later stages · 2 to look at", or that
+// it only sets tend up.
+func carries(b *core.Batch) string {
+ var sec, api, dep int
+ for _, ch := range b.Changes {
+ switch {
+ case ch.API != nil:
+ api++
+ case ch.Kind == core.Security:
+ sec++
+ default:
+ dep++
+ }
}
- if n := len(c.Kept) + len(c.Left); n > 0 {
- parts = append(parts, fmt.Sprintf("%d to look at", n))
+ var parts []string
+ for _, x := range []struct {
+ n int
+ text string
+ }{
+ {sec, "fix %d security"},
+ {api, "%d API"},
+ {dep, "move off %d deprecated"},
+ {len(b.Unused), "remove %d unused"},
+ {len(b.Next), "%d in later stages"},
+ {len(b.Kept), "%d to look at"},
+ } {
+ if x.n > 0 {
+ parts = append(parts, fmt.Sprintf(x.text, x.n))
+ }
}
if len(parts) == 0 {
- return "nothing to tidy; adds tend.yml"
+ return "nothing to catch up on; adds tend.yml"
}
return strings.Join(parts, " · ")
}
diff --git a/internal/cli/output_test.go b/internal/cli/output_test.go
index 5e4f9aa..8d45548 100644
--- a/internal/cli/output_test.go
+++ b/internal/cli/output_test.go
@@ -33,21 +33,23 @@ func TestSubjectWithoutDeps(t *testing.T) {
}
}
-// check shows the tidy-up as what it would do, not as a dep and a target.
-func TestTidyLine(t *testing.T) {
+// check shows the first PR as what it would do, not as a dep and a target.
+func TestFirstLine(t *testing.T) {
d := core.Dep{Ecosystem: core.Npm, Name: "left-pad", Version: "1.3.0"}
open := &core.PR{Number: 1, Body: ``}
+ api := &core.APIChange{Provider: "stripe"}
tests := []struct {
- c core.Cleanup
+ b core.Batch
open *core.PR
want string
}{
- {core.Cleanup{Unused: []core.Dep{d, d, d}, Moves: []core.Change{{}}, Kept: []core.Aside{{}}}, nil, "remove 3 unused · move off 1 deprecated · 1 to look at"},
- {core.Cleanup{Left: []core.Aside{{}, {}}}, open, "2 to look at · open PR #1"},
- {core.Cleanup{}, nil, "nothing to tidy; adds tend.yml"},
+ {core.Batch{Unused: []core.Dep{d, d, d}, Changes: []core.Change{{Kind: core.Security}, {Kind: core.Security}, {Kind: core.Deprecation, API: api}, {Kind: core.Deprecation}}, Kept: []core.Aside{{}}},
+ nil, "fix 2 security · 1 API · move off 1 deprecated · remove 3 unused · 1 to look at"},
+ {core.Batch{Next: []core.Later{{}, {}}}, open, "2 in later stages · open PR #1"},
+ {core.Batch{}, nil, "nothing to catch up on; adds tend.yml"},
}
for _, tt := range tests {
- ch := core.Change{ID: core.TidyID, Kind: core.Tidy, Deps: []core.Dep{d}, Cleanup: &tt.c}
+ ch := core.Change{ID: core.FirstID, Kind: core.First, Deps: []core.Dep{d}, Batch: &tt.b}
if got := subject(&ch) + "|" + target(&ch) + "|" + detail(&ch, plan.OpenID(tt.open, nil), tt.open); got != "first PR||"+tt.want {
t.Errorf("line = %q, want %q", got, tt.want)
}
diff --git a/internal/cli/run.go b/internal/cli/run.go
index 7000a2d..8c0a327 100644
--- a/internal/cli/run.go
+++ b/internal/cli/run.go
@@ -12,6 +12,7 @@ import (
"time"
"github.com/mohsensc/tend-cli/internal/api"
+ "github.com/mohsensc/tend-cli/internal/config"
"github.com/mohsensc/tend-cli/internal/core"
"github.com/mohsensc/tend-cli/internal/deliver"
"github.com/mohsensc/tend-cli/internal/eco"
@@ -29,7 +30,7 @@ import (
// outcome is what one run did, for the final line and for --json.
type outcome struct {
- Action string `json:"action"` // opened|updated|committed|branch|dry-run|waiting|nothing|up-to-date|unproven|moved
+ Action string `json:"action"` // opened|updated|committed|branch|dry-run|waiting|nothing|up-to-date|unproven|moved|reverted
Change *core.Change `json:"change"`
PR *core.PR `json:"pr"`
Branch string `json:"branch"`
@@ -88,7 +89,12 @@ func (s *session) pass(ctx context.Context) (*outcome, error) {
if err != nil {
return nil, err
}
- s.settleCommit(ctx)
+ if res, err := s.settleCommit(ctx); err != nil || res != nil {
+ if res != nil {
+ s.save()
+ }
+ return res, err
+ }
baseRef, err := s.baseName(ctx)
if err != nil {
return nil, fmt.Errorf("forge: %w", err)
@@ -120,10 +126,7 @@ func (s *session) pass(ctx context.Context) (*outcome, error) {
}()
}
- r := &runner{s: s, wt: wt, baseRef: baseRef, ecos: map[string]core.Ecosystem{}}
- for _, e := range eco.For(s.cfg) {
- r.ecos[e.Name()] = e
- }
+ r := &runner{s: s, wt: wt, baseRef: baseRef, ecos: ecosFor(s.cfg)}
// The base commit's run comes first: what the runtimes say is deprecated
// while the project's own commands run is one more thing to plan from.
p, inv, err := s.plan(ctx, wt.Dir, wt.Base, func(inv *core.Inventory) []core.Warning {
@@ -162,10 +165,20 @@ func (s *session) pass(ctx context.Context) (*outcome, error) {
if !s.o.dryRun {
s.snapshot(inv)
}
+ s.track(ctx, p, wt.Base)
s.save()
return res, nil
}
+// ecosFor is every ecosystem tend.yml turns on, by name.
+func ecosFor(cfg *config.Config) map[string]core.Ecosystem {
+ res := map[string]core.Ecosystem{}
+ for _, e := range eco.For(cfg) {
+ res[e.Name()] = e
+ }
+ return res
+}
+
// runner carries one pass from the pick to the delivery.
type runner struct {
s *session
@@ -179,7 +192,31 @@ type runner struct {
pick int // the option the maintainer picked, 0 for none
cmdAt time.Time // when the maintainer's command this run honors was made
comments []core.Comment
- slug string // the change being worked on, for its logs
+ slug string // the change being worked on, for its logs
+ tests []string // test lines the baseline added in this run
+ floor string // the baseline's files as a diff, which each part is made on top of
+ cmds core.Commands // the project's commands as the base commit has them
+}
+
+// restart puts the worktree back on its base, with the baseline this run
+// added staged on top, for another go at making a part.
+func (r *runner) restart(ctx context.Context) error {
+ if err := reset(ctx, r.wt); err != nil || r.floor == "" {
+ return err
+ }
+ if err := patch.Put(ctx, r.wt.Dir, r.floor); err != nil {
+ return err
+ }
+ _, err := gitx.Run(ctx, r.wt.Dir, "add", "-A")
+ return err
+}
+
+// detect is the project's commands in the worktree, with the test lines
+// this run's baseline added.
+func (r *runner) detect() core.Commands {
+ c := verify.Detect(r.wt.Dir, r.inv.Manifests, r.ecos, r.s.cfg.Verify)
+ c.Test = append(c.Test, r.tests...)
+ return c
}
// option takes up `tend apply N`. An option the PR does not have gets one
@@ -222,7 +259,7 @@ func (r *runner) work(ctx context.Context) (*outcome, error) {
case hasCmd && cmd.Verb == "retry" && wait != nil && r.fresh(cmd):
r.requeue(id)
case wait != nil && !s.o.dryRun:
- if why := cmp.Or(plan.Stale(p, r.inv, id), s.untidy(p, id)); why != "" {
+ if why := cmp.Or(plan.Stale(p, r.inv, id), s.unwanted(p, id)); why != "" {
if err := deliver.Close(ctx, s.forge, wait.Number, "Closing: "+why+"."); err != nil {
return nil, err
}
@@ -307,6 +344,9 @@ func (r *runner) declined(ctx context.Context, pick *core.Change, preempt, wait
break
}
s.logf("#%d for %s was closed without merging, so tend leaves it", pr.Number, pick.ID)
+ if core.StageOf(pick.ID) > 0 {
+ s.st.Stage = plan.Last
+ }
s.st.Parked[pick.ID] = state.Parked{PR: pr.Number, Reason: "rejected", To: pick.To, At: s.e.Now()}
s.st.See(pick.ID, "parked", fmt.Sprintf("#%d was closed without merging", pr.Number), s.e.Now())
gone := pick.ID
@@ -338,19 +378,52 @@ func (r *runner) upToDate(pick *core.Change, preempt *core.PR, cmd plan.Command,
return false
}
id, base, _, ok := deliver.ParseMarker(open.Body)
- if !ok || id != pick.ID || base != r.wt.Base {
+ if !ok || id != pick.ID || base != r.wt.Base || !holds(s.st.Open, open, pick) {
return false
}
return !hasCmd || s.st.Open == nil || !cmd.At.After(s.st.Open.At)
}
+// holds reports whether the open PR was built from every queued change pick
+// carries. The first PR is built from the whole queue, so a change queued
+// after it opened, a new advisory say, rebuilds it on the same base.
+func holds(o *state.OpenPR, open *core.PR, pick *core.Change) bool {
+ b := pick.Batch
+ if b == nil {
+ return true
+ }
+ if o == nil || o.PR != open.Number {
+ return false
+ }
+ for _, id := range built(b) {
+ if !slices.Contains(o.Holds, id) {
+ return false
+ }
+ }
+ return true
+}
+
+// built lists the queued changes a batch was built from, made or left for
+// later.
+func built(b *core.Batch) []string {
+ var res []string
+ for _, ch := range b.Changes {
+ res = append(res, ch.ID)
+ }
+ for _, l := range b.Next {
+ res = append(res, l.Change.ID)
+ }
+ return res
+}
+
func (r *runner) change(ctx context.Context, ch *core.Change, preempt *core.PR) (*outcome, error) {
- if ch.Kind == core.Tidy {
- return r.tidy(ctx, ch, preempt)
+ if ch.Kind == core.First {
+ return r.batch(ctx, ch, preempt)
}
s, wt := r.s, r.wt
r.slug = core.Slug(ch.ID)
- cmds := verify.Detect(wt.Dir, r.inv.Manifests, r.ecos, s.cfg.Verify)
+ cmds := r.detect()
+ r.cmds = cmds
nothing := len(cmds.Install)+len(cmds.Build)+len(cmds.Test) == 0
proof := &core.Proof{Container: s.cfg.Verify.Container, Nothing: nothing}
if !nothing {
@@ -364,6 +437,20 @@ func (r *runner) change(ctx context.Context, ch *core.Change, preempt *core.PR)
}
return r.unproven(ch, "patch: "+err.Error()), nil
}
+ // Before it asks, tend tries the other ways it may take by itself: up a
+ // major at a time, then each option its rule allows.
+ if (pt.Decision || !plan.Proven(proof)) && r.pick == 0 && !nothing {
+ tried := proof.Patched
+ c, cpt, err := r.further(ctx, ch, cmds, proof)
+ if err != nil {
+ return nil, err
+ }
+ if c != nil {
+ ch, pt = c, cpt
+ } else {
+ proof.Patched = tried
+ }
+ }
if !pt.Decision && !nothing && !plan.Proven(proof) {
if !plan.Decides(ch) {
return r.unproven(ch, failure(proof.Patched)), nil
@@ -405,22 +492,42 @@ func (r *runner) change(ctx context.Context, ch *core.Change, preempt *core.PR)
return r.deliver(ctx, ch, pt, proof, vt, preempt)
}
-// options are how this run makes a patch: its ecosystems, index and model,
-// and for a model that calls tools, the project's commands to run as it works.
-func (r *runner) options(cmds core.Commands, proof *core.Proof) patch.Options {
+// options are how this run makes a patch for ch: its ecosystems, index and
+// model, and for a model that calls tools, the project's commands to run as
+// it works and a budget that grows with what ch moves.
+func (r *runner) options(ch *core.Change, cmds core.Commands, proof *core.Proof) patch.Options {
s := r.s
o := patch.Options{Ecos: r.ecos, Index: r.inv.Index, Model: r.model, Attempts: s.cfg.Model.Attempts, Option: r.pick, Proven: !proof.Nothing, Log: s.logf}
if _, ok := r.model.(model.Agent); ok && !proof.Nothing {
o.Commands, o.Turns, o.Tokens = cmds, s.cfg.Model.Turns, s.cfg.Model.Tokens
o.Transcript = filepath.Join(s.dir, "logs", r.slug, "agent.jsonl")
o.Prove = func(ctx context.Context, c core.Commands) (*core.Run, error) { return r.prove(ctx, c, "patched") }
+ scale(&o, shares(ch))
}
return o
}
+// further tries what tend may do by itself when making ch did not pass: up
+// its steps a major at a time, then each option plan.Ranked allows. It
+// returns the change as made and its patch, with proof.Patched the run that
+// passed it, or nil with the worktree back on the base.
+func (r *runner) further(ctx context.Context, ch *core.Change, cmds core.Commands, proof *core.Proof) (*core.Change, *core.Patch, error) {
+ if len(ch.Steps) > 0 {
+ c, pt, run, why, err := r.climb(ctx, ch, cmds, proof, nil)
+ if err != nil || c != nil {
+ if c != nil {
+ proof.Patched = run
+ r.s.logf("climbed %s to %s%s", name(&part{ch: ch}), c.To, strings.TrimSuffix("; "+why, "; "))
+ }
+ return c, pt, err
+ }
+ }
+ return r.decide(ctx, ch, cmds, proof, nil)
+}
+
// attempt applies the change and proves it, once.
func (r *runner) attempt(ctx context.Context, ch *core.Change, cmds core.Commands, proof *core.Proof) (*core.Patch, error) {
- o := r.options(cmds, proof)
+ o := r.options(ch, cmds, proof)
var last *core.Run
lastTree := ""
if o.Prove != nil {
@@ -544,7 +651,8 @@ func (r *runner) vet(ctx context.Context, ch *core.Change, pt *core.Patch, proof
return nil, err
}
}
- in := vet.Input{Dir: wt.Dir, Base: wt.Base, Change: ch, Patch: pt, Proof: proof, Index: idx, Ecos: r.ecos, Model: r.model, Fetch: s.fetch}
+ in := vet.Input{Dir: wt.Dir, Base: wt.Base, Change: ch, Patch: pt, Proof: proof, Index: idx, Ecos: r.ecos, Model: r.model, Fetch: s.fetch, Option: r.pick,
+ Commands: r.cmds, Detect: r.detect}
if ch.API != nil {
in.Spec, in.Hosts = r.spec(ch.API.Provider)
}
@@ -563,8 +671,7 @@ func (r *runner) vet(ctx context.Context, ch *core.Change, pt *core.Patch, proof
}
if !proof.Nothing {
s.logf("vetting changed the patch; proving it again")
- cmds := verify.Detect(wt.Dir, r.inv.Manifests, r.ecos, s.cfg.Verify)
- if proof.Patched, err = r.prove(ctx, cmds, "patched"); err != nil {
+ if proof.Patched, err = r.prove(ctx, r.cmds, "patched"); err != nil {
return nil, err
}
vt.Verdict = vet.Verdict(vt, proof)
@@ -590,7 +697,7 @@ func (r *runner) deliver(ctx context.Context, ch *core.Change, pt *core.Patch, p
in := deliver.BodyInput{
Change: ch, Patch: pt, Proof: proof, Vetting: vt, Base: wt.Base, BaseRef: r.baseRef,
Rev: 1, Option: r.pick, Meta: r.meta(ch),
- TidyDue: ch.Kind != core.Tidy && s.st.Onboard == due,
+ FirstDue: ch.Kind != core.First && s.st.Onboard == due,
}
if s.forge == nil && cfg.Mode == "pr" {
in.Notes = append(in.Notes, "Prepared without a pull request: "+s.why+".")
@@ -601,6 +708,15 @@ func (r *runner) deliver(ctx context.Context, ch *core.Change, pt *core.Patch, p
res.Action, res.line = "dry-run", "dry run; the worktree is kept at "+wt.Dir
return res, nil
}
+ // A commit goes in with nobody to read it first, so only a proven one does.
+ if cfg.Mode == "commit" {
+ switch {
+ case pt.Decision:
+ return r.unproven(ch, "commit mode pushes no decision: "+pt.Note), nil
+ case proof.Nothing:
+ return r.unproven(ch, "commit mode pushes only what a proof passed, and the project has no build or test command; set verify.test in tend.yml"), nil
+ }
+ }
author := verify.AuthorFrom(s.root, s.e.Getenv)
sha, err := wt.Commit(ctx, deliver.Message(in, cfg.TitlePrefix), author, pt.Decision)
@@ -624,6 +740,9 @@ func (r *runner) deliver(ctx context.Context, ch *core.Change, pt *core.Patch, p
return r.undelivered(ch, res, err)
}
s.st.Open = &state.OpenPR{ID: ch.ID, Branch: branch, Base: r.baseRef, Commit: res.Commit, At: now}
+ if ch.Batch != nil {
+ s.st.Open.Stage = ch.Batch.Stage
+ }
res.Action, res.Branch = "committed", branch
res.line = fmt.Sprintf("committed %s to %s: %s", core.Short(res.Commit), branch, res.Title)
case s.forge == nil || s.remote == "":
@@ -653,6 +772,9 @@ func (r *runner) deliver(ctx context.Context, ch *core.Change, pt *core.Patch, p
res.Action = "updated"
}
s.st.Open = &state.OpenPR{ID: ch.ID, PR: pr.Number, Branch: pr.Branch, Base: pr.Base, Commit: cmp.Or(pr.Head, sha), At: now}
+ if ch.Batch != nil {
+ s.st.Open.Holds, s.st.Open.Stage = built(ch.Batch), ch.Batch.Stage
+ }
if p, ok := s.st.Parked[ch.ID]; ok && p.Reason == "preempted" {
delete(s.st.Parked, ch.ID)
}
@@ -752,30 +874,6 @@ func (s *session) reconcile(ctx context.Context) (*core.PR, error) {
return pr, nil
}
-// settleCommit closes the books on a change delivered as a commit: it is on
-// the branch, or someone took it off again.
-func (s *session) settleCommit(ctx context.Context) {
- o := s.st.Open
- if o == nil || o.PR != 0 || s.o.dryRun {
- return
- }
- if s.remote == "" || o.Commit == "" {
- s.st.Open = nil
- return
- }
- if err := s.push.Fetch(ctx, o.Branch); err != nil {
- s.logf("cannot fetch %s to look for %s: %v", o.Branch, core.Short(o.Commit), err)
- return
- }
- s.st.Open = nil
- ref := "refs/remotes/" + s.remote + "/" + o.Branch
- if _, err := gitx.Run(ctx, s.root, "merge-base", "--is-ancestor", o.Commit, ref); err != nil {
- s.st.Parked[o.ID] = state.Parked{Reason: "rejected", To: core.TargetOf(o.ID), At: s.e.Now()}
- return
- }
- s.st.See(o.ID, "delivered", "", s.e.Now())
-}
-
func (r *runner) command(ctx context.Context, pr *core.PR) (plan.Command, bool) {
cs, err := r.s.forge.Comments(ctx, pr.Number)
if err != nil {
@@ -804,15 +902,18 @@ func (s *session) skip(ctx context.Context, pr *core.PR, id string, c plan.Comma
}
// displace closes the PR a new one is about to replace: the same change at an
-// older target is superseded; anything else gives way to security work and
-// comes back. It goes first, so tend never has two PRs open, and the state is
-// saved at once, so the displaced change returns even if the new PR never
-// opens.
+// older target is superseded; the first PR folds any other in; anything else
+// gives way to security work and comes back. It goes first, so tend never
+// has two PRs open, and the state is saved at once, so the displaced change
+// returns even if the new PR never opens.
func (s *session) displace(ctx context.Context, old *core.PR, oldID string, ch *core.Change) error {
msg := "Closing to make room for a security fix. tend will reopen this after that merges."
same := core.Subject(oldID) == core.Subject(ch.ID) && !ver.Less(ch.To, core.TargetOf(oldID))
- if same {
+ switch {
+ case same:
msg = fmt.Sprintf("Superseded by a newer change that moves to %s.", ch.To)
+ case ch.Kind == core.First:
+ msg = folded(ch.Batch, oldID)
}
if err := deliver.Close(ctx, s.forge, old.Number, msg); err != nil {
return err
@@ -827,6 +928,19 @@ func (s *session) displace(ctx context.Context, old *core.PR, oldID string, ch *
return nil
}
+// folded is the line that closes a PR the first PR folds in, saying where
+// its change went.
+func folded(b *core.Batch, id string) string {
+ at := func(ch core.Change) bool { return core.Subject(ch.ID) == core.Subject(id) }
+ switch {
+ case slices.ContainsFunc(b.Changes, at):
+ return "Folded into tend's first pull request, which makes this change with the rest."
+ case slices.ContainsFunc(b.Next, func(l core.Later) bool { return at(l.Change) }):
+ return "Folded into tend's first pull request, which plans this change for a later stage of its catch-up."
+ }
+ return "Folded into tend's first pull request; this comes back after that one if it is still needed."
+}
+
// notice prints one line a day at most when a newer release of tend exists.
func (s *session) notice(ctx context.Context) {
rel := &s.st.Release
diff --git a/internal/cli/testdata/init.golden b/internal/cli/testdata/init.golden
index e980463..236fedc 100644
--- a/internal/cli/testdata/init.golden
+++ b/internal/cli/testdata/init.golden
@@ -4,7 +4,7 @@
# base: "" # base branch; "" means the repo's default branch
# cooldown: 3d # skip releases younger than this; security fixes and deprecations do not wait
# schedule: 1d # how often watch runs and the workflow init --ci writes: 1h to 12h, 1d or 7d
-# onboarding: pr # the first run: pr (a tidy-up PR with a welcome) | quiet (no PR, just start) | off
+# onboarding: pr # the first run: pr (one catch-up PR with a welcome) | quiet (no PR, just start) | off
# ecosystems: [] # read only these, e.g. [npm, docker, actions]; [] means all
# updates: # which changes get a pull request; a breaking change always does
diff --git a/internal/cli/track.go b/internal/cli/track.go
new file mode 100644
index 0000000..e90c8d9
--- /dev/null
+++ b/internal/cli/track.go
@@ -0,0 +1,110 @@
+package cli
+
+import (
+ "context"
+ "fmt"
+ "maps"
+ "slices"
+ "strings"
+
+ "github.com/mohsensc/tend-cli/internal/core"
+ "github.com/mohsensc/tend-cli/internal/plan"
+)
+
+// trackMarker finds tend's tracking issue among the repository's issues.
+const trackMarker = ""
+
+const trackTitle = "tend: what it could not do on its own"
+
+// track keeps tend's one tracking issue in step with what tend could not
+// do on base: opened when there is something to list, edited when the list
+// changes, closed when it empties, and opened again when it fills. It asks
+// the forge nothing while the list is what it last wrote.
+func (s *session) track(ctx context.Context, p *plan.Plan, base string) {
+ tr, ok := s.forge.(core.Tracker)
+ if !ok || s.o.dryRun {
+ return
+ }
+ lines := s.undone(p, base)
+ open := len(lines) > 0
+ body := issueBody(lines)
+ is := &s.st.Issue
+ if is.Number != 0 && is.Body == body && is.Open == open {
+ return
+ }
+ if is.Number == 0 {
+ found, err := tr.FindIssue(ctx, trackMarker)
+ if err != nil {
+ s.logf("cannot look for the tracking issue: %v", err)
+ return
+ }
+ if found != nil {
+ is.Number, is.Body, is.Open = found.Number, found.Body, found.Open
+ }
+ }
+ switch {
+ case is.Number == 0 && !open:
+ case is.Number == 0:
+ made, err := tr.CreateIssue(ctx, trackTitle, body, s.cfg.Deliver.Labels)
+ if err != nil {
+ s.logf("cannot open the tracking issue: %v", err)
+ return
+ }
+ is.Number, is.Body, is.Open = made.Number, body, true
+ s.logf("opened #%d, which lists what tend could not do on its own", made.Number)
+ case is.Body != body || is.Open != open:
+ if err := tr.EditIssue(ctx, is.Number, body, open); err != nil {
+ s.logf("cannot update the tracking issue #%d: %v", is.Number, err)
+ return
+ }
+ if is.Open && !open {
+ s.logf("closed #%d: everything it listed is done", is.Number)
+ }
+ is.Body, is.Open = body, open
+ }
+}
+
+// undone lists, a line each with why, what tend tried on base and could
+// not prove or make, what it pushed and took back after CI failed, and the
+// deprecated packages it knows no replacement for.
+func (s *session) undone(p *plan.Plan, base string) []string {
+ var res []string
+ for _, id := range slices.Sorted(maps.Keys(s.st.Seen)) {
+ if x := s.st.Seen[id]; x.Verdict == "unsupported" && base != "" && x.Base == base {
+ first, _, _ := strings.Cut(x.Detail, "\n")
+ res = append(res, fmt.Sprintf("- `%s`: could not be made or proven on %s: %s", id, core.Short(base), strings.TrimSuffix(first, ".")))
+ }
+ }
+ for _, id := range slices.Sorted(maps.Keys(s.st.Parked)) {
+ if x := s.st.Parked[id]; x.Reason == "reverted" {
+ res = append(res, fmt.Sprintf("- `%s`: %s", id, x.Detail))
+ }
+ }
+ if p != nil {
+ var gone []core.Dep
+ for _, ch := range p.Queue {
+ if ch.Batch != nil {
+ gone = append(gone, ch.Batch.Unused...)
+ }
+ }
+ for _, ch := range p.Queue {
+ if slices.ContainsFunc(gone, func(d core.Dep) bool { return len(ch.Deps) > 0 && d.Name == ch.Deps[0].Name }) {
+ continue
+ }
+ if ch.API == nil && ch.To == "" && ch.ToName == "" && len(ch.Options) == 0 && len(ch.Deps) > 0 {
+ res = append(res, fmt.Sprintf("- `%s`: deprecated, and tend knows no replacement for it, so it stays", ch.Deps[0].Name))
+ }
+ }
+ }
+ return res
+}
+
+// issueBody is the tracking issue's text for lines, or the line that
+// closes it when there are none.
+func issueBody(lines []string) string {
+ if len(lines) == 0 {
+ return "Everything tend listed here is done or no longer needed.\n\n" + trackMarker + "\n"
+ }
+ return "tend keeps this list of what it could not do on its own, each with why. It tries each again when the code or the upstream release moves on, and takes a line off once it is done; nothing here waits on an answer.\n\n" +
+ strings.Join(lines, "\n") + "\n\n" + trackMarker + "\n"
+}
diff --git a/internal/config/config.go b/internal/config/config.go
index 6be9d4b..f5de22e 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -240,8 +240,8 @@ func Default() *Config {
//go:embed sample.yml
var Sample []byte
-// Starter is the tend.yml a first PR adds to a repo with nothing to tidy: a
-// few keys people change first, commented out, so it changes nothing.
+// Starter is the tend.yml a first PR adds to a repo with nothing to catch up
+// on: a few keys people change first, commented out, so it changes nothing.
//
//go:embed starter.yml
var Starter []byte
diff --git a/internal/config/ignore.go b/internal/config/ignore.go
index d0f11b8..dfa2d52 100644
--- a/internal/config/ignore.go
+++ b/internal/config/ignore.go
@@ -27,7 +27,7 @@ func (c *Config) Ignored(d core.Dep, to string) (string, bool) {
}
// Keeps reports whether an ignore entry names d, whatever versions it covers:
-// a tidy-up never removes a dependency tend.yml mentions.
+// the first PR never removes a dependency tend.yml mentions.
func (c *Config) Keeps(d core.Dep) bool {
for _, ig := range c.Ignore {
if (ig.Ecosystem == "" || ig.Ecosystem == d.Ecosystem) && Glob(ig.Name, d.Name) {
diff --git a/internal/config/sample.yml b/internal/config/sample.yml
index e980463..236fedc 100644
--- a/internal/config/sample.yml
+++ b/internal/config/sample.yml
@@ -4,7 +4,7 @@
# base: "" # base branch; "" means the repo's default branch
# cooldown: 3d # skip releases younger than this; security fixes and deprecations do not wait
# schedule: 1d # how often watch runs and the workflow init --ci writes: 1h to 12h, 1d or 7d
-# onboarding: pr # the first run: pr (a tidy-up PR with a welcome) | quiet (no PR, just start) | off
+# onboarding: pr # the first run: pr (one catch-up PR with a welcome) | quiet (no PR, just start) | off
# ecosystems: [] # read only these, e.g. [npm, docker, actions]; [] means all
# updates: # which changes get a pull request; a breaking change always does
diff --git a/internal/core/change.go b/internal/core/change.go
index 91ef906..7327c2a 100644
--- a/internal/core/change.go
+++ b/internal/core/change.go
@@ -9,9 +9,10 @@ const (
Breaking Kind = "breaking"
Deprecation Kind = "deprecation"
Update Kind = "update"
- // Tidy is tend's first PR on a repo, which clears out what nothing uses
- // and what is deprecated before the rest of the queue.
- Tidy Kind = "tidy"
+ // First is a catch-up PR: tend's first PR on a repo, and the stages after
+ // it, which bring the repo up to date before tend opens PRs one change at
+ // a time.
+ First Kind = "first"
)
type Change struct {
@@ -20,7 +21,7 @@ type Change struct {
Severity string // security only: low|moderate|high|critical
Level string // bumps: major|minor|patch; "" otherwise
Deps []Dep // what is bumped or replaced; several only for a group
- To string // target version/tag/ref; "" for API changes and decision-only changes
+ To string // target version/tag/ref; "" for API and decision-only changes; a security fix's least fixed release, see Patch.Landed
ToName string // replacement package when the fix swaps packages, else ""
API *APIChange
Evidence []Evidence
@@ -28,23 +29,58 @@ type Change struct {
Sunset time.Time // when the thing stops working; zero if unknown
Published time.Time // when the upstream change appeared
Sites []Site // affected call sites in this repo
- Cleanup *Cleanup `json:",omitempty"` // a tidy change: what it clears out
+ Batch *Batch `json:",omitempty"` // a catch-up PR: what it carries
+ // Steps are the releases a major bump can climb through when the jump
+ // to To fails its proof: the newest of each major in between, ascending.
+ Steps []string `json:",omitempty"`
+ Via []string `json:",omitempty"` // the steps a run climbed through to reach To
+ Choice *Choice `json:",omitempty"` // the option a run took itself, nil when none
}
-// Cleanup is what tend's first PR on a repo clears out: dependencies the
-// project declares and nothing uses, and deprecated libraries the code calls.
-type Cleanup struct {
- Unused []Dep // nothing uses them; the PR removes them
- Moves []Change // deprecated libraries the PR moves off, one change each
- Kept []Aside // they look unused, but tend cannot prove it, or removing them failed
- Left []Aside // deprecated libraries the PR does not move, with the ways off them
+// Choice is the option tend took by its own rule, and why that one.
+type Choice struct {
+ N int // 1-based, into Options
+ Why string
}
-// Aside is a dependency a cleanup names but leaves as it is.
+// Batch is what a catch-up PR carries: the queued changes of its stage and
+// the stages before it, each made as its own PR would make it, and for the
+// first one the dependencies nothing uses and a test baseline; then the
+// queued changes it leaves for a later stage.
+type Batch struct {
+ Stage int // the stage this PR completes, see plan.Tier
+ Changes []Change // what the PR makes
+ Unused []Dep // nothing uses them; the PR removes them
+ Kept []Aside // they look unused, but tend cannot prove it, or removing them failed
+ Next []Later // queued changes left for a later stage
+ Baseline *Baseline `json:",omitempty"` // tests the PR adds first, when the project's own are weak
+}
+
+// Baseline is what a catch-up PR adds so that its proof, and every later
+// one, has something to go by: a smoke test of the modules that load on the
+// base commit, and tests a model wrote of how the code behaves now.
+type Baseline struct {
+ Why string // why the project's own tests are weak
+ Files []string // the test files it adds
+ Command string // the line it adds to verify.test, "" when the project's tests run them
+ Modules int // modules the smoke test loads
+ Checks []string // build and typecheck lines it added to the proof
+ Model bool // a model wrote tests
+ Code string `json:"-"` // the files as a diff against the base
+}
+
+// Aside is a dependency a batch names but leaves as it is.
type Aside struct {
- Dep Dep
- Why string
- Options []Option // the ways off a deprecated library
+ Dep Dep
+ Why string
+}
+
+// Later is a queued change a batch leaves for later, and why: for the
+// stage it belongs to, or one it failed in. Stage 0 is past the catch-up.
+type Later struct {
+ Change Change
+ Why string
+ Stage int
}
type APIChange struct {
@@ -69,6 +105,7 @@ type Option struct {
Title string
Detail string // trade-offs, one short paragraph
Safe bool // mechanical: can be applied and proven without a model
+ Stay bool `json:",omitempty"` // keeps the version in use and has tend.yml ignore the move
Codemod *Codemod
ToName string
To string
@@ -81,3 +118,19 @@ type Codemod struct {
Fields map[string]string // field -> field; "" drops the field
Text map[string]string // literal line substitutions (actions `::set-output` -> $GITHUB_OUTPUT)
}
+
+// Calls are the sites of ch in code, leaving out the manifest lines that name
+// what it moves.
+func Calls(ch *Change) []Site {
+ var res []Site
+ for _, s := range ch.Sites {
+ named := false
+ for _, d := range ch.Deps {
+ named = named || s.File == d.Manifest.Path
+ }
+ if !named {
+ res = append(res, s)
+ }
+ }
+ return res
+}
diff --git a/internal/core/core.go b/internal/core/core.go
index bbe1e8d..3197a85 100644
--- a/internal/core/core.go
+++ b/internal/core/core.go
@@ -78,6 +78,10 @@ type Bump struct {
Files []string // changed paths, relative to root
Locked bool // the lockfile was regenerated by the native tool
Note string // why Locked is false, e.g. "pnpm not found"
+ // Landed is the release the lockfile took when it is past the one asked
+ // for: a tool that moves a dep only the lockfile names takes the newest
+ // release its ranges allow, so the release asked for is a floor.
+ Landed string
}
// Ecosystem is one self-contained file under internal/eco.
@@ -91,6 +95,8 @@ type Ecosystem interface {
Meta(ctx context.Context, f Fetcher, name string) (*Meta, error)
// Bump rewrites the requirement in d.Manifest to reach `to` (or swaps the package when
// toName != "") and regenerates the lockfile with the native tool. root is a worktree.
+ // A dep only the lockfile names reaches to or a later release of its
+ // major, which Bump.Landed then names.
Bump(ctx context.Context, root string, d Dep, to, toName string) (*Bump, error)
// Commands are the default install/build/test lines when tend.yml sets none.
Commands(root string, m Manifest) Commands
@@ -108,7 +114,7 @@ type GroupBumper interface {
}
// Remover is an ecosystem that can take dependencies out of a manifest, for
-// a tidy-up that removes what nothing uses.
+// the first PR, which removes what nothing uses.
type Remover interface {
// Remove deletes every requirement on deps, all of one manifest, and
// regenerates the lockfile with the native tool, as Bump does.
@@ -121,6 +127,31 @@ type Traits struct {
Page func(name string) string // where a person reads about a package, nil for nowhere
KeepShape bool // a tag keeps its shape across a bump: node:16-alpine moves to another -alpine tag
Transitive bool // the native tool can move a locked transitive dep by itself
+ Tooling bool // it pins what the project runs or builds on, not code it calls: runtimes, base images, CI
+}
+
+// Baseliner is an ecosystem that can give a project with weak tests a
+// baseline to prove changes against: tests it generates, where they go,
+// and the line that runs them.
+type Baseliner interface {
+ // Suite is where a manifest's generated tests go and how they run, nil
+ // when the ecosystem cannot run any for it.
+ Suite(root string, m Manifest) *Suite
+}
+
+// Suite is a place for generated tests in one ecosystem.
+type Suite struct {
+ Lang string // what the tests are written in, for the model: "JavaScript, with node:test and node:assert"
+ Smoke string // the smoke test's path, "" when the build already loads every module
+ Tests string // the path of the tests a model writes
+ Checks []string // build or typecheck lines worth adding when they pass on the base
+ Modules []string // what a smoke test would load
+ // Load is the line that loads one module and exits, Code the smoke test
+ // that loads mods, and Run the test line that runs files, "" when the
+ // project's own test lines do.
+ Load func(mod string) string
+ Code func(mods []string) string
+ Run func(files []string) string
}
// Fetcher is what internal/fetch.Client implements. Declared here so core has no deps.
diff --git a/internal/core/forge.go b/internal/core/forge.go
index 53031a4..ec92d94 100644
--- a/internal/core/forge.go
+++ b/internal/core/forge.go
@@ -58,3 +58,31 @@ type Forge interface {
Comment(ctx context.Context, number int, body string) error
AutoMerge(ctx context.Context, pr *PR, method string) error // method: merge|squash|rebase
}
+
+// CI is what a repository's own checks said about a commit.
+type CI struct {
+ State string // none|pending|success|failure
+ Failed []string // names of the checks that failed
+}
+
+// Checks is a forge that reports the CI result of a commit.
+type Checks interface {
+ Checks(ctx context.Context, sha string) (CI, error)
+}
+
+type Issue struct {
+ Number int
+ Title string
+ Body string
+ Open bool
+}
+
+// Tracker is a forge that keeps tend's one tracking issue.
+type Tracker interface {
+ // FindIssue returns the newest issue, open or closed, whose body holds
+ // marker, nil if none.
+ FindIssue(ctx context.Context, marker string) (*Issue, error)
+ CreateIssue(ctx context.Context, title, body string, labels []string) (*Issue, error)
+ // EditIssue sets the body and opens or closes the issue.
+ EditIssue(ctx context.Context, number int, body string, open bool) error
+}
diff --git a/internal/core/id.go b/internal/core/id.go
index a130c0f..b469d13 100644
--- a/internal/core/id.go
+++ b/internal/core/id.go
@@ -2,6 +2,7 @@ package core
import (
"slices"
+ "strconv"
"strings"
)
@@ -13,10 +14,13 @@ import (
// api: api// [#]
//
// A group change carries its group name in c.ID; when it has none yet, the
-// name is the longest common prefix of the dep names. A tidy change is TidyID.
+// name is the longest common prefix of the dep names. The first PR is FirstID.
func ChangeID(c *Change) string {
- if c.Kind == Tidy {
- return TidyID
+ if c.Kind == First {
+ if c.ID != "" && StageOf(c.ID) > 0 {
+ return c.ID
+ }
+ return FirstID
}
if c.API != nil {
a := c.API
@@ -39,8 +43,25 @@ func ChangeID(c *Change) string {
return d.Ecosystem + "/" + d.Name + "@" + c.To
}
-// TidyID is the id of tend's first PR on a repo, whatever it clears out.
-const TidyID = "tidy-up"
+// FirstID is the id of tend's first PR on a repo, whatever it carries. It
+// keeps the name the first PR had when it only tidied up, so a first PR an
+// earlier tend opened is updated in place.
+const FirstID = "tidy-up"
+
+// StageID is the id of a catch-up PR after the first, for stage k.
+func StageID(k int) string { return "catch-up-" + strconv.Itoa(k) }
+
+// StageOf is the stage a later catch-up PR's id names, 0 for any other id.
+func StageOf(id string) int {
+ n, err := strconv.Atoi(strings.TrimPrefix(id, "catch-up-"))
+ if err != nil || !strings.HasPrefix(id, "catch-up-") || n < 1 {
+ return 0
+ }
+ return n
+}
+
+// CatchUp reports whether id is a catch-up PR's, the first or a later one.
+func CatchUp(id string) bool { return id == FirstID || StageOf(id) > 0 }
// Names lists the packages a change moves, each once, in the order of its
// deps. One package written in two manifests, or on two lines of one, is one
diff --git a/internal/core/id_test.go b/internal/core/id_test.go
index cb555ae..bcf9017 100644
--- a/internal/core/id_test.go
+++ b/internal/core/id_test.go
@@ -21,7 +21,8 @@ func TestChangeID(t *testing.T) {
{"one image on two lines", Change{Deps: []Dep{{Ecosystem: Docker, Name: "library/node", Line: 1}, {Ecosystem: Docker, Name: "library/node", Line: 7}}, To: "24-alpine"}, "docker/library/node@24-alpine"},
{"one package in two manifests", Change{Deps: []Dep{dep(Npm, "stripe"), dep(Npm, "stripe")}, To: "16.1.0"}, "npm/stripe@16.1.0"},
{"no deps keeps id", Change{ID: "npm/moment@"}, "npm/moment@"},
- {"tidy whatever its deps", Change{Kind: Tidy, Deps: []Dep{dep(Npm, "left-pad")}}, "tidy-up"},
+ {"the first PR whatever its deps", Change{Kind: First, Deps: []Dep{dep(Npm, "left-pad")}}, "tidy-up"},
+ {"a later stage", Change{ID: StageID(3), Kind: First}, "catch-up-3"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -80,3 +81,14 @@ func TestSubject(t *testing.T) {
}
}
}
+
+func TestStageOf(t *testing.T) {
+ for id, want := range map[string]int{"catch-up-2": 2, "catch-up-4": 4, FirstID: 0, "catch-up-": 0, "catch-up-x": 0, "npm/catch-up-2@1.0.0": 0} {
+ if got := StageOf(id); got != want {
+ t.Errorf("StageOf(%q) = %d, want %d", id, got, want)
+ }
+ }
+ if !CatchUp(FirstID) || !CatchUp(StageID(2)) || CatchUp("npm/a@1.0.0") {
+ t.Error("CatchUp")
+ }
+}
diff --git a/internal/core/stages.go b/internal/core/stages.go
index 1914ac3..bf16098 100644
--- a/internal/core/stages.go
+++ b/internal/core/stages.go
@@ -10,6 +10,9 @@ type Patch struct {
Edited []string // files a model edited
Decision bool // nothing applied; the PR asks the maintainer to choose
Note string
+ // Landed maps "/" to the release a dep only the lockfile names
+ // landed on, for each that went past the change's To.
+ Landed map[string]string `json:",omitempty"`
}
type Step struct {
diff --git a/internal/deliver/body.go b/internal/deliver/body.go
index b3a4ff0..5dba2bd 100644
--- a/internal/deliver/body.go
+++ b/internal/deliver/body.go
@@ -1,6 +1,7 @@
package deliver
import (
+ "cmp"
_ "embed"
"fmt"
"html"
@@ -44,16 +45,16 @@ type BodyInput struct {
Rev int // 1 for a new PR, bumped on every update
Option int // option the maintainer picked, 0 for tend's own choice
Notes []string
- // TidyDue marks a PR that went ahead of tend's first PR, so a lost state
- // still finds the tidy-up owed.
- TidyDue bool
+ // FirstDue marks a PR that went ahead of tend's first PR, so a lost state
+ // still finds the first PR owed.
+ FirstDue bool
}
type page struct {
Heading, Why, Level string
- Welcome, Changed string // a tidy-up's, in place of the heading and Touched
+ Welcome, Batch string // the first PR's, in place of the heading and Touched
Upstream, Touched, Proof, Vetting, Notes string
- Options, Footer, ID, Base, Tidy string
+ Options, Footer, ID, Base, Due, Stage string
Rev int
}
@@ -68,13 +69,20 @@ func Body(in BodyInput) string {
Base: markerEscape.Replace(in.Base),
Rev: max(in.Rev, 1),
}
- if in.TidyDue {
- p.Tidy = "due"
+ if in.FirstDue {
+ p.Due = "due"
}
- if ch.Kind == core.Tidy && ch.Cleanup != nil {
- p.Welcome, p.Changed = welcome(ch.Cleanup), cleaned(in)
+ if ch.Kind == core.First && ch.Batch != nil {
+ p.Welcome, p.Batch = welcome(ch.Batch), batched(in)
+ if ch.ID != core.FirstID {
+ p.Welcome = intro(ch.Batch)
+ }
+ if k := ch.Batch.Stage; k > 0 {
+ p.Stage = strconv.Itoa(k)
+ }
} else {
- p.Heading, p.Why, p.Level = heading(ch), why(in), level(in)
+ at := shown(in)
+ p.Heading, p.Why, p.Level = heading(at.Change), why(in), level(at)
p.Upstream, p.Touched, p.Options = upstream(ch), touched(in), options(in)
}
if v := in.Vetting; v != nil {
@@ -85,7 +93,7 @@ func Body(in BodyInput) string {
}
res := render(p)
// The longest sections give way first; the marker always stays.
- for _, f := range []*string{&p.Upstream, &p.Proof, &p.Touched, &p.Changed, &p.Options, &p.Notes, &p.Vetting} {
+ for _, f := range []*string{&p.Upstream, &p.Proof, &p.Touched, &p.Batch, &p.Options, &p.Notes, &p.Vetting} {
if len(res) <= bodyMax {
break
}
@@ -95,6 +103,23 @@ func Body(in BodyInput) string {
return res
}
+// shown is in with its change as the patch made it: a dep only the lockfile
+// names at the release it landed on, past the least one that would do, and
+// a replacement the option it applied moves to.
+func shown(in BodyInput) BodyInput {
+ if at := landedAt(in.Patch, in.Change); at != "" {
+ ch := *in.Change
+ ch.To = at
+ in.Change = &ch
+ }
+ if o := picked(in); o != nil && o.ToName != "" && (in.Patch == nil || !in.Patch.Decision) {
+ ch := *in.Change
+ ch.ToName, ch.To = o.ToName, o.To
+ in.Change = &ch
+ }
+ return in
+}
+
func render(p page) string {
var b strings.Builder
if err := tmpl.Execute(&b, p); err != nil {
@@ -140,15 +165,27 @@ func tail(s string, n int) string {
// markerEscape keeps an id from closing the comment or the attribute it sits in.
var markerEscape = strings.NewReplacer("&", "&", `"`, """, "-->", "-->")
-var markerRe = regexp.MustCompile(``)
+var markerRe = regexp.MustCompile(``)
-// TidyDue reports whether the marker of body says tend's first PR is still
-// owed: the PR went ahead of it.
-func TidyDue(body string) bool {
+// FirstDue reports whether the marker of body says tend's first PR is still
+// owed: the PR went ahead of it. The attribute is named for the tidy-up the
+// first PR once was, which markers on open PRs still carry.
+func FirstDue(body string) bool {
all := markerRe.FindAllStringSubmatch(body, -1)
return len(all) > 0 && all[len(all)-1][4] == "due"
}
+// StageOf is the catch-up stage the marker of body names, 0 for a PR that
+// is not a catch-up PR or that an older tend opened.
+func StageOf(body string) int {
+ all := markerRe.FindAllStringSubmatch(body, -1)
+ if len(all) == 0 {
+ return 0
+ }
+ n, _ := strconv.Atoi(all[len(all)-1][5])
+ return n
+}
+
// ParseMarker reads the marker Body ends with. The last one wins.
func ParseMarker(body string) (id, base string, rev int, ok bool) {
all := markerRe.FindAllStringSubmatch(body, -1)
@@ -456,7 +493,7 @@ func touched(in BodyInput) string {
lines = append(lines, "- "+strings.Join(others, ", "))
}
res := strings.Join(lines, "\n")
- for _, s := range []string{lockOnly(ch, p), goMoved(ch, p.Diff), raised(ch)} {
+ for _, s := range []string{lockOnly(ch, p), past(ch, p), goMoved(ch, p.Diff), raised(ch)} {
if s != "" {
res += "\n\n" + s
}
@@ -503,6 +540,18 @@ func lockOnly(ch *core.Change, p *core.Patch) string {
return fmt.Sprintf("%s in %s already allows %s, so only %s changed.", code(d.Req), code(m.Path), ch.To, code(m.Lock))
}
+// past explains a dep only the lockfile names that landed past ch.To: the
+// tool moves such a dep to the newest release the ranges on it allow.
+func past(ch *core.Change, p *core.Patch) string {
+ at := landedAt(p, ch)
+ if at == "" {
+ return ""
+ }
+ d := ch.Deps[0]
+ tool := cmp.Or(d.Manifest.Tool, "the lock tool")
+ return fmt.Sprintf("tend asked for %s; %s names %s only as a dependency of other packages, and %s moves such a dependency to the newest release their ranges allow, %s.", ch.To, code(d.Manifest.Lock), code(d.Name), code(tool), at)
+}
+
// raised explains a runtime minimum: it is what the project promises to
// run on, so moving it up is a change for the people who use the project.
func raised(ch *core.Change) string {
@@ -806,11 +855,15 @@ func options(in BodyInput) string {
if applied == 0 {
res = append(res, "", "Nothing was applied. Comment on this PR with the number you want.")
}
+ if c := ch.Choice; c != nil && in.Option == 0 && applied == c.N {
+ res = append([]string{fmt.Sprintf("tend took option %d on its own: %s. Comment `tend apply N` to have another instead.", c.N, Clause(c.Why)), ""}, res...)
+ }
return strings.Join(res, "\n")
}
// appliedOption is the option the patch carries: the maintainer's pick, else
-// the first mechanical one, which is what a patch without a decision applied.
+// the one tend took by its own rule, else the first mechanical one, which is
+// what a patch without a decision applied.
func appliedOption(in BodyInput) int {
if in.Option > 0 {
return in.Option
@@ -818,6 +871,9 @@ func appliedOption(in BodyInput) int {
if in.Patch == nil || in.Patch.Decision {
return 0
}
+ if c := in.Change.Choice; c != nil {
+ return c.N
+ }
for i, o := range in.Change.Options {
if o.Safe {
return i + 1
diff --git a/internal/deliver/body.tmpl b/internal/deliver/body.tmpl
index 39e6ec8..6a513da 100644
--- a/internal/deliver/body.tmpl
+++ b/internal/deliver/body.tmpl
@@ -12,9 +12,7 @@
{{.}}
{{- end}}
-{{- with .Changed}}
-
-### What changed
+{{- with .Batch}}
{{.}}
{{- end}}
@@ -50,4 +48,4 @@
{{- end}}
{{.Footer}}
-
+
diff --git a/internal/deliver/body_test.go b/internal/deliver/body_test.go
index 7ace58d..03f22e3 100644
--- a/internal/deliver/body_test.go
+++ b/internal/deliver/body_test.go
@@ -295,37 +295,106 @@ diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
name: "tidy",
in: BodyInput{
Change: &core.Change{
- ID: core.TidyID, Kind: core.Tidy,
- Cleanup: &core.Cleanup{
+ ID: core.FirstID, Kind: core.First,
+ Batch: &core.Batch{
+ Stage: 1,
+ Changes: []core.Change{
+ {
+ ID: "npm/lodash@4.17.21", Kind: core.Security, Severity: "high", Level: "patch",
+ Deps: []core.Dep{dep("npm", "lodash", "4.17.20")}, To: "4.17.21",
+ Evidence: []core.Evidence{{Source: "osv", Title: "GHSA-35jh-r3h4-6jhm Command injection in lodash"}},
+ },
+ {
+ ID: "npm/tar@7.5.21", Kind: core.Security, Severity: "moderate", Level: "patch",
+ Deps: []core.Dep{{Ecosystem: "npm", Name: "tar", Version: "7.5.20", Manifest: core.Manifest{Path: "package.json", Lock: "package-lock.json", Tool: "npm"}}}, To: "7.5.21",
+ Evidence: []core.Evidence{{Source: "osv", Title: "GHSA-8qq5-rm4j-mr97 Arbitrary file overwrite in tar"}},
+ },
+ {
+ ID: "go/golang.org/x/net@0.38.0", Kind: core.Security, Severity: "moderate", Level: "minor",
+ Deps: []core.Dep{{Ecosystem: "go", Name: "golang.org/x/net", Version: "v0.36.0", Direct: true, Manifest: core.Manifest{Path: "go.mod"}}}, To: "v0.38.0",
+ Evidence: []core.Evidence{{Source: "osv", Title: "GO-2025-3595 Cross-site scripting in golang.org/x/net/html"}},
+ },
+ {
+ ID: "api/stripe/GET /v1/charges#source", Kind: core.Deprecation,
+ API: &core.APIChange{Provider: "stripe", Method: "GET", Path: "/v1/charges", Field: "source", What: "response field deprecated"},
+ Evidence: []core.Evidence{{Source: "openapi", Title: "source is deprecated"}},
+ },
+ {
+ ID: "npm/stripe@16.0.0", Kind: core.Deprecation,
+ Deps: []core.Dep{dep("npm", "stripe", "14.2.0")}, To: "16.0.0", Sites: stripeSites,
+ Evidence: []core.Evidence{{Source: "registry", Title: "stripe 14.2.0 is deprecated", Text: "14.x is deprecated: charges.* was replaced by paymentIntents.*"}},
+ },
+ },
Unused: []core.Dep{
{Ecosystem: "npm", Name: "@acme/colors", Version: "1.2.0", Direct: true, Manifest: core.Manifest{Path: "package.json"}},
{Ecosystem: "npm", Name: "left-pad", Version: "1.3.0", Direct: true, Manifest: core.Manifest{Path: "package.json"}},
},
- Moves: []core.Change{{
- ID: "npm/stripe@16.0.0", Kind: core.Deprecation,
- Deps: []core.Dep{dep("npm", "stripe", "14.2.0")}, To: "16.0.0", Sites: stripeSites,
- Evidence: []core.Evidence{{Source: "registry", Title: "stripe 14.2.0 is deprecated", Text: "14.x is deprecated: charges.* was replaced by paymentIntents.*"}},
- }},
Kept: []core.Aside{
{Dep: core.Dep{Ecosystem: "npm", Name: "eslint-plugin-acme", Version: "2.0.0", Manifest: core.Manifest{Path: "package.json"}},
Why: "a plugin eslint loads by a name its config gives"},
{Dep: core.Dep{Ecosystem: "npm", Name: "chalk", Version: "5.3.0", Manifest: core.Manifest{Path: "package.json"}}, Why: "with it removed, `npm test` fails (exit 1)"},
},
- Left: []core.Aside{{Dep: dep("npm", "moment", "2.30.1"), Why: "No model is configured to move the 3 call sites.",
- Options: []core.Option{{Title: "Migrate to `dayjs`"}, {Title: "Pin to 2.30.1 and ignore"}}}},
+ Next: []core.Later{
+ {Change: core.Change{
+ ID: "toolchain/nodejs@22.20.0", Kind: core.Deprecation,
+ Deps: []core.Dep{{Ecosystem: "toolchain", Name: "nodejs", Version: "18.20.4", Direct: true, Manifest: core.Manifest{Path: ".nvmrc"}}}, To: "22.20.0",
+ Evidence: []core.Evidence{{Source: "eol", Title: "Node.js 18 reached end of life on 2025-04-30"}},
+ }, Stage: 2},
+ {Change: core.Change{ID: "npm/vitest@3.2.4", Kind: core.Breaking, Level: "major", Deps: []core.Dep{dep("npm", "vitest", "1.6.0")}, To: "3.2.4"}, Stage: 3},
+ {Change: core.Change{ID: "npm/axios@1.12.0", Kind: core.Security, Level: "major", Deps: []core.Dep{dep("npm", "axios", "0.27.2")}, To: "1.12.0"},
+ Why: "with it in the batch, `npm test` fails (exit 1)", Stage: 2},
+ {Change: core.Change{ID: "npm/moment@", Kind: core.Deprecation, Deps: []core.Dep{dep("npm", "moment", "2.30.1")},
+ Options: []core.Option{{Title: "Switch to dayjs", ToName: "dayjs", To: "1.11.13"}, {Title: "Switch to luxon", ToName: "luxon", To: "3.7.2"}, {Title: "Pin to 2.30.1 and ignore", To: "2.30.1"}}},
+ Stage: 4},
+ {Change: core.Change{ID: "npm/uuid@9.0.1", Kind: core.Deprecation, Deps: []core.Dep{dep("npm", "uuid", "3.4.0")}, To: "9.0.1"},
+ Why: "making it changes no files"},
+ },
+ Baseline: &core.Baseline{
+ Why: "there is no test command",
+ Files: []string{"test/tend/characterization.js", "test/tend/smoke.js"}, Modules: 4, Model: true,
+ Command: "node --test test/tend/characterization.js test/tend/smoke.js",
+ },
+ },
+ },
+ Patch: &core.Patch{Files: []string{".nvmrc", "go.mod", "go.sum", "package-lock.json", "package.json", "src/billing.js"}, Diff: stripeDiff, Model: true,
+ Note: "4 steps: 1 read, 2 edits, 1 run; the commands passed the one time they ran",
+ Landed: map[string]string{"npm/tar": "7.5.22"}},
+ Proof: npmProof,
+ Vetting: pass("scope: 6 files, all explained by this change", "symbols: 2/2 changed calls resolve", "lockfile", "debug", "comments"),
+ Base: "abc1234def", BaseRef: "main", Rev: 1,
+ },
+ },
+ {
+ name: "catch_up_stage",
+ in: BodyInput{
+ Change: &core.Change{
+ ID: core.StageID(4), Kind: core.First,
+ Batch: &core.Batch{
+ Stage: 4,
+ Changes: []core.Change{
+ {
+ ID: "npm/express@5.1.0", Kind: core.Breaking, Level: "major",
+ Deps: []core.Dep{dep("npm", "express", "3.21.2")}, To: "5.1.0", Steps: []string{"4.21.2"}, Via: []string{"4.21.2"},
+ },
+ {
+ ID: "npm/request@", Kind: core.Deprecation, Deps: []core.Dep{dep("npm", "request", "2.88.2")},
+ Options: []core.Option{{Title: "Switch to undici", ToName: "undici", To: "7.16.0"}, {Title: "Switch to axios", ToName: "axios", To: "1.12.2"}},
+ Choice: &core.Choice{N: 2, Why: "the project already depends on axios"},
+ Sites: []core.Site{{File: "src/client.js", Line: 3, Chain: []string{"request", "get"}, Text: "request.get(url, cb)"}},
+ },
+ },
},
},
- Patch: &core.Patch{Files: []string{"package-lock.json", "package.json", "src/billing.js"}, Diff: stripeDiff, Model: true,
- Note: "4 steps: 1 read, 2 edits, 1 run; the commands passed the one time they ran"},
+ Patch: &core.Patch{Files: []string{"package-lock.json", "package.json", "src/app.js", "src/client.js"}, Model: true},
Proof: npmProof,
- Vetting: pass("scope: 3 files, all explained by this change", "symbols: 2/2 changed calls resolve", "lockfile", "debug", "comments"),
+ Vetting: pass("scope: 4 files, all explained by this change"),
Base: "abc1234def", BaseRef: "main", Rev: 1,
},
},
{
name: "tidy_welcome",
in: BodyInput{
- Change: &core.Change{ID: core.TidyID, Kind: core.Tidy, Cleanup: &core.Cleanup{}},
+ Change: &core.Change{ID: core.FirstID, Kind: core.First, Batch: &core.Batch{}},
Patch: &core.Patch{Files: []string{"tend.yml"}},
Proof: &core.Proof{Base: passRun("abc1234", ok("go test ./...", 4, "")), Patched: passRun("bbb2222", ok("go test ./...", 4, "ok example.com/app"))},
Vetting: pass("scope: 1 file, explained by this change"),
@@ -360,11 +429,13 @@ diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
// The welcome is plain: a few sentences, no exclamation marks, no emoji, and
// every way to steer tend named.
func TestWelcome(t *testing.T) {
- for _, c := range []*core.Cleanup{
+ for _, c := range []*core.Batch{
{},
{Unused: []core.Dep{{Name: "a"}}},
- {Unused: []core.Dep{{Name: "a"}, {Name: "b"}}, Moves: []core.Change{{}}, Kept: []core.Aside{{}}},
- {Left: []core.Aside{{}}},
+ {Unused: []core.Dep{{Name: "a"}, {Name: "b"}}, Changes: []core.Change{{Kind: core.Security}, {Kind: core.Deprecation}}, Kept: []core.Aside{{}}},
+ {Next: []core.Later{{}}},
+ {Stage: 1, Changes: []core.Change{{Kind: core.Security}}, Next: []core.Later{{Stage: 2}, {Stage: 4}}},
+ {Stage: 2, Next: []core.Later{{Stage: 3}}},
} {
w := welcome(c)
if n := strings.Count(w, ". ") + 1; n < 3 || n > 5 {
@@ -384,7 +455,7 @@ func TestWelcome(t *testing.T) {
}
}
// It never says it found nothing and then lists what it found.
- if len(c.Kept)+len(c.Left) > 0 && strings.Contains(w, "found nothing to tidy up") {
+ if len(c.Kept)+len(c.Next) > 0 && strings.Contains(w, "found nothing to catch up on") {
t.Errorf("welcome contradicts itself:\n%s", w)
}
}
@@ -410,6 +481,7 @@ quoted
{"empty", "", "", "", 0, false},
{"bad rev", ``, "", "", 0, false},
{"tidy-up owed", ``, "npm/a@1.0.1", "y", 2, true},
+ {"a catch-up stage", ``, "catch-up-3", "y", 1, true},
{"other comment", ``, "", "", 0, false},
}
for _, tc := range tests {
@@ -422,16 +494,29 @@ quoted
}
}
-func TestTidyDueMarker(t *testing.T) {
+func TestStageOfMarker(t *testing.T) {
+ for body, want := range map[string]int{
+ ``: 1,
+ ``: 3,
+ ``: 0,
+ "no marker": 0,
+ } {
+ if got := StageOf(body); got != want {
+ t.Errorf("StageOf(%q) = %d, want %d", body, got, want)
+ }
+ }
+}
+
+func TestFirstDueMarker(t *testing.T) {
ch := &core.Change{ID: "npm/a@1.0.1", Kind: core.Security, Deps: []core.Dep{{Ecosystem: "npm", Name: "a", Version: "1.0.0"}}, To: "1.0.1"}
- body := Body(BodyInput{Change: ch, Base: "abc", TidyDue: true})
- if !strings.Contains(body, ``) || !TidyDue(body) {
- t.Errorf("marker of a PR ahead of the tidy-up:\n%s", body)
+ body := Body(BodyInput{Change: ch, Base: "abc", FirstDue: true})
+ if !strings.Contains(body, ``) || !FirstDue(body) {
+ t.Errorf("marker of a PR ahead of the first PR:\n%s", body)
}
if id, _, _, ok := ParseMarker(body); !ok || id != "npm/a@1.0.1" {
t.Errorf("ParseMarker = %q, %v", id, ok)
}
- if body := Body(BodyInput{Change: ch, Base: "abc"}); TidyDue(body) || !strings.Contains(body, `rev="1" -->`) {
+ if body := Body(BodyInput{Change: ch, Base: "abc"}); FirstDue(body) || !strings.Contains(body, `rev="1" -->`) {
t.Errorf("marker of any other PR:\n%s", body)
}
}
diff --git a/internal/deliver/docs_test.go b/internal/deliver/docs_test.go
index 9c9b877..e8a1a29 100644
--- a/internal/deliver/docs_test.go
+++ b/internal/deliver/docs_test.go
@@ -24,7 +24,7 @@ func repoFile(t *testing.T, rel string) string {
func TestAnatomyShowsTheGoldenBodies(t *testing.T) {
doc := repoFile(t, "docs/pr-anatomy.md")
- for _, name := range []string{"breaking_bump_model", "decision", "tidy"} {
+ for _, name := range []string{"breaking_bump_model", "decision", "tidy", "catch_up_stage"} {
body := strings.TrimRight(repoFile(t, "internal/deliver/testdata/"+name+".golden.md"), "\n")
if !strings.Contains(doc, body) {
t.Errorf("docs/pr-anatomy.md does not contain testdata/%s.golden.md; regenerate the example", name)
diff --git a/internal/deliver/fake.go b/internal/deliver/fake.go
index 81b99e1..84a2220 100644
--- a/internal/deliver/fake.go
+++ b/internal/deliver/fake.go
@@ -19,20 +19,24 @@ type FakeForge struct {
Err error // returned by every call when set
Labels map[int][]string
Reviewers map[int][]string
- Merges map[int]string // auto-merge method requested per PR
- CreateErr error // returned by the next CreatePR, once
- Peak int // the most PRs open at once
+ Merges map[int]string // auto-merge method requested per PR
+ CreateErr error // returned by the next CreatePR, once
+ Peak int // the most PRs open at once
+ CI map[string]core.CI // what CI made of a commit, by sha; none when missing
mu sync.Mutex
prs []*core.PR
comments map[int][]core.Comment
closer map[int]string
nextID int64
+ issues []*core.Issue
}
var (
- _ core.Forge = (*FakeForge)(nil)
- _ Closer = (*FakeForge)(nil)
+ _ core.Forge = (*FakeForge)(nil)
+ _ Closer = (*FakeForge)(nil)
+ _ core.Checks = (*FakeForge)(nil)
+ _ core.Tracker = (*FakeForge)(nil)
)
// tendLogin is the account tend writes as on the fake forge.
@@ -44,6 +48,7 @@ func NewFake(owner, name, base string) *FakeForge {
Labels: map[int][]string{},
Reviewers: map[int][]string{},
Merges: map[int]string{},
+ CI: map[string]core.CI{},
comments: map[int][]core.Comment{},
closer: map[int]string{},
}
@@ -285,3 +290,69 @@ func (f *FakeForge) find(n int) *core.PR {
}
return f.prs[n-1]
}
+
+func (f *FakeForge) Checks(ctx context.Context, sha string) (core.CI, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.Err != nil {
+ return core.CI{}, f.Err
+ }
+ if ci, ok := f.CI[sha]; ok {
+ return ci, nil
+ }
+ return core.CI{State: "none"}, nil
+}
+
+func (f *FakeForge) FindIssue(ctx context.Context, marker string) (*core.Issue, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.Err != nil {
+ return nil, f.Err
+ }
+ for i := len(f.issues) - 1; i >= 0; i-- {
+ if strings.Contains(f.issues[i].Body, marker) {
+ res := *f.issues[i]
+ return &res, nil
+ }
+ }
+ return nil, nil
+}
+
+func (f *FakeForge) CreateIssue(ctx context.Context, title, body string, labels []string) (*core.Issue, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.Err != nil {
+ return nil, f.Err
+ }
+ is := &core.Issue{Number: 1000 + len(f.issues), Title: title, Body: body, Open: true}
+ f.issues = append(f.issues, is)
+ res := *is
+ return &res, nil
+}
+
+func (f *FakeForge) EditIssue(ctx context.Context, number int, body string, open bool) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.Err != nil {
+ return f.Err
+ }
+ for _, is := range f.issues {
+ if is.Number == number {
+ is.Body, is.Open = body, open
+ return nil
+ }
+ }
+ return fmt.Errorf("fake forge: no issue #%d", number)
+}
+
+// Issues returns copies of every issue in creation order. Their numbers
+// start at 1000, apart from the PRs'.
+func (f *FakeForge) Issues() []core.Issue {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ res := make([]core.Issue, len(f.issues))
+ for i, is := range f.issues {
+ res[i] = *is
+ }
+ return res
+}
diff --git a/internal/deliver/first.go b/internal/deliver/first.go
new file mode 100644
index 0000000..42e3912
--- /dev/null
+++ b/internal/deliver/first.go
@@ -0,0 +1,616 @@
+package deliver
+
+import (
+ "cmp"
+ "context"
+ "fmt"
+ "slices"
+ "strconv"
+ "strings"
+
+ "github.com/mohsensc/tend-cli/internal/api"
+ "github.com/mohsensc/tend-cli/internal/core"
+ "github.com/mohsensc/tend-cli/internal/plan"
+)
+
+// FirstBranch is where tend's first PR on a repo lives, whatever it carries.
+const FirstBranch = branchPrefix + core.FirstID
+
+// StageBranch is where the catch-up PR of stage k lives, for the stages
+// after the first PR.
+func StageBranch(k int) string { return branchPrefix + core.StageID(k) }
+
+// titleMax is how long a catch-up PR's title may grow before its counts are
+// summed into one.
+const titleMax = 80
+
+// firstTitle counts what a catch-up PR does: "Catch up: 12 security fixes, 1
+// deprecated library, 6 unused dependencies", or says it only sets tend up.
+func firstTitle(b *core.Batch) string {
+ did := tally(b, false)
+ switch {
+ case len(did) > 0:
+ s := "Catch up: " + strings.Join(did, ", ")
+ if len(s) > titleMax {
+ s = "Catch up: " + strings.Join(tally(b, true), ", ")
+ }
+ if len(s) > titleMax {
+ s = "Catch up: " + count(len(b.Changes)+len(b.Unused), "change", "changes")
+ }
+ return s
+ case len(b.Kept)+len(b.Next) == 0:
+ return "Set up tend: nothing to catch up on"
+ }
+ return "Set up tend"
+}
+
+// sections are the headings a catch-up PR lists its changes under, in order.
+var sections = []string{"Security", "API", "Deprecated", "Runtimes and tooling", "Upgrades"}
+
+// tally counts the changes a batch makes by what they are, in the order the
+// body lists them, then the dependencies it removes and the baseline it
+// adds. short counts every deprecation as one kind.
+func tally(b *core.Batch, short bool) []string {
+ var order []string
+ n := map[string]int{}
+ many := map[string]string{}
+ for _, s := range sections {
+ for i := range b.Changes {
+ ch := &b.Changes[i]
+ if group(ch) != s {
+ continue
+ }
+ one, more := noun(ch)
+ if short && s == "Deprecated" {
+ one, more = "deprecation", "deprecations"
+ }
+ if n[one] == 0 {
+ order = append(order, one)
+ }
+ n[one]++
+ many[one] = more
+ }
+ }
+ var res []string
+ if b.Baseline != nil {
+ res = append(res, "a test baseline")
+ }
+ for _, one := range order {
+ res = append(res, count(n[one], one, many[one]))
+ }
+ if k := len(b.Unused); k > 0 {
+ res = append(res, count(k, "unused dependency", "unused dependencies"))
+ }
+ return res
+}
+
+// group is the section of a catch-up PR a change it makes goes in.
+func group(ch *core.Change) string {
+ switch {
+ case ch.API != nil:
+ return "API"
+ case ch.Kind == core.Security:
+ return "Security"
+ case plan.Tier(ch) == plan.Runtimes:
+ return "Runtimes and tooling"
+ case ch.Kind == core.Breaking || ch.Kind == core.Update:
+ return "Upgrades"
+ }
+ return "Deprecated"
+}
+
+// noun is what a change in a catch-up PR is, for one and for many.
+func noun(ch *core.Change) (string, string) {
+ switch {
+ case ch.API != nil:
+ return "API change", "API changes"
+ case ch.Kind == core.Security:
+ return "security fix", "security fixes"
+ case len(ch.Deps) == 0:
+ return "deprecation", "deprecations"
+ case ch.Deps[0].Min:
+ return "runtime minimum", "runtime minimums"
+ }
+ switch ch.Deps[0].Ecosystem {
+ case core.Toolchain, core.Docker:
+ return "end-of-life runtime", "end-of-life runtimes"
+ case core.Actions:
+ return "deprecated Action", "deprecated Actions"
+ }
+ switch {
+ case group(ch) == "Runtimes and tooling":
+ return "build tool", "build tools"
+ case group(ch) == "Upgrades" && ch.Level == "major":
+ return "major upgrade", "major upgrades"
+ case group(ch) == "Upgrades":
+ return "upgrade", "upgrades"
+ }
+ if name, _ := plan.Target(ch); name != ch.Deps[0].Name {
+ return "replaced library", "replaced libraries"
+ }
+ return "deprecated library", "deprecated libraries"
+}
+
+func count(n int, one, many string) string { return strconv.Itoa(n) + " " + pick(n, one, many) }
+
+func pick(n int, one, many string) string {
+ if n == 1 {
+ return one
+ }
+ return many
+}
+
+// ahead counts the stages a batch leaves for later catch-up PRs.
+func ahead(b *core.Batch) int {
+ var ks []int
+ for _, l := range b.Next {
+ if l.Stage > b.Stage && !slices.Contains(ks, l.Stage) {
+ ks = append(ks, l.Stage)
+ }
+ }
+ return len(ks)
+}
+
+// welcome opens tend's first PR: what tend is, what this PR does, what
+// comes after it, and how to steer it.
+func welcome(b *core.Batch) string {
+ did := tally(b, false)
+ s := []string{"Thanks for adding tend: it looks after the packages this repository depends on and the APIs its code calls."}
+ more := ahead(b)
+ found := len(b.Kept)+len(b.Next) > 0
+ switch {
+ case len(did) > 0 && more > 0:
+ s = append(s, "This first pull request starts catching the repository up: "+and(did)+".",
+ "The rest comes in "+count(more, "more pull request", "more pull requests")+", one stage at a time, listed under Next stages and each proven the same way.")
+ case len(did) > 0:
+ s = append(s, "This first pull request catches up in one go: "+and(did)+".")
+ case more > 0:
+ s = append(s, "Its first look found nothing to fix right away, so this pull request only adds a `tend.yml` with every key commented out.",
+ "The catch-up comes in "+count(more, "more pull request", "more pull requests")+", one stage at a time, listed under Next stages.")
+ case found:
+ s = append(s, "Its first look found nothing it could fix or remove for certain, so this pull request only adds a `tend.yml` with every key commented out.")
+ default:
+ s = append(s, "Its first look found nothing to catch up on, so this pull request only adds a `tend.yml` with every key commented out.")
+ }
+ if found && more == 0 {
+ s = append(s, "What it found and left alone is listed below, for you to decide or for a pull request of its own.")
+ }
+ then := "From now on it opens one pull request at a time"
+ if more > 0 {
+ then = "Once the catch-up is done it opens one pull request at a time"
+ }
+ s = append(s,
+ then+", only for changes that touch your code, and each one shows the build and test runs that prove it.",
+ "Steer it with `tend.yml`, or comment `tend skip`, `tend retry` or `tend apply N` on its pull requests.")
+ return strings.Join(s, " ")
+}
+
+// intro opens a catch-up PR after the first: which stage it is, what it
+// does and what is left.
+func intro(b *core.Batch) string {
+ s := "This pull request carries on tend's catch-up with " + plan.StageName(b.Stage)
+ if did := tally(b, false); len(did) > 0 {
+ s += ": " + and(did)
+ }
+ s += "."
+ if more := ahead(b); more > 0 {
+ return s + " " + count(more, "more stage follows", "more stages follow") + ", listed under Next stages."
+ }
+ return s + " It is the last stage; after it, tend opens one pull request at a time, only for changes that touch your code."
+}
+
+// and joins a list the way a sentence does: "a, b and c".
+func and(s []string) string {
+ if len(s) < 2 {
+ return strings.Join(s, "")
+ }
+ return strings.Join(s[:len(s)-1], ", ") + " and " + s[len(s)-1]
+}
+
+// batched is a catch-up PR's own sections, each left out when empty: the
+// baseline, Security, one per API provider, Deprecated, Runtimes and
+// tooling, Upgrades, Unused, Next stages and Not done, after a word on the
+// parts a model wrote.
+func batched(in BodyInput) string {
+ b, p := in.Change.Batch, in.Patch
+ repl := map[string]map[int][]string{}
+ if p != nil {
+ repl = replacements(p.Diff)
+ }
+ var parts []string
+ switch {
+ case p == nil:
+ case p.Model && p.Note != "":
+ parts = append(parts, "Part of this pull request was written by a model, in "+p.Note+". The vetting section below covers it.")
+ case p.Model:
+ parts = append(parts, "Part of this pull request was written by a model. The vetting section below covers it.")
+ }
+ if s := baseline(in); s != "" {
+ parts = append(parts, "### Baseline\n\n"+s)
+ }
+ if s := secured(b.Changes, p, repl); s != "" {
+ parts = append(parts, "### Security\n\n"+s)
+ }
+ var providers []string
+ for _, ch := range b.Changes {
+ if a := ch.API; a != nil && !slices.Contains(providers, a.Provider) {
+ providers = append(providers, a.Provider)
+ }
+ }
+ for _, name := range providers {
+ var lines []string
+ for i := range b.Changes {
+ ch := &b.Changes[i]
+ if a := ch.API; a != nil && a.Provider == name {
+ lines = append(lines, "- "+code(op(a))+": "+reason(BodyInput{Change: ch}))
+ lines = append(lines, sitesMade(ch, repl)...)
+ }
+ }
+ parts = append(parts, "### "+api.Title(name)+" API\n\n"+strings.Join(lines, "\n"))
+ }
+ for _, s := range sections[2:] {
+ var lines []string
+ for i := range b.Changes {
+ ch := &b.Changes[i]
+ if group(ch) == s {
+ lines = append(lines, "- "+moved(ch))
+ lines = append(lines, sitesMade(ch, repl)...)
+ }
+ }
+ if len(lines) > 0 {
+ parts = append(parts, "### "+s+"\n\n"+strings.Join(lines, "\n"))
+ }
+ }
+ if s := unused(b); s != "" {
+ parts = append(parts, "### Unused\n\n"+s)
+ }
+ if s := stages(b); s != "" {
+ parts = append(parts, "### Next stages\n\n"+s)
+ }
+ if s := undone(b); s != "" {
+ parts = append(parts, "### Not done\n\n"+s)
+ }
+ return strings.Join(parts, "\n\n")
+}
+
+// baseline says why the PR adds tests first and what they are.
+func baseline(in BodyInput) string {
+ bl := in.Change.Batch.Baseline
+ if bl == nil {
+ return ""
+ }
+ at := baseLabel(in)
+ lines := []string{"This project's tests are too thin to prove the catch-up by: " + Clause(bl.Why) + ". So this pull request first adds tests that pin down how the code behaves on " + at + ", and every proof from here on runs them:", ""}
+ for _, f := range bl.Files {
+ switch {
+ case strings.Contains(f, "smoke") && bl.Modules == 1:
+ lines = append(lines, "- "+code(f)+": loads the one module that loads on the base commit, and exits")
+ case strings.Contains(f, "smoke"):
+ lines = append(lines, "- "+code(f)+": loads each of the "+count(bl.Modules, "module", "modules")+" that load on the base commit, and exits")
+ case bl.Model:
+ lines = append(lines, "- "+code(f)+": tests a model wrote of the current behavior")
+ default:
+ lines = append(lines, "- "+code(f))
+ }
+ }
+ for _, c := range bl.Checks {
+ lines = append(lines, "- "+code(c)+", which passes on the base commit")
+ }
+ if bl.Command != "" {
+ lines = append(lines, "- "+code(bl.Command)+" in `verify.test` in `tend.yml`, after the project's own test lines")
+ }
+ return strings.Join(append(lines, "", "They pass on "+at+": the base column of the proof below is that commit with these tests added."), "\n")
+}
+
+// secured lists the security fixes, under the ecosystem of each.
+func secured(chs []core.Change, p *core.Patch, repl map[string]map[int][]string) string {
+ var ecos []string
+ by := map[string][]string{}
+ for i := range chs {
+ ch := &chs[i]
+ if group(ch) != "Security" {
+ continue
+ }
+ e := ch.Deps[0].Ecosystem
+ if by[e] == nil {
+ ecos = append(ecos, e)
+ }
+ by[e] = append(by[e], "- "+fixed(ch, p))
+ by[e] = append(by[e], sitesMade(ch, repl)...)
+ }
+ var res []string
+ for _, e := range ecos {
+ res = append(res, e+":\n\n"+strings.Join(by[e], "\n"))
+ }
+ return strings.Join(res, "\n\n")
+}
+
+// fixed names a security fix: the package, the move, the advisories, and
+// the release the lockfile took when that is past the one that fixes them.
+func fixed(ch *core.Change, p *core.Patch) string {
+ at := landedAt(p, ch)
+ s := named(ch, cmp.Or(at, ch.To))
+ if !ch.Deps[0].Direct {
+ s += " (transitive)"
+ }
+ if ids := advisories(ch); len(ids) > 0 {
+ s += ": " + ids[0]
+ if ch.Severity != "" {
+ s += " (" + ch.Severity + ")"
+ }
+ if len(ids) > 1 {
+ s += fmt.Sprintf(" +%d more", len(ids)-1)
+ }
+ }
+ if at != "" {
+ s += "; " + ch.To + " fixes it, and the lockfile took the newest release its ranges allow"
+ }
+ return s
+}
+
+// named names what a change moves and where to: "`tar` 7.5.20 → 7.5.22".
+func named(ch *core.Change, to string) string {
+ d := ch.Deps[0]
+ s := code(depName(d))
+ if n := len(core.Names(ch)); n > 1 {
+ s = code(groupName(ch)) + fmt.Sprintf(" (%d packages)", n)
+ }
+ from := plan.Lowest(ch.Deps)
+ if from != "" {
+ s += " " + from
+ }
+ name, at := plan.Target(ch)
+ if ch.Choice == nil {
+ at = to
+ }
+ switch {
+ case name != d.Name:
+ s = strings.TrimSpace(s + " → " + code(name) + " " + at)
+ case at != "" && at != from:
+ s += " → " + at
+ }
+ return s
+}
+
+// moved names a move and what is behind it, with the file a pin sits in,
+// the releases a ladder climbed through and the option tend took.
+func moved(ch *core.Change) string {
+ if len(ch.Deps) == 0 {
+ return code(ch.ID)
+ }
+ s := named(ch, ch.To)
+ switch ch.Deps[0].Ecosystem {
+ case core.Toolchain, core.Docker, core.Actions:
+ s += " in " + code(ch.Deps[0].Manifest.Path)
+ }
+ if len(ch.Via) > 0 {
+ s += ", by way of " + and(ch.Via) + ", each proven"
+ }
+ if c := ch.Choice; c != nil && c.N <= len(ch.Options) {
+ return s + fmt.Sprintf(", picked from %d options: %s", len(ch.Options), Clause(c.Why))
+ }
+ switch ch.Kind {
+ case core.Breaking, core.Update:
+ if ch.Level != "" {
+ return s + ": a new " + ch.Level + " release"
+ }
+ return s + ": a new release"
+ }
+ return s + because(ch)
+}
+
+// because is the deprecation behind a move, after a colon, or "".
+func because(ch *core.Change) string {
+ for _, ev := range ch.Evidence {
+ if (ev.Source == "registry" || ev.Source == "archived") && ev.Text != "" {
+ return ": " + oneLine(ev.Text, 160)
+ }
+ }
+ for _, ev := range ch.Evidence {
+ if ev.Title != "" {
+ return ": " + oneLine(ev.Title, 160)
+ }
+ }
+ return ""
+}
+
+// sitesMade lists the call sites of ch the patch changed, each with what
+// replaced it, indented under the change.
+func sitesMade(ch *core.Change, repl map[string]map[int][]string) []string {
+ var made []core.Site
+ for _, s := range core.Calls(ch) {
+ if len(repl[s.File][s.Line]) > 0 {
+ made = append(made, s)
+ }
+ }
+ var res []string
+ for _, l := range siteLines(made, repl) {
+ res = append(res, " "+l)
+ }
+ return res
+}
+
+// unused lists the dependencies the first PR removes, then those it keeps
+// though they look unused, each with why.
+func unused(b *core.Batch) string {
+ var parts []string
+ if len(b.Unused) > 0 {
+ lines := []string{"Removed, since nothing in the project uses " + pick(len(b.Unused), "it:", "them:"), ""}
+ for _, d := range b.Unused {
+ lines = append(lines, "- "+declared(d))
+ }
+ parts = append(parts, strings.Join(lines, "\n"))
+ }
+ if len(b.Kept) > 0 {
+ lines := []string{"Possibly unused, kept: these look unused, but tend cannot prove it, so they are yours to decide.", ""}
+ for _, a := range b.Kept {
+ lines = append(lines, "- "+declared(a.Dep)+": "+Clause(a.Why))
+ }
+ parts = append(parts, strings.Join(lines, "\n"))
+ }
+ return strings.Join(parts, "\n\n")
+}
+
+// declared names a dependency and where the project declares it.
+func declared(d core.Dep) string {
+ s := code(d.Name)
+ if v := plan.Current(d); v != "" {
+ s += " " + v
+ }
+ if d.Manifest.Path != "" {
+ s += " in " + code(d.Manifest.Path)
+ }
+ return s
+}
+
+// stages lists the catch-up PRs still to come, stage by stage, with what
+// each will carry.
+func stages(b *core.Batch) string {
+ var ks []int
+ for _, l := range b.Next {
+ if l.Stage > b.Stage && !slices.Contains(ks, l.Stage) {
+ ks = append(ks, l.Stage)
+ }
+ }
+ if len(ks) == 0 {
+ return ""
+ }
+ slices.Sort(ks)
+ lines := []string{"Each comes as a pull request of its own once this one is merged, proven the same way.", ""}
+ for _, k := range ks {
+ lines = append(lines, strconv.Itoa(k)+". "+upper(plan.StageName(k)))
+ for _, l := range b.Next {
+ if l.Stage == k {
+ lines = append(lines, " - "+later(l))
+ }
+ }
+ }
+ return strings.Join(lines, "\n")
+}
+
+// undone lists what a batch left out with nowhere left to go: the catch-up
+// ends without it, and it comes back one change at a time.
+func undone(b *core.Batch) string {
+ var lines []string
+ for _, l := range b.Next {
+ if l.Stage <= b.Stage {
+ lines = append(lines, "- "+later(l))
+ }
+ }
+ if len(lines) == 0 {
+ return ""
+ }
+ head := "These could not be made or proven here. Each comes back as a pull request of its own after the catch-up, and tend's tracking issue keeps the list."
+ return head + "\n\n" + strings.Join(lines, "\n")
+}
+
+// later names a change a batch leaves for later, with why, and the ways off
+// it its own PR offers.
+func later(l core.Later) string {
+ ch := &l.Change
+ var s string
+ switch {
+ case ch.API != nil:
+ s = code(op(ch.API)) + " on the " + api.Title(ch.API.Provider) + " API"
+ case len(ch.Deps) == 0:
+ s = code(ch.ID)
+ default:
+ s = named(ch, ch.To)
+ if m := ch.Deps[0].Manifest.Path; m != "" && len(core.Names(ch)) == 1 {
+ s += " in " + code(m)
+ }
+ }
+ why := oneLine(Clause(l.Why), 200)
+ if why == "" {
+ why = strings.TrimSuffix(what(ch), ".")
+ }
+ line := s + ": " + why
+ if !strings.HasSuffix(why, "…") {
+ line += "."
+ }
+ if tries := plan.Ranked(ch, nil); l.Why == "" && len(tries) > 0 {
+ var names []string
+ for _, t := range tries {
+ names = append(names, choiceName(&ch.Options[t.N-1]))
+ }
+ line += " tend takes the first of " + and(names) + " its proof passes, in that order."
+ }
+ return line
+}
+
+// what says what a change waiting for a later stage is.
+func what(ch *core.Change) string {
+ switch {
+ case ch.API != nil:
+ return reason(BodyInput{Change: ch})
+ case ch.Kind == core.Breaking || ch.Kind == core.Update:
+ if ch.Level != "" {
+ return "a new " + ch.Level + " release"
+ }
+ return "a new release"
+ case len(core.Calls(ch)) > plan.Spread:
+ return fmt.Sprintf("a migration of %d call sites", len(core.Calls(ch)))
+ case len(ch.Deps) > 0 && ch.Deps[0].Min:
+ return "the oldest " + ch.Deps[0].Name + " the project supports, past its end of life"
+ case ch.To == "" && ch.ToName == "" && len(ch.Options) == 0:
+ return "deprecated, with no known replacement"
+ case ch.To == "" && ch.ToName == "":
+ return "deprecated, with no single replacement"
+ }
+ if s := because(ch); s != "" {
+ return strings.TrimPrefix(s, ": ")
+ }
+ return string(ch.Kind)
+}
+
+// choiceName is what an option moves to, as a list names it.
+func choiceName(o *core.Option) string {
+ if o.ToName != "" {
+ return code(o.ToName)
+ }
+ return o.Title
+}
+
+func upper(s string) string {
+ if s == "" {
+ return s
+ }
+ return strings.ToUpper(s[:1]) + s[1:]
+}
+
+// landedAt is the release the patch locked ch's dep at when the lockfile
+// took one past ch.To, else "".
+func landedAt(p *core.Patch, ch *core.Change) string {
+ if p == nil || len(ch.Deps) == 0 {
+ return ""
+ }
+ d := ch.Deps[0]
+ return p.Landed[d.Ecosystem+"/"+d.Name]
+}
+
+func op(a *core.APIChange) string {
+ return strings.TrimSpace(strings.ToUpper(a.Method) + " " + a.Path)
+}
+
+// Clause makes a sentence the second half of one: "No model is configured."
+// reads "no model is configured" after a colon.
+func Clause(s string) string {
+ s = strings.TrimSuffix(strings.TrimSpace(s), ".")
+ if len(s) > 1 && s[0] >= 'A' && s[0] <= 'Z' && (s[1] < 'A' || s[1] > 'Z') {
+ s = string(s[0]+'a'-'A') + s[1:]
+ }
+ return s
+}
+
+// Displaced reports whether pr was closed by tend to make room, for a
+// security fix, for the first PR or to keep one PR open, rather than
+// declined: it comes back. It reads a close the way Declined does, so a word
+// someone leaves on the PR after tend closed it does not turn the close into
+// theirs.
+func Displaced(ctx context.Context, forge core.Forge, pr *core.PR) (bool, error) {
+ if pr == nil || pr.State != "closed" {
+ return false, nil
+ }
+ no, err := Declined(ctx, forge, pr)
+ return !no, err
+}
diff --git a/internal/deliver/tidy_test.go b/internal/deliver/first_test.go
similarity index 94%
rename from internal/deliver/tidy_test.go
rename to internal/deliver/first_test.go
index 522adc7..6b27147 100644
--- a/internal/deliver/tidy_test.go
+++ b/internal/deliver/first_test.go
@@ -9,13 +9,13 @@ import (
"github.com/mohsensc/tend-cli/internal/core"
)
-// A tidy-up tend closed for a security fix comes back; one a person closed,
+// A first PR tend closed for a security fix comes back; one a person closed,
// or skipped, does not.
func TestDisplaced(t *testing.T) {
ctx := context.Background()
f := NewFake("acme", "shop", "main")
open := func() int {
- pr, err := f.CreatePR(ctx, core.PRInput{Branch: TidyBranch, Base: "main", Body: ""})
+ pr, err := f.CreatePR(ctx, core.PRInput{Branch: FirstBranch, Base: "main", Body: ""})
if err != nil {
t.Fatal(err)
}
diff --git a/internal/deliver/github_test.go b/internal/deliver/github_test.go
index aacae3c..882a954 100644
--- a/internal/deliver/github_test.go
+++ b/internal/deliver/github_test.go
@@ -29,7 +29,7 @@ type step struct {
header map[string]string
}
-type api struct {
+type stub struct {
g *GitHub
warn *bytes.Buffer
slept []time.Duration
@@ -37,7 +37,7 @@ type api struct {
// newAPI starts a server that plays steps in order. Every deviation fails the
// test; so does leaving steps unplayed.
-func newAPI(t *testing.T, steps []step) *api {
+func newAPI(t *testing.T, steps []step) *stub {
t.Helper()
var mu sync.Mutex
next := 0
@@ -68,7 +68,7 @@ func newAPI(t *testing.T, steps []step) *api {
t.Errorf("%d of %d expected requests were never made; next was %s", len(steps)-next, len(steps), steps[next].req)
}
})
- res := &api{warn: &bytes.Buffer{}}
+ res := &stub{warn: &bytes.Buffer{}}
g := NewGitHub(fetch.New("", "test"), srv.Client(), "tok", "acme", "shop").(*GitHub)
g.api, g.warn = srv.URL, res.warn
g.sleep = func(_ context.Context, d time.Duration) error { res.slept = append(res.slept, d); return nil }
diff --git a/internal/deliver/reconcile.go b/internal/deliver/reconcile.go
index 3a25773..accdb1d 100644
--- a/internal/deliver/reconcile.go
+++ b/internal/deliver/reconcile.go
@@ -8,6 +8,7 @@ import (
"time"
"github.com/mohsensc/tend-cli/internal/core"
+ "github.com/mohsensc/tend-cli/internal/plan"
"github.com/mohsensc/tend-cli/internal/state"
)
@@ -87,6 +88,9 @@ func finish(ctx context.Context, forge core.Forge, st *state.State, pr *core.PR)
s := st.Seen[o.ID]
s.Verdict = "delivered"
st.Seen[o.ID] = s
+ if core.CatchUp(o.ID) {
+ st.Stage = max(st.Stage, o.Stage, StageOf(pr.Body))
+ }
st.Open = nil
return nil
}
@@ -108,6 +112,11 @@ func finish(ctx context.Context, forge core.Forge, st *state.State, pr *core.PR)
st.Parked = map[string]state.Parked{}
}
st.Parked[o.ID] = state.Parked{PR: o.PR, Reason: "rejected", To: core.TargetOf(o.ID), At: now()}
+ // A later catch-up PR closed unmerged ends the catch-up: what it held
+ // comes back one change at a time.
+ if core.StageOf(o.ID) > 0 {
+ st.Stage = plan.Last
+ }
st.Open = nil
return nil
}
diff --git a/internal/deliver/reconcile_test.go b/internal/deliver/reconcile_test.go
index c2e6711..cbe3ace 100644
--- a/internal/deliver/reconcile_test.go
+++ b/internal/deliver/reconcile_test.go
@@ -2,6 +2,7 @@ package deliver
import (
"errors"
+ "reflect"
"strings"
"testing"
"time"
@@ -80,7 +81,7 @@ func TestReconcile(t *testing.T) {
t.Fatalf("got %+v", got)
}
want := state.OpenPR{ID: "npm/a@2.0.0", PR: 1, Branch: "tend/npm-a-2.0.0", Base: "main", At: clock}
- if st.Open == nil || *st.Open != want {
+ if st.Open == nil || !reflect.DeepEqual(*st.Open, want) {
t.Errorf("open = %+v, want %+v", st.Open, want)
}
},
diff --git a/internal/deliver/testdata/catch_up_stage.golden.md b/internal/deliver/testdata/catch_up_stage.golden.md
new file mode 100644
index 0000000..a7f189d
--- /dev/null
+++ b/internal/deliver/testdata/catch_up_stage.golden.md
@@ -0,0 +1,35 @@
+This pull request carries on tend's catch-up with migrations and replacements: 1 replaced library and 1 major upgrade. It is the last stage; after it, tend opens one pull request at a time, only for changes that touch your code.
+
+Part of this pull request was written by a model. The vetting section below covers it.
+
+### Deprecated
+
+- `request` 2.88.2 → `axios` 1.12.2, picked from 2 options: the project already depends on axios
+
+### Upgrades
+
+- `express` 3.21.2 → 5.1.0, by way of 4.21.2, each proven: a new major release
+
+### Proof
+
+| step | base (main@abc1234) | patched |
+|---|---|---|
+| `npm ci` | ok · 12s | ok · 13s |
+| `npm test` | ok · 30s | ok · 31s |
+
+npm test (patched), end of its output
+
+```
+TAP version 13
+ok 1 - payment intents
+1..1
+# pass 1
+```
+
+
+### Vetting
+
+- scope: 4 files, all explained by this change
+
+tend · comment `tend skip` or `tend retry`
+
diff --git a/internal/deliver/testdata/tidy.golden.md b/internal/deliver/testdata/tidy.golden.md
index c4ef766..e8ab03d 100644
--- a/internal/deliver/testdata/tidy.golden.md
+++ b/internal/deliver/testdata/tidy.golden.md
@@ -1,32 +1,67 @@
-Thanks for adding tend: it looks after the packages this repository depends on and the APIs its code calls. This first pull request tidies up: it removes 2 dependencies nothing in the project uses and moves the code off 1 deprecated library. What it found and left alone is listed below, for you to decide. From now on it opens one pull request at a time, only for changes that touch your code, and each one shows the build and test runs that prove it. Steer it with `tend.yml`, or comment `tend skip`, `tend retry` or `tend apply N` on its pull requests.
+Thanks for adding tend: it looks after the packages this repository depends on and the APIs its code calls. This first pull request starts catching the repository up: a test baseline, 3 security fixes, 1 API change, 1 deprecated library and 2 unused dependencies. The rest comes in 3 more pull requests, one stage at a time, listed under Next stages and each proven the same way. Once the catch-up is done it opens one pull request at a time, only for changes that touch your code, and each one shows the build and test runs that prove it. Steer it with `tend.yml`, or comment `tend skip`, `tend retry` or `tend apply N` on its pull requests.
-### What changed
+Part of this pull request was written by a model, in 4 steps: 1 read, 2 edits, 1 run; the commands passed the one time they ran. The vetting section below covers it.
-Removed, since nothing in the project uses them:
+### Baseline
-- `@acme/colors` 1.2.0 in `package.json`
-- `left-pad` 1.3.0 in `package.json`
+This project's tests are too thin to prove the catch-up by: there is no test command. So this pull request first adds tests that pin down how the code behaves on main@abc1234, and every proof from here on runs them:
+
+- `test/tend/characterization.js`: tests a model wrote of the current behavior
+- `test/tend/smoke.js`: loads each of the 4 modules that load on the base commit, and exits
+- `node --test test/tend/characterization.js test/tend/smoke.js` in `verify.test` in `tend.yml`, after the project's own test lines
+
+They pass on main@abc1234: the base column of the proof below is that commit with these tests added.
+
+### Security
+
+npm:
+
+- `lodash` 4.17.20 → 4.17.21: GHSA-35jh-r3h4-6jhm (high)
+- `tar` 7.5.20 → 7.5.22 (transitive): GHSA-8qq5-rm4j-mr97 (moderate); 7.5.21 fixes it, and the lockfile took the newest release its ranges allow
+
+go:
+
+- `golang.org/x/net` v0.36.0 → v0.38.0: GO-2025-3595 (moderate)
-Moved off a deprecated library:
+### Stripe API
+
+- `GET /v1/charges`: response field deprecated (source)
+
+### Deprecated
- `stripe` 14.2.0 → 16.0.0: 14.x is deprecated: charges.* was replaced by paymentIntents.*
- `src/billing.js:42` `const c = await stripe.charges.create({ amount: order.total })` → `const c = await stripe.paymentIntents.create({ amount: order.total })`
- `src/billing.js:88` `return stripe.charges.retrieve(id)` → `return stripe.paymentIntents.retrieve(id)`
+### Unused
+
+Removed, since nothing in the project uses them:
+
+- `@acme/colors` 1.2.0 in `package.json`
+- `left-pad` 1.3.0 in `package.json`
+
Possibly unused, kept: these look unused, but tend cannot prove it, so they are yours to decide.
- `eslint-plugin-acme` 2.0.0 in `package.json`: a plugin eslint loads by a name its config gives
- `chalk` 5.3.0 in `package.json`: with it removed, `npm test` fails (exit 1)
-Deprecated, not moved: each gets a pull request of its own after this one.
+### Next stages
+
+Each comes as a pull request of its own once this one is merged, proven the same way.
+
+2. Runtimes and build tooling
+ - `nodejs` 18.20.4 → 22.20.0 in `.nvmrc`: Node.js 18 reached end of life on 2025-04-30.
+ - `axios` 0.27.2 → 1.12.0: with it in the batch, `npm test` fails (exit 1).
+3. Major upgrades
+ - `vitest` 1.6.0 → 3.2.4: a new major release.
+4. Migrations and replacements
+ - `moment` 2.30.1: deprecated, with no single replacement. tend takes the first of `dayjs` and `luxon` its proof passes, in that order.
-- `moment` 2.30.1: no model is configured to move the 3 call sites. `tend apply N` on its pull request picks one of:
- 1. Migrate to `dayjs`
- 2. Pin to 2.30.1 and ignore
+### Not done
-Files: `package-lock.json`, `package.json`, `src/billing.js`.
+These could not be made or proven here. Each comes back as a pull request of its own after the catch-up, and tend's tracking issue keeps the list.
-Part of this change was written by a model, in 4 steps: 1 read, 2 edits, 1 run; the commands passed the one time they ran. The vetting section below covers it.
+- `uuid` 3.4.0 → 9.0.1: making it changes no files.
### Proof
@@ -47,11 +82,11 @@ ok 1 - payment intents
### Vetting
-- scope: 3 files, all explained by this change
+- scope: 6 files, all explained by this change
- symbols: 2/2 changed calls resolve
- lockfile: only the bumped packages and their dependencies changed
- debug: nothing added
- comments: nothing added
tend · comment `tend skip` or `tend retry`
-
+
diff --git a/internal/deliver/testdata/tidy_welcome.golden.md b/internal/deliver/testdata/tidy_welcome.golden.md
index b54c6fc..f9e8789 100644
--- a/internal/deliver/testdata/tidy_welcome.golden.md
+++ b/internal/deliver/testdata/tidy_welcome.golden.md
@@ -1,8 +1,4 @@
-Thanks for adding tend: it looks after the packages this repository depends on and the APIs its code calls. Its first look found nothing to tidy up, so this pull request only adds a `tend.yml` with every key commented out. From now on it opens one pull request at a time, only for changes that touch your code, and each one shows the build and test runs that prove it. Steer it with `tend.yml`, or comment `tend skip`, `tend retry` or `tend apply N` on its pull requests.
-
-### What changed
-
-Adds `tend.yml` with every key commented out, so it changes nothing until you uncomment a line.
+Thanks for adding tend: it looks after the packages this repository depends on and the APIs its code calls. Its first look found nothing to catch up on, so this pull request only adds a `tend.yml` with every key commented out. From now on it opens one pull request at a time, only for changes that touch your code, and each one shows the build and test runs that prove it. Steer it with `tend.yml`, or comment `tend skip`, `tend retry` or `tend apply N` on its pull requests.
### Proof
diff --git a/internal/deliver/tidy.go b/internal/deliver/tidy.go
deleted file mode 100644
index e87c49a..0000000
--- a/internal/deliver/tidy.go
+++ /dev/null
@@ -1,196 +0,0 @@
-package deliver
-
-import (
- "context"
- "fmt"
- "slices"
- "strconv"
- "strings"
-
- "github.com/mohsensc/tend-cli/internal/core"
- "github.com/mohsensc/tend-cli/internal/plan"
-)
-
-// TidyBranch is where tend's first PR on a repo lives, whatever it tidies.
-const TidyBranch = branchPrefix + core.TidyID
-
-// tidyTitle says what the tidy-up does: "Tidy up: remove 4 unused
-// dependencies, move off 1 deprecated library", or that it only sets tend up.
-func tidyTitle(c *core.Cleanup) string {
- var did []string
- if n := len(c.Unused); n > 0 {
- did = append(did, "remove "+count(n, "unused dependency", "unused dependencies"))
- }
- if n := len(c.Moves); n > 0 {
- did = append(did, "move off "+count(n, "deprecated library", "deprecated libraries"))
- }
- switch {
- case len(did) > 0:
- return "Tidy up: " + strings.Join(did, ", ")
- case len(c.Kept)+len(c.Left) == 0:
- return "Set up tend: nothing to tidy up"
- }
- return "Set up tend"
-}
-
-func count(n int, one, many string) string { return strconv.Itoa(n) + " " + pick(n, one, many) }
-
-func pick(n int, one, many string) string {
- if n == 1 {
- return one
- }
- return many
-}
-
-// welcome opens tend's first PR: what tend is, what this PR does, what it
-// does from now on, and how to steer it.
-func welcome(c *core.Cleanup) string {
- var did []string
- if n := len(c.Unused); n > 0 {
- did = append(did, "removes "+count(n, "dependency", "dependencies")+" nothing in the project uses")
- }
- if n := len(c.Moves); n > 0 {
- did = append(did, "moves the code off "+count(n, "deprecated library", "deprecated libraries"))
- }
- s := []string{"Thanks for adding tend: it looks after the packages this repository depends on and the APIs its code calls."}
- found := len(c.Kept)+len(c.Left) > 0
- switch {
- case len(did) > 0:
- s = append(s, "This first pull request tidies up: it "+strings.Join(did, " and ")+".")
- case found:
- s = append(s, "Its first look found nothing it could remove or move for certain, so this pull request only adds a `tend.yml` with every key commented out.")
- default:
- s = append(s, "Its first look found nothing to tidy up, so this pull request only adds a `tend.yml` with every key commented out.")
- }
- if found {
- s = append(s, "What it found and left alone is listed below, for you to decide.")
- }
- s = append(s,
- "From now on it opens one pull request at a time, only for changes that touch your code, and each one shows the build and test runs that prove it.",
- "Steer it with `tend.yml`, or comment `tend skip`, `tend retry` or `tend apply N` on its pull requests.")
- return strings.Join(s, " ")
-}
-
-// cleaned is a tidy-up's What changed section: what it removed and moved,
-// then what it names and leaves alone, each with why.
-func cleaned(in BodyInput) string {
- c, p := in.Change.Cleanup, in.Patch
- var parts []string
- if len(c.Unused) > 0 {
- lines := []string{"Removed, since nothing in the project uses " + pick(len(c.Unused), "it:", "them:"), ""}
- for _, d := range c.Unused {
- lines = append(lines, "- "+declared(d))
- }
- parts = append(parts, strings.Join(lines, "\n"))
- }
- if len(c.Moves) > 0 {
- lines := []string{"Moved off " + pick(len(c.Moves), "a deprecated library:", "deprecated libraries:"), ""}
- repl := map[string]map[int][]string{}
- if p != nil {
- repl = replacements(p.Diff)
- }
- for _, m := range c.Moves {
- lines = append(lines, "- "+moved(&m))
- for _, l := range siteLines(m.Sites, repl) {
- lines = append(lines, " "+l)
- }
- }
- parts = append(parts, strings.Join(lines, "\n"))
- }
- if len(c.Kept) > 0 {
- lines := []string{"Possibly unused, kept: these look unused, but tend cannot prove it, so they are yours to decide.", ""}
- for _, a := range c.Kept {
- lines = append(lines, "- "+declared(a.Dep)+": "+clause(a.Why))
- }
- parts = append(parts, strings.Join(lines, "\n"))
- }
- if len(c.Left) > 0 {
- parts = append(parts, left(c.Left))
- }
- switch {
- case p == nil || len(p.Files) == 0:
- case len(c.Unused)+len(c.Moves) == 0 && slices.Equal(p.Files, []string{"tend.yml"}):
- parts = append(parts, "Adds `tend.yml` with every key commented out, so it changes nothing until you uncomment a line.")
- default:
- var files []string
- for _, f := range p.Files {
- files = append(files, code(f))
- }
- parts = append(parts, "Files: "+strings.Join(files, ", ")+".")
- }
- if p != nil && p.Model {
- s := "Part of this change was written by a model. The vetting section below covers it."
- if p.Note != "" {
- s = "Part of this change was written by a model, in " + p.Note + ". The vetting section below covers it."
- }
- parts = append(parts, s)
- }
- return strings.Join(parts, "\n\n")
-}
-
-// declared names a dependency and where the project declares it.
-func declared(d core.Dep) string {
- s := code(d.Name)
- if v := plan.Current(d); v != "" {
- s += " " + v
- }
- if d.Manifest.Path != "" {
- s += " in " + code(d.Manifest.Path)
- }
- return s
-}
-
-// moved names a library move and the deprecation behind it.
-func moved(m *core.Change) string {
- d := m.Deps[0]
- s := code(d.Name) + " " + plan.Current(d) + " → "
- if m.ToName != "" {
- s += code(m.ToName) + " "
- }
- s += m.To
- for _, ev := range m.Evidence {
- if (ev.Source == "registry" || ev.Source == "archived") && ev.Text != "" {
- return s + ": " + oneLine(ev.Text, 160)
- }
- }
- return s
-}
-
-// left lists the deprecated libraries the tidy-up does not move, with why,
-// and the ways off each, which its own PR offers next.
-func left(as []core.Aside) string {
- lines := []string{"Deprecated, not moved: each gets a pull request of its own after this one.", ""}
- for _, a := range as {
- line := "- " + declared(a.Dep) + ": " + clause(a.Why) + "."
- if len(a.Options) > 0 {
- line += " `tend apply N` on its pull request picks one of:"
- }
- lines = append(lines, line)
- for i, o := range a.Options {
- lines = append(lines, fmt.Sprintf(" %d. %s", i+1, o.Title))
- }
- }
- return strings.Join(lines, "\n")
-}
-
-// clause makes a sentence the second half of one: "No model is configured."
-// reads "no model is configured" after a colon.
-func clause(s string) string {
- s = strings.TrimSuffix(strings.TrimSpace(s), ".")
- if len(s) > 1 && s[0] >= 'A' && s[0] <= 'Z' && (s[1] < 'A' || s[1] > 'Z') {
- s = string(s[0]+'a'-'A') + s[1:]
- }
- return s
-}
-
-// Displaced reports whether pr was closed by tend to make room, for a
-// security fix or to keep one PR open, rather than declined: it comes back.
-// It reads a close the way Declined does, so a word someone leaves on the
-// PR after tend closed it does not turn the close into theirs.
-func Displaced(ctx context.Context, forge core.Forge, pr *core.PR) (bool, error) {
- if pr == nil || pr.State != "closed" {
- return false, nil
- }
- no, err := Declined(ctx, forge, pr)
- return !no, err
-}
diff --git a/internal/deliver/title.go b/internal/deliver/title.go
index e9847a0..798ca0f 100644
--- a/internal/deliver/title.go
+++ b/internal/deliver/title.go
@@ -4,6 +4,7 @@ import (
"fmt"
"strings"
+ "github.com/mohsensc/tend-cli/internal/api"
"github.com/mohsensc/tend-cli/internal/core"
"github.com/mohsensc/tend-cli/internal/ver"
)
@@ -13,9 +14,9 @@ const branchMax = 100
// Title is the PR title and commit subject, with prefix prepended verbatim. It
// names what the PR carries: a decision asks, a pin pins, anything else moves.
func Title(in BodyInput, prefix string) string {
- ch := in.Change
- if ch.Kind == core.Tidy && ch.Cleanup != nil {
- return prefix + tidyTitle(ch.Cleanup)
+ ch := shown(in).Change
+ if ch.Kind == core.First && ch.Batch != nil {
+ return prefix + firstTitle(ch.Batch)
}
if p := in.Patch; p != nil && p.Decision && len(ch.Options) > 0 {
return prefix + decide(ch)
@@ -47,9 +48,14 @@ func decide(ch *core.Change) string {
return "Decide: migrate off " + depName(d)
}
-// picked is the option the PR carries, if the maintainer picked one.
+// picked is the option the PR carries, if the maintainer picked one or tend
+// took one by its own rule.
func picked(in BodyInput) *core.Option {
- if n := in.Option; n > 0 && n <= len(in.Change.Options) {
+ n := in.Option
+ if c := in.Change.Choice; n == 0 && c != nil {
+ n = c.N
+ }
+ if n > 0 && n <= len(in.Change.Options) {
return &in.Change.Options[n-1]
}
return nil
@@ -57,7 +63,7 @@ func picked(in BodyInput) *core.Option {
// pins reports whether o keeps the version in use rather than moving off it.
func pins(ch *core.Change, o *core.Option) bool {
- return len(ch.Deps) > 0 && o.ToName == "" && o.Codemod == nil && o.To != "" && o.To == ch.Deps[0].Version
+ return len(ch.Deps) > 0 && (o.Stay || o.ToName == "" && o.Codemod == nil && o.To != "" && o.To == ch.Deps[0].Version)
}
func title(ch *core.Change) string {
@@ -108,7 +114,7 @@ func apiTitle(a *core.APIChange) string {
subject := op
switch {
case a.Field != "" && op == "":
- subject = noun + " " + a.Field + " of the " + a.Provider + " API"
+ subject = noun + " " + a.Field + " of the " + api.Title(a.Provider) + " API"
case a.Field != "":
subject = noun + " " + a.Field + " on " + op
}
@@ -170,10 +176,14 @@ func groupName(ch *core.Change) string {
}
// Branch is tend/--, tend/-group--,
-// tend/api--, or TidyBranch for tend's first PR.
+// tend/api--, FirstBranch for tend's first PR, or
+// StageBranch for a later catch-up PR.
func Branch(ch *core.Change) string {
- if ch.Kind == core.Tidy {
- return TidyBranch
+ if ch.Kind == core.First {
+ if k := core.StageOf(ch.ID); k > 0 {
+ return StageBranch(k)
+ }
+ return FirstBranch
}
if a := ch.API; a != nil {
op := strings.TrimSpace(strings.ToUpper(a.Method) + " " + a.Path)
diff --git a/internal/deliver/title_test.go b/internal/deliver/title_test.go
index d3cbd45..78fae19 100644
--- a/internal/deliver/title_test.go
+++ b/internal/deliver/title_test.go
@@ -1,6 +1,7 @@
package deliver
import (
+ "slices"
"strings"
"testing"
@@ -15,11 +16,46 @@ func advisory(source, id, summary string) core.Evidence {
return core.Evidence{Source: source, Title: id + " " + summary}
}
+// A dep only the lockfile names that landed past the release asked for is
+// titled with the release it landed on; its branch keeps the target.
+func TestTitleLanded(t *testing.T) {
+ ch := &core.Change{ID: "npm/tar@7.5.21", Kind: core.Security, Deps: []core.Dep{{Ecosystem: "npm", Name: "tar", Version: "7.5.20"}}, To: "7.5.21",
+ Evidence: []core.Evidence{advisory("osv", "GHSA-8qq5-rm4j-mr97", "file overwrite")}}
+ in := BodyInput{Change: ch, Patch: &core.Patch{Landed: map[string]string{"npm/tar": "7.5.22"}}}
+ if got := Title(in, ""); got != "Bump tar to 7.5.22 (fixes GHSA-8qq5-rm4j-mr97)" {
+ t.Errorf("title = %q", got)
+ }
+ if got := Branch(ch); got != "tend/npm-tar-7.5.21" {
+ t.Errorf("branch = %q", got)
+ }
+ ch.Deps[0].Manifest = core.Manifest{Path: "package.json", Lock: "package-lock.json", Tool: "npm"}
+ in.Patch.Files = []string{"package-lock.json"}
+ body := Body(in)
+ for _, want := range []string{
+ "## tar 7.5.20 → 7.5.22",
+ "fixed in 7.5.21",
+ "tend asked for 7.5.21; `package-lock.json` names `tar` only as a dependency of other packages, and `npm` moves such a dependency to the newest release their ranges allow, 7.5.22.",
+ } {
+ if !strings.Contains(body, want) {
+ t.Errorf("body lacks %q:\n%s", want, body)
+ }
+ }
+}
+
func TestTitleAndBranch(t *testing.T) {
- tidy := func(c core.Cleanup) core.Change {
- return core.Change{ID: core.TidyID, Kind: core.Tidy, Deps: []core.Dep{dep("npm", "left-pad", "1.3.0")}, Cleanup: &c}
+ first := func(b core.Batch) core.Change {
+ return core.Change{ID: core.FirstID, Kind: core.First, Deps: []core.Dep{dep("npm", "left-pad", "1.3.0")}, Batch: &b}
}
+ sec := core.Change{Kind: core.Security, Deps: []core.Dep{dep("npm", "a", "1.0.0")}}
+ lib := core.Change{Kind: core.Deprecation, Deps: []core.Dep{dep("npm", "a", "1.0.0")}}
+ pin := core.Change{Kind: core.Deprecation, Deps: []core.Dep{{Ecosystem: core.Toolchain, Name: "nodejs"}}}
+ act := core.Change{Kind: core.Deprecation, Deps: []core.Dep{{Ecosystem: core.Actions, Name: "actions/checkout"}}}
+ api := core.Change{Kind: core.Breaking, API: &core.APIChange{Provider: "stripe"}}
two := []core.Dep{dep("npm", "a", "1.0.0"), dep("npm", "b", "1.0.0")}
+ var twelve []core.Change
+ for range 12 {
+ twelve = append(twelve, sec)
+ }
tests := []struct {
name string
ch core.Change
@@ -28,33 +64,39 @@ func TestTitleAndBranch(t *testing.T) {
branch string
}{
{
- name: "tidy-up",
- ch: tidy(core.Cleanup{Unused: append(two, two...), Moves: []core.Change{{}}}),
- title: "Tidy up: remove 4 unused dependencies, move off 1 deprecated library",
+ name: "first PR",
+ ch: first(core.Batch{Unused: append(append(two, two...), two...), Changes: append(slices.Clone(twelve), lib)}),
+ title: "Catch up: 12 security fixes, 1 deprecated library, 6 unused dependencies",
branch: "tend/tidy-up",
},
{
- name: "tidy-up that removes one",
- ch: tidy(core.Cleanup{Unused: two[:1]}),
+ name: "first PR that removes one",
+ ch: first(core.Batch{Unused: two[:1]}),
prefix: "chore: ",
- title: "chore: Tidy up: remove 1 unused dependency",
+ title: "chore: Catch up: 1 unused dependency",
+ branch: "tend/tidy-up",
+ },
+ {
+ name: "first PR of every kind, in the order of its sections",
+ ch: first(core.Batch{Changes: []core.Change{act, api, sec}}),
+ title: "Catch up: 1 security fix, 1 API change, 1 deprecated Action",
branch: "tend/tidy-up",
},
{
- name: "tidy-up that moves two",
- ch: tidy(core.Cleanup{Moves: []core.Change{{}, {}}}),
- title: "Tidy up: move off 2 deprecated libraries",
+ name: "first PR whose kinds make a long title",
+ ch: first(core.Batch{Changes: []core.Change{pin, lib, api, sec, act}, Unused: two}),
+ title: "Catch up: 1 security fix, 1 API change, 3 deprecations, 2 unused dependencies",
branch: "tend/tidy-up",
},
{
- name: "nothing to tidy",
- ch: tidy(core.Cleanup{}),
- title: "Set up tend: nothing to tidy up",
+ name: "nothing to catch up on",
+ ch: first(core.Batch{}),
+ title: "Set up tend: nothing to catch up on",
branch: "tend/tidy-up",
},
{
- name: "nothing tidied, things to look at",
- ch: tidy(core.Cleanup{Kept: []core.Aside{{}}}),
+ name: "nothing made, things to look at",
+ ch: first(core.Batch{Kept: []core.Aside{{}}}),
title: "Set up tend",
branch: "tend/tidy-up",
},
diff --git a/internal/deliver/track.go b/internal/deliver/track.go
new file mode 100644
index 0000000..56d97ba
--- /dev/null
+++ b/internal/deliver/track.go
@@ -0,0 +1,138 @@
+package deliver
+
+import (
+ "context"
+ "slices"
+ "strconv"
+ "strings"
+
+ "github.com/mohsensc/tend-cli/internal/core"
+)
+
+var (
+ _ core.Checks = (*GitHub)(nil)
+ _ core.Tracker = (*GitHub)(nil)
+)
+
+// Checks reads what the repository's CI made of a commit: its check runs
+// and its commit statuses together. A cancelled or skipped check says
+// nothing either way.
+func (g *GitHub) Checks(ctx context.Context, sha string) (core.CI, error) {
+ var runs struct {
+ Runs []struct {
+ Name string `json:"name"`
+ Status string `json:"status"`
+ Conclusion string `json:"conclusion"`
+ } `json:"check_runs"`
+ }
+ if err := g.do(ctx, "GET", g.repoPath("/commits/"+sha+"/check-runs?per_page=100"), nil, &runs); err != nil {
+ return core.CI{}, err
+ }
+ var status struct {
+ Statuses []struct {
+ Context string `json:"context"`
+ State string `json:"state"`
+ } `json:"statuses"`
+ }
+ if err := g.do(ctx, "GET", g.repoPath("/commits/"+sha+"/status"), nil, &status); err != nil {
+ return core.CI{}, err
+ }
+ var res []ciCheck
+ for _, r := range runs.Runs {
+ c := ciCheck{r.Name, "success"}
+ switch {
+ case r.Status != "completed":
+ c.state = "pending"
+ case slices.Contains([]string{"failure", "timed_out", "action_required", "startup_failure"}, r.Conclusion):
+ c.state = "failure"
+ case r.Conclusion == "cancelled" || r.Conclusion == "skipped" || r.Conclusion == "stale":
+ continue
+ }
+ res = append(res, c)
+ }
+ for _, s := range status.Statuses {
+ c := ciCheck{s.Context, s.State}
+ if s.State == "error" {
+ c.state = "failure"
+ }
+ res = append(res, c)
+ }
+ return verdict(res), nil
+}
+
+type ciCheck struct{ name, state string }
+
+// verdict sums up checks: a failure, else one still running, else success,
+// or none when there are no checks at all.
+func verdict(cs []ciCheck) core.CI {
+ res := core.CI{State: "none"}
+ for _, c := range cs {
+ switch {
+ case c.state == "failure":
+ res.State = "failure"
+ res.Failed = append(res.Failed, c.name)
+ case c.state == "pending" && res.State != "failure":
+ res.State = "pending"
+ case res.State == "none":
+ res.State = "success"
+ }
+ }
+ slices.Sort(res.Failed)
+ res.Failed = slices.Compact(res.Failed)
+ return res
+}
+
+type issue struct {
+ Number int `json:"number"`
+ Title string `json:"title"`
+ Body string `json:"body"`
+ State string `json:"state"`
+ Pull *struct {
+ URL string `json:"url"`
+ } `json:"pull_request"`
+}
+
+func (i issue) issue() *core.Issue {
+ return &core.Issue{Number: i.Number, Title: i.Title, Body: i.Body, Open: i.State == "open"}
+}
+
+// FindIssue looks through the issues tend's account opened for the one
+// whose body holds marker, newest first. Pull requests, which the issues
+// API lists too, never count.
+func (g *GitHub) FindIssue(ctx context.Context, marker string) (*core.Issue, error) {
+ all, err := getAll[issue](ctx, g, g.repoPath("/issues?state=all&sort=created&direction=desc"))
+ if err != nil {
+ return nil, err
+ }
+ for _, i := range all {
+ if i.Pull == nil && strings.Contains(i.Body, marker) {
+ return i.issue(), nil
+ }
+ }
+ return nil, nil
+}
+
+func (g *GitHub) CreateIssue(ctx context.Context, title, body string, labels []string) (*core.Issue, error) {
+ for _, n := range labels {
+ if err := g.ensureLabel(ctx, n); err != nil {
+ return nil, err
+ }
+ }
+ var res issue
+ in := map[string]any{"title": title, "body": body}
+ if len(labels) > 0 {
+ in["labels"] = labels
+ }
+ if err := g.do(ctx, "POST", g.repoPath("/issues"), in, &res); err != nil {
+ return nil, err
+ }
+ return res.issue(), nil
+}
+
+func (g *GitHub) EditIssue(ctx context.Context, number int, body string, open bool) error {
+ state := "closed"
+ if open {
+ state = "open"
+ }
+ return g.do(ctx, "PATCH", g.repoPath("/issues/"+strconv.Itoa(number)), map[string]any{"body": body, "state": state}, nil)
+}
diff --git a/internal/deliver/track_test.go b/internal/deliver/track_test.go
new file mode 100644
index 0000000..9b06cfc
--- /dev/null
+++ b/internal/deliver/track_test.go
@@ -0,0 +1,69 @@
+package deliver
+
+import (
+ "context"
+ "reflect"
+ "testing"
+
+ "github.com/mohsensc/tend-cli/internal/core"
+)
+
+// CI is read from check runs and commit statuses together: a failure
+// anywhere wins, then one still running; cancelled and skipped runs say
+// nothing; no checks at all is none.
+func TestChecks(t *testing.T) {
+ tests := []struct {
+ name, runs, status string
+ want core.CI
+ }{
+ {"none", `{"check_runs": []}`, `{"statuses": []}`, core.CI{State: "none"}},
+ {"passed", `{"check_runs": [{"name": "test", "status": "completed", "conclusion": "success"}]}`, `{"statuses": []}`, core.CI{State: "success"}},
+ {"running", `{"check_runs": [{"name": "test", "status": "in_progress"}, {"name": "lint", "status": "completed", "conclusion": "success"}]}`, `{"statuses": []}`, core.CI{State: "pending"}},
+ {"failed", `{"check_runs": [{"name": "test", "status": "completed", "conclusion": "failure"}, {"name": "lint", "status": "in_progress"}]}`, `{"statuses": [{"context": "ci/legacy", "state": "error"}]}`,
+ core.CI{State: "failure", Failed: []string{"ci/legacy", "test"}}},
+ {"cancelled only", `{"check_runs": [{"name": "test", "status": "completed", "conclusion": "cancelled"}]}`, `{"statuses": []}`, core.CI{State: "none"}},
+ {"a status pending", `{"check_runs": []}`, `{"statuses": [{"context": "ci/legacy", "state": "pending"}]}`, core.CI{State: "pending"}},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ api := newAPI(t, []step{
+ {req: "GET /repos/acme/shop/commits/abc123/check-runs?per_page=100", resp: tt.runs},
+ {req: "GET /repos/acme/shop/commits/abc123/status", resp: tt.status},
+ })
+ got, err := api.g.Checks(context.Background(), "abc123")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(got, tt.want) {
+ t.Errorf("got %+v, want %+v", got, tt.want)
+ }
+ })
+ }
+}
+
+// The tracking issue is found by its marker among issues, never among the
+// PRs the issues API lists too, and is created with tend's labels and
+// edited in place.
+func TestTrackingIssue(t *testing.T) {
+ api := newAPI(t, []step{
+ {req: "GET /repos/acme/shop/issues?state=all&sort=created&direction=desc&per_page=100", resp: `[
+ {"number": 9, "title": "a PR", "body": "", "state": "open", "pull_request": {"url": "x"}},
+ {"number": 7, "title": "tend: what it could not do on its own", "body": "list\n", "state": "closed"}
+ ]`},
+ {req: "GET /repos/acme/shop/labels/tend", resp: `{"name": "tend"}`},
+ {req: "POST /repos/acme/shop/issues", body: `{"body":"b","labels":["tend"],"title":"t"}`, status: 201, resp: `{"number": 12, "title": "t", "body": "b", "state": "open"}`},
+ {req: "PATCH /repos/acme/shop/issues/12", body: `{"body":"c","state":"closed"}`, resp: `{}`},
+ })
+ ctx := context.Background()
+ is, err := api.g.FindIssue(ctx, "")
+ if err != nil || is == nil || is.Number != 7 || is.Open {
+ t.Fatalf("found %+v, %v", is, err)
+ }
+ made, err := api.g.CreateIssue(ctx, "t", "b", []string{"tend"})
+ if err != nil || made.Number != 12 || !made.Open {
+ t.Fatalf("made %+v, %v", made, err)
+ }
+ if err := api.g.EditIssue(ctx, 12, "c", false); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/internal/e2e/catchup_test.go b/internal/e2e/catchup_test.go
new file mode 100644
index 0000000..abb282d
--- /dev/null
+++ b/internal/e2e/catchup_test.go
@@ -0,0 +1,151 @@
+package e2e
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/mohsensc/tend-cli/internal/deliver"
+ "github.com/mohsensc/tend-cli/internal/model"
+ "github.com/mohsensc/tend-cli/internal/plan"
+)
+
+// replies is a model that answers with each of says in turn, a file under
+// replies/ when one is named so, then finds nothing to say when vetting asks.
+func replies(t *testing.T, says ...string) *model.Script {
+ t.Helper()
+ s := &model.Script{}
+ for _, say := range says {
+ if b, err := os.ReadFile(filepath.Join("testdata", "replies", say)); err == nil {
+ say = string(b)
+ }
+ s.Replies = append(s.Replies, say)
+ }
+ for range 12 {
+ s.Replies = append(s.Replies, "NONE")
+ }
+ return s
+}
+
+// An app nobody has touched since the Node 4 days, with no tests: a runtime
+// pin and minimum long past their end of life, a web framework two majors
+// behind whose majors each break the app, the deprecated request with no
+// single replacement, a vulnerable parser and a dependency nothing uses.
+// tend catches it up in four PRs, a stage each and never two open: the
+// first adds a smoke test and tests of how the app behaves now, and proves
+// the fix and the removal against them; the second moves the runtime; the
+// third climbs the framework a major at a time when the jump fails; the
+// fourth takes the catalog's recommended replacement for request. Then it
+// is up to date and goes on one change at a time.
+func TestCatchUpLegacy(t *testing.T) {
+ need(t, "node", "npm")
+ w := fresh(t, "node-legacy")
+ w.fetch.osv.ids = []string{"GHSA-3m7x-8p2r-6fjw"}
+
+ w.model = replies(t, "legacy-baseline.md")
+ res := w.tend("run").want(t, 0)
+ if !strings.HasPrefix(res.stdout, "tend: opened #1 Catch up: a test baseline, 1 security fix, 1 unused dependency ") {
+ t.Fatalf("stage 1: %q\n%s", res.stdout, res.stderr)
+ }
+ pr := *w.forge.PR(1)
+ w.golden("1-body.md", pr.Body)
+ w.golden("1-diff.patch", w.diff(pr.Branch)+"\n")
+ for _, want := range []string{
+ "### Baseline\n\nThis project's tests are too thin to prove the catch-up by: there is no test command.",
+ "`test/tend/smoke.js`: loads each of the 3 modules that load on the base commit",
+ "### Next stages",
+ "2. Runtimes and build tooling",
+ "3. Major upgrades\n - `@fixture/web` 1.0.0 → 3.0.0 in `package.json`: a new major release.",
+ "4. Migrations and replacements\n - `request` 2.88.2 in `package.json`: deprecated, with no single replacement.",
+ "tend takes the first of `undici`, `node-fetch` and `axios` its proof passes, in that order.",
+ } {
+ if !strings.Contains(pr.Body, want) {
+ t.Errorf("stage 1 lacks %q:\n%s", want, pr.Body)
+ }
+ }
+ if yml := w.git(w.origin, "show", pr.Branch+":tend.yml"); !strings.Contains(yml, "node --test test/tend/characterization.js test/tend/smoke.js") {
+ t.Errorf("tend.yml on the branch:\n%s", yml)
+ }
+ w.merge(1)
+ w.pull()
+
+ w.model = replies(t)
+ res = w.tend("run").want(t, 0)
+ if !strings.HasPrefix(res.stdout, "tend: opened #2 Catch up: 1 runtime minimum, 1 end-of-life runtime ") {
+ t.Fatalf("stage 2: %q\n%s", res.stdout, res.stderr)
+ }
+ pr = *w.forge.PR(2)
+ if pr.Branch != deliver.StageBranch(plan.Runtimes) || !strings.Contains(pr.Body, "node --test test/tend/characterization.js test/tend/smoke.js") {
+ t.Errorf("stage 2 = %+v", pr)
+ }
+ w.golden("2-body.md", pr.Body)
+ w.merge(2)
+ w.pull()
+
+ w.model = replies(t, "NOCHANGE", "legacy-web-2.diff", "legacy-web-3.diff")
+ res = w.tend("run").want(t, 0)
+ if !strings.HasPrefix(res.stdout, "tend: opened #3 Catch up: 1 major upgrade ") {
+ t.Fatalf("stage 3: %q\n%s", res.stdout, res.stderr)
+ }
+ for _, want := range []string{"climbing @fixture/web to 2.0.0", "climbing @fixture/web to 3.0.0", "climbed @fixture/web to 3.0.0"} {
+ if !strings.Contains(res.stderr, want) {
+ t.Errorf("stage 3 does not log %q:\n%s", want, res.stderr)
+ }
+ }
+ pr = *w.forge.PR(3)
+ if want := "- `@fixture/web` 1.0.0 → 3.0.0, by way of 2.0.0, each proven: a new major release"; !strings.Contains(pr.Body, want) {
+ t.Errorf("stage 3 lacks %q:\n%s", want, pr.Body)
+ }
+ w.golden("3-body.md", pr.Body)
+ w.golden("3-diff.patch", w.diff(pr.Branch)+"\n")
+ w.merge(3)
+ w.pull()
+
+ w.model = replies(t, "legacy-undici.diff")
+ res = w.tend("run").want(t, 0)
+ if !strings.HasPrefix(res.stdout, "tend: opened #4 Catch up: 1 replaced library ") {
+ t.Fatalf("stage 4: %q\n%s", res.stdout, res.stderr)
+ }
+ pr = *w.forge.PR(4)
+ if want := "- `request` 2.88.2 → `undici` 7.16.0, picked from 4 options: the catalog's recommended replacement"; !strings.Contains(pr.Body, want) {
+ t.Errorf("stage 4 lacks %q:\n%s", want, pr.Body)
+ }
+ w.golden("4-body.md", pr.Body)
+ w.golden("4-diff.patch", w.diff(pr.Branch)+"\n")
+ w.merge(4)
+ w.pull()
+
+ w.model = replies(t)
+ if res := w.tend("run").want(t, 0); res.stdout != "tend: up to date\n" {
+ t.Errorf("after the catch-up: %q\n%s", res.stdout, res.stderr)
+ }
+ if st := w.state(); st.Stage != plan.Last || st.Onboard != "merged" {
+ t.Errorf("state: stage %d, onboard %q", st.Stage, st.Onboard)
+ }
+ if n := len(w.forge.All()); n != 4 {
+ t.Errorf("%d PRs, want 4", n)
+ }
+ pkg := w.git(w.origin, "show", "main:package.json")
+ if lock := w.git(w.origin, "show", "main:package-lock.json"); !strings.Contains(lock, "parser-1.0.1.tgz") {
+ t.Errorf("the lockfile on main does not lock the fixed parser:\n%s", lock)
+ }
+ for _, want := range []string{`"@fixture/web": "^3.0.0"`, `"undici": "^7.16.0"`} {
+ if !strings.Contains(pkg, want) {
+ t.Errorf("package.json on main lacks %s:\n%s", want, pkg)
+ }
+ }
+ for _, gone := range []string{"request", "@fixture/colors", `">=4"`} {
+ if strings.Contains(pkg, gone) {
+ t.Errorf("package.json on main still has %s:\n%s", gone, pkg)
+ }
+ }
+ if v := w.git(w.origin, "show", "main:.nvmrc"); v == "4.9.1" {
+ t.Errorf(".nvmrc on main: %s", v)
+ }
+ for _, is := range w.forge.Issues() {
+ if is.Open {
+ t.Errorf("a tracking issue is open:\n%s", is.Body)
+ }
+ }
+}
diff --git a/internal/e2e/e2e_test.go b/internal/e2e/e2e_test.go
index 6bf92b9..0615afd 100644
--- a/internal/e2e/e2e_test.go
+++ b/internal/e2e/e2e_test.go
@@ -183,15 +183,64 @@ func TestNodeAgent(t *testing.T) {
}
}
-// S1 without a model: the bare bump breaks the tests, so the PR changes
-// nothing and lays out the ways forward. A maintainer's pick, and only a
-// maintainer's, turns it into the migration.
+// S1 without a model: the bare bump breaks the tests, so tend takes the way
+// off it its rule allows, the rename the deprecation names, proves it, and
+// says why it chose it. The other option stays one comment away, and only a
+// maintainer's comment takes it.
+func TestNodeChoice(t *testing.T) {
+ need(t, "node", "npm")
+ w := setup(t, "node-sdk")
+ res := w.tend("run").want(t, 0)
+ if !strings.HasPrefix(res.stdout, "tend: opened #1 Migrate off deprecated @fixture/pay 1.x ") {
+ t.Fatalf("run said %q\n%s", res.stdout, res.stderr)
+ }
+ pr := onlyPR(t, w)
+ w.goldenPR(pr)
+ if want := "tend took option 1 on its own: the rename the deprecation notice names. Comment `tend apply N` to have another instead."; !strings.Contains(pr.Body, want) {
+ t.Errorf("the body does not say why tend chose:\n%s", pr.Body)
+ }
+ if !strings.Contains(res.stderr, "trying option 1 of @fixture/pay on its own") {
+ t.Errorf("the choice is not logged:\n%s", res.stderr)
+ }
+
+ w.forge.Now = func() time.Time { return now.Add(time.Hour) }
+ w.say(1, "drive-by", "NONE", "tend apply 2")
+ if res := w.tend("run").want(t, 0); !strings.Contains(res.stdout, "waiting on PR #1") || rev(t, *w.forge.PR(1)) != 1 {
+ t.Fatalf("a comment from outside the repo was honored: %q", res.stdout)
+ }
+ w.forge.Now = func() time.Time { return now.Add(2 * time.Hour) }
+ w.say(1, "owner", "OWNER", "tend apply 2")
+ res = w.tend("run").want(t, 0)
+ if !strings.HasPrefix(res.stdout, "tend: updated #1 Pin @fixture/pay to 1.4.0 ") {
+ t.Fatalf("after tend apply 2: %q", res.stdout)
+ }
+ if d := w.diff("tend/npm-fixture-pay-2.0.0"); !strings.Contains(d, `versions: [">=2.0.0"]`) || strings.Contains(d, "package-lock.json") {
+ t.Errorf("the pin:\n%s", d)
+ }
+}
+
+// When no way off can be proven, tend stays put: the PR changes nothing and
+// lays out the options. A maintainer's pick, and only a maintainer's, turns
+// it into the migration.
func TestNodeDecision(t *testing.T) {
need(t, "node", "npm")
w := setup(t, "node-sdk")
+ w.commit("Pin the endpoint", map[string]string{"test/endpoint.test.js": `'use strict'
+
+const test = require('node:test')
+const assert = require('node:assert')
+const { charge } = require('../src/billing')
+
+test('charges go to the charges endpoint', async () => {
+ let url
+ globalThis.fetch = async (u) => { url = u; return { ok: true, json: async () => ({}) } }
+ await charge(5, 'cus_1').catch(() => {})
+ assert.match(url, /\/v1\/charges$/)
+})
+`})
res := w.tend("run").want(t, 0)
if !strings.HasPrefix(res.stdout, "tend: opened #1 Decide: migrate off @fixture/pay 1.x ") {
- t.Fatalf("run said %q", res.stdout)
+ t.Fatalf("run said %q\n%s", res.stdout, res.stderr)
}
if strings.Count(res.stderr, "mechanical only") != 1 || !strings.Contains(res.stderr, "npm/@fixture/pay@2.0.0 needs code edits a model would make") {
t.Errorf("the run does not say plainly that it had no model:\n%s", res.stderr)
@@ -213,7 +262,7 @@ func TestNodeDecision(t *testing.T) {
}
w.forge.Now = func() time.Time { return now.Add(time.Hour) }
- w.say(1, "drive-by", "NONE", "tend apply 1")
+ w.say(1, "drive-by", "NONE", "tend apply 2")
if res := w.tend("run").want(t, 0); !strings.Contains(res.stdout, "waiting on PR #1") {
t.Fatalf("a comment from outside the repo was honored: %q", res.stdout)
}
@@ -222,11 +271,10 @@ func TestNodeDecision(t *testing.T) {
}
w.forge.Now = func() time.Time { return now.Add(2 * time.Hour) }
- w.say(1, "owner", "OWNER", "tend apply 1")
- w.model = script(t, "node-sdk")
+ w.say(1, "owner", "OWNER", "tend apply 2")
res = w.tend("run").want(t, 0)
- if !strings.HasPrefix(res.stdout, "tend: updated #1 Migrate off deprecated @fixture/pay 1.x ") {
- t.Fatalf("after tend apply 1: %q", res.stdout)
+ if !strings.HasPrefix(res.stdout, "tend: updated #1 Pin @fixture/pay to 1.4.0 ") {
+ t.Fatalf("after tend apply 2: %q", res.stdout)
}
pr = *w.forge.PR(1)
if rev(t, pr) != 2 || len(w.forge.All()) != 1 || pr.Draft {
@@ -544,7 +592,7 @@ func TestDryRun(t *testing.T) {
w.noForge = true
delete(w.getenv, "GITHUB_REPOSITORY")
res := w.tend("run", "--dry-run").want(t, 0)
- if !strings.HasPrefix(res.stdout, "Decide: migrate off @fixture/pay 1.x\n\n## @fixture/pay 1.4.0 → 2.0.0\n") {
+ if !strings.HasPrefix(res.stdout, "Migrate off deprecated @fixture/pay 1.x\n\n## @fixture/pay 1.4.0 → 2.0.0\n") {
t.Errorf("dry run printed:\n%s", res.stdout)
}
wt := strings.TrimSuffix(res.stdout[strings.LastIndex(res.stdout, " ")+1:], "\n")
@@ -955,6 +1003,59 @@ func TestCommitMode(t *testing.T) {
}
}
+// Commit mode, unattended: tend waits while the repository's CI runs on its
+// commit, reverts the commit when CI fails on it, backs off the change, and
+// says so in its one tracking issue instead of trying again.
+func TestCommitModeRevert(t *testing.T) {
+ need(t, "go")
+ w := setup(t, "go-vuln")
+ w.commit("Commit straight to main", map[string]string{"tend.yml": "deliver: {mode: commit}\n"})
+ w.tend("run").want(t, 0)
+ sha := w.git(w.origin, "rev-parse", "main")
+
+ w.forge.CI[sha] = core.CI{State: "pending"}
+ if res := w.tend("run").want(t, 0); !strings.HasPrefix(res.stdout, "tend: waiting on CI for "+core.Short(sha)+", which tend pushed to main") {
+ t.Fatalf("while CI runs: %q\n%s", res.stdout, res.stderr)
+ }
+ w.forge.CI[sha] = core.CI{State: "failure", Failed: []string{"test (ubuntu-latest)"}}
+ res := w.tend("run").want(t, 0)
+ if !strings.HasPrefix(res.stdout, "tend: reverted "+core.Short(sha)+" on main: CI failed (test (ubuntu-latest))") {
+ t.Fatalf("after CI failed: %q\n%s", res.stdout, res.stderr)
+ }
+ msg := w.git(w.origin, "log", "-1", "--format=%B", "main")
+ for _, want := range []string{
+ `Revert "Bump example.com/fixture/crypto to v1.0.1 (fixes GO-2026-0001)"`,
+ "CI failed on " + core.Short(sha) + ": test (ubuntu-latest).",
+ "will not try go/example.com/fixture/crypto@v1.0.1 again",
+ "This reverts commit " + sha + ".",
+ } {
+ if !strings.Contains(msg, want) {
+ t.Errorf("the revert says %q, want %q", msg, want)
+ }
+ }
+ if d := w.git(w.origin, "diff", sha+"^", "main"); d != "" {
+ t.Errorf("main after the revert is not the tree before tend's commit:\n%s", d)
+ }
+ if p := w.state().Parked["go/example.com/fixture/crypto@v1.0.1"]; p.Reason != "reverted" {
+ t.Errorf("parked = %+v", p)
+ }
+
+ if res := w.tend("run").want(t, 0); res.stdout != "tend: up to date\n" {
+ t.Errorf("after the revert: %q\n%s", res.stdout, res.stderr)
+ }
+ is := w.forge.Issues()
+ if len(is) != 1 || !is[0].Open || !strings.Contains(is[0].Body, "- `go/example.com/fixture/crypto@v1.0.1`: reverted in ") || !strings.Contains(is[0].Body, "CI failed on "+core.Short(sha)) {
+ t.Fatalf("issues = %+v", is)
+ }
+ w.tend("run").want(t, 0)
+ if n := len(w.forge.Issues()); n != 1 || w.forge.Issues()[0].Body != is[0].Body {
+ t.Errorf("a run with nothing new touched the issue: %+v", w.forge.Issues())
+ }
+ if n := strings.Count(w.git(w.origin, "log", "--format=%s", "main")+"\n", "\nBump example.com/fixture/crypto"); n != 1 {
+ t.Errorf("the change was pushed %d times", n)
+ }
+}
+
// real is the clone's path as git reports it, symlinks resolved.
func (w *world) real() string {
w.t.Helper()
diff --git a/internal/e2e/harness_test.go b/internal/e2e/harness_test.go
index 43411c9..7554704 100644
--- a/internal/e2e/harness_test.go
+++ b/internal/e2e/harness_test.go
@@ -176,6 +176,14 @@ func (w *world) commit(msg string, files map[string]string) {
w.base = w.git(w.dir, "rev-parse", "HEAD")
}
+// pull brings the clone up to main on origin, as the Action's checkout of
+// the default branch is before each run, tend.yml included.
+func (w *world) pull() {
+ w.t.Helper()
+ w.git(w.dir, "fetch", "--quiet", "origin")
+ w.git(w.dir, "reset", "--quiet", "--hard", "origin/main")
+}
+
func (w *world) git(dir string, args ...string) string {
w.t.Helper()
cmd := exec.Command("git", append([]string{"-c", "commit.gpgsign=false"}, args...)...)
diff --git a/internal/e2e/onboard_test.go b/internal/e2e/onboard_test.go
index 377fc38..033ea0a 100644
--- a/internal/e2e/onboard_test.go
+++ b/internal/e2e/onboard_test.go
@@ -3,7 +3,6 @@ package e2e
import (
"os"
"path/filepath"
- "regexp"
"slices"
"strings"
"testing"
@@ -26,12 +25,12 @@ func TestOnboardNode(t *testing.T) {
w.golden("check.txt", w.tend("check").want(t, 0).stdout)
res := w.tend("run").want(t, 0)
- if !strings.HasPrefix(res.stdout, "tend: opened #1 Tidy up: remove 3 unused dependencies, move off 1 deprecated library ") {
+ if !strings.HasPrefix(res.stdout, "tend: opened #1 Catch up: 1 deprecated library, 3 unused dependencies ") {
t.Fatalf("run said %q\n%s", res.stdout, res.stderr)
}
pr := onlyPR(t, w)
w.goldenPR(pr)
- if pr.Branch != deliver.TidyBranch || pr.Draft {
+ if pr.Branch != deliver.FirstBranch || pr.Draft {
t.Errorf("pr = %+v", pr)
}
pkg := w.git(w.origin, "show", pr.Branch+":package.json")
@@ -48,7 +47,7 @@ func TestOnboardNode(t *testing.T) {
if cs := w.commits(pr.Branch); len(cs) != 1 || !slices.Equal(cs[0].files, []string{"package-lock.json", "package.json", "src/billing.js"}) {
t.Errorf("commits = %+v", cs)
}
- if st := w.state(); st.Onboard != "due" || st.Open == nil || st.Open.ID != core.TidyID {
+ if st := w.state(); st.Onboard != "due" || st.Open == nil || st.Open.ID != core.FirstID {
t.Errorf("state: onboard %q, open %+v", st.Onboard, st.Open)
}
@@ -65,27 +64,26 @@ func TestOnboardNode(t *testing.T) {
}
// Closing the first PR unmerged is a maintainer's answer: tend never opens
-// it again, and what it held back gets PRs of its own. Without a model, the
-// deprecated SDK is not moved in the first PR but laid out with its options.
+// it again, and what it carried comes back as PRs of their own. Without a
+// model, the deprecated SDK still moves: the rename its deprecation notice
+// names passes the proof, so tend takes it and says so.
func TestOnboardClosed(t *testing.T) {
need(t, "node", "npm")
w := fresh(t, "node-tidy")
res := w.tend("run").want(t, 0)
- if !strings.HasPrefix(res.stdout, "tend: opened #1 Tidy up: remove 3 unused dependencies ") {
+ if !strings.HasPrefix(res.stdout, "tend: opened #1 Catch up: 1 deprecated library, 3 unused dependencies ") {
t.Fatalf("run said %q\n%s", res.stdout, res.stderr)
}
body := w.forge.PR(1).Body
- for _, want := range []string{"Deprecated, not moved", "`@fixture/pay` 1.4.0 in `package.json`: no model is configured to move the 2 call sites.", "Pin to 1.4.0 and ignore"} {
- if !strings.Contains(body, want) {
- t.Errorf("the body lacks %q:\n%s", want, body)
- }
+ if want := "- `@fixture/pay` 1.4.0 → 2.0.0, picked from 2 options: the rename the deprecation notice names"; !strings.Contains(body, want) {
+ t.Errorf("the body lacks %q:\n%s", want, body)
}
if n := strings.Count(res.stderr, "tend: removed "); n != 1 {
t.Errorf("the removal is logged %d times, want once:\n%s", n, res.stderr)
}
w.closeByHuman(1)
- if res := w.tend("run").want(t, 0); !strings.HasPrefix(res.stdout, "tend: opened #2 Decide: migrate off @fixture/pay 1.x ") {
+ if res := w.tend("run").want(t, 0); !strings.HasPrefix(res.stdout, "tend: opened #2 Migrate off deprecated @fixture/pay 1.x ") {
t.Fatalf("after the close: %q", res.stdout)
}
if st := w.state(); st.Onboard != "closed" {
@@ -107,7 +105,7 @@ func TestOnboardBisect(t *testing.T) {
"test/strings.test.js": "'use strict'\n\nconst test = require('node:test')\nconst name = ['@fixture', 'strings'].join('/')\n\ntest('pads', () => { require(name).pad('a', 2) })\n",
})
res := w.tend("run").want(t, 0)
- if !strings.HasPrefix(res.stdout, "tend: opened #1 Tidy up: remove 2 unused dependencies ") {
+ if !strings.HasPrefix(res.stdout, "tend: opened #1 Catch up: 1 deprecated library, 2 unused dependencies ") {
t.Fatalf("run said %q\n%s", res.stdout, res.stderr)
}
pr := onlyPR(t, w)
@@ -118,53 +116,149 @@ func TestOnboardBisect(t *testing.T) {
if !strings.Contains(pkg, "@fixture/strings") || strings.Contains(pkg, "@fixture/colors") || strings.Contains(pkg, "@fixture/old-test-helper") {
t.Errorf("package.json on the branch:\n%s", pkg)
}
- if n := strings.Count(res.stderr, "proving patched"); n != 4 {
- t.Errorf("%d proofs of a patch, want the whole, a half, then each of the other half:\n%s", n, res.stderr)
+ if n := strings.Count(res.stderr, "proving patched"); n != 5 {
+ t.Errorf("%d proofs of a patch, want the rename on its own, the whole, a half, then each of the other half:\n%s", n, res.stderr)
}
}
// A Go module requires a module nothing imports, and the first PR removes
-// it. A security fix that arrives while that PR is open takes its place,
-// leaving the unused module alone, and the first PR comes back once the fix
-// merges, whatever was said on it since, to remove it.
+// it. A security fix that arrives while that PR is open does not go ahead of
+// it: the first PR is built again with the fix in it, and stays the one open
+// PR until it merges.
func TestOnboardGo(t *testing.T) {
need(t, "go")
w := fresh(t, "go-tidy")
w.fetch.osv.ids = nil
res := w.tend("run").want(t, 0)
- if !strings.HasPrefix(res.stdout, "tend: opened #1 Tidy up: remove 1 unused dependency ") {
+ if !strings.HasPrefix(res.stdout, "tend: opened #1 Catch up: 1 unused dependency ") {
t.Fatalf("run said %q\n%s", res.stdout, res.stderr)
}
- w.goldenPR(onlyPR(t, w))
w.fetch.osv.ids = []string{"GO-2026-0001"}
- if res := w.tend("run").want(t, 0); !strings.HasPrefix(res.stdout, "tend: opened #2 Bump example.com/fixture/crypto to v1.0.1 (fixes GO-2026-0001) ") {
+ if res := w.tend("run").want(t, 0); !strings.HasPrefix(res.stdout, "tend: updated #1 Catch up: 1 security fix, 1 unused dependency ") {
t.Fatalf("with the advisory: %q\n%s", res.stdout, res.stderr)
}
- if d := w.diff(w.forge.PR(2).Branch); !strings.Contains(d, "example.com/fixture/crypto v1.0.1") || regexp.MustCompile(`(?m)^-.*example.com/fixture/logs`).MatchString(d) {
- t.Errorf("the security fix moves more than the bump:\n%s", d)
+ pr := onlyPR(t, w)
+ w.goldenPR(pr)
+ if d := w.diff(pr.Branch); !strings.Contains(d, "example.com/fixture/crypto v1.0.1") || !strings.Contains(d, "-\texample.com/fixture/logs") {
+ t.Errorf("the first PR lacks the fix or the removal:\n%s", d)
}
- cs, _ := w.forge.Comments(t.Context(), 1)
- if w.forge.PR(1).State != "closed" || len(cs) == 0 || !strings.HasPrefix(cs[0].Body, "Closing to make room for a security fix. tend will reopen this after that merges.") {
- t.Errorf("#1 is %s, comments %+v", w.forge.PR(1).State, cs)
+ if res := w.tend("run").want(t, 0); !strings.Contains(res.stdout, "waiting on PR #1") || len(w.forge.All()) != 1 {
+ t.Errorf("then: %q, %d PRs", res.stdout, len(w.forge.All()))
+ }
+ w.merge(1)
+ if res := w.tend("run").want(t, 0); res.stdout != "tend: up to date\n" || w.state().Onboard != "merged" {
+ t.Errorf("after the first PR merged: %q, onboard %q", res.stdout, w.state().Onboard)
}
+}
- // A word on the closed PR is not a person closing it.
- w.say(1, "ada", "OWNER", "ok, the fix first")
- w.merge(2)
- if res := w.tend("run").want(t, 0); !strings.HasPrefix(res.stdout, "tend: opened #3 Tidy up: remove 1 unused dependency ") {
- t.Fatalf("after the fix merged: %q\n%s", res.stdout, res.stderr)
+// The first run on a Node project with advisories against a package it
+// imports and against one only its lockfile names: both fixes, the move off
+// the deprecated SDK and the removals go out as one PR, proven by one run.
+// npm moves the transitive package to the newest release its range allows,
+// past the one that fixes it, and the PR says which it got.
+func TestOnboardCatchUp(t *testing.T) {
+ need(t, "node", "npm")
+ w := fresh(t, "node-catchup")
+ w.model = script(t, "node-sdk")
+ w.fetch.osv.ids = []string{"GHSA-2c8f-9v3w-4hq7", "GHSA-3m7x-8p2r-6fjw"}
+ res := w.tend("run").want(t, 0)
+ if !strings.HasPrefix(res.stdout, "tend: opened #1 Catch up: 2 security fixes, 1 deprecated library, 3 unused dependencies ") {
+ t.Fatalf("run said %q\n%s", res.stdout, res.stderr)
}
- if pr := w.forge.PR(3); pr.Branch != deliver.TidyBranch || !strings.Contains(w.diff(pr.Branch), "-\texample.com/fixture/logs") {
- t.Errorf("#3 = %+v\n%s", pr, w.diff(pr.Branch))
+ pr := onlyPR(t, w)
+ w.goldenPR(pr)
+ for _, want := range []string{
+ "### Security\n\nnpm:\n\n- `@fixture/archive` 1.0.0 → 1.1.1 (transitive): GHSA-2c8f-9v3w-4hq7 (high); 1.1.0 fixes it, and the lockfile took the newest release its ranges allow\n- `@fixture/parser` 1.0.0 → 1.0.1: GHSA-3m7x-8p2r-6fjw (moderate)",
+ "### Deprecated\n\n- `@fixture/pay` 1.4.0 → 2.0.0",
+ "### Unused\n\nRemoved, since nothing in the project uses them:",
+ } {
+ if !strings.Contains(pr.Body, want) {
+ t.Errorf("the body lacks %q:\n%s", want, pr.Body)
+ }
}
- w.merge(3)
- if res := w.tend("run").want(t, 0); res.stdout != "tend: up to date\n" || w.state().Onboard != "merged" {
- t.Errorf("after the first PR merged: %q, onboard %q", res.stdout, w.state().Onboard)
+ lock := w.git(w.origin, "show", pr.Branch+":package-lock.json")
+ for _, want := range []string{"archive-1.1.1.tgz", "parser-1.0.1.tgz", "pay-2.0.0.tgz"} {
+ if !strings.Contains(lock, want) {
+ t.Errorf("the lockfile does not lock %s:\n%s", want, lock)
+ }
+ }
+ if n := strings.Count(res.stderr, "proving patched"); n != 1 {
+ t.Errorf("%d proofs of the batch, want 1:\n%s", n, res.stderr)
+ }
+ if res := w.tend("run").want(t, 0); !strings.Contains(res.stdout, "waiting on PR #1") {
+ t.Errorf("second run: %q", res.stdout)
+ }
+}
+
+// A security fix whose release breaks the tests: the proof of the whole
+// batch fails, tend splits it until the culprit is found, and the fix goes
+// under Up next with the step that failed, to come as a PR of its own. The
+// rest goes out, and the proofs stay within their bound.
+func TestOnboardCatchUpBisect(t *testing.T) {
+ need(t, "node", "npm")
+ w := fresh(t, "node-catchup")
+ w.fetch.osv.ids = []string{"GHSA-2c8f-9v3w-4hq7", "GHSA-3m7x-8p2r-6fjw", "GHSA-4q9w-7h3c-5vrx"}
+ res := w.tend("run").want(t, 0)
+ if !strings.HasPrefix(res.stdout, "tend: opened #1 Catch up: 2 security fixes, 1 deprecated library, 3 unused dependencies ") {
+ t.Fatalf("run said %q\n%s", res.stdout, res.stderr)
+ }
+ pr := onlyPR(t, w)
+ if want := "- `@fixture/format` 1.1.0 → 1.1.1 in `package.json`: with it in the batch, `npm test` fails (exit 1)."; !strings.Contains(pr.Body, want) {
+ t.Errorf("the body does not say why @fixture/format waits:\n%s", pr.Body)
+ }
+ if !strings.Contains(res.stderr, "tend: left @fixture/format out of the first PR: with it in the batch, `npm test` fails (exit 1)") {
+ t.Errorf("the drop is not logged:\n%s", res.stderr)
+ }
+ if pkg := w.git(w.origin, "show", pr.Branch+":package.json"); !strings.Contains(pkg, `"@fixture/format": "^1.1.0"`) {
+ t.Errorf("package.json on the branch:\n%s", pkg)
+ }
+ if n := strings.Count(res.stderr, "proving patched"); n != 6 {
+ t.Errorf("%d proofs, want the rename on its own, the whole, a half that fails, its first part, the next on top of it, then the rest:\n%s", n, res.stderr)
+ }
+
+ // Once the first PR merges, the fix it left out comes on its own.
+ w.merge(1)
+ if res := w.tend("run").want(t, 0); !strings.HasPrefix(res.stdout, "tend: opened #2 Bump @fixture/format to 1.1.1 (fixes GHSA-4q9w-7h3c-5vrx) ") {
+ t.Errorf("after the merge: %q", res.stdout)
+ }
+}
+
+// A repo an older tend ran on has a security fix open that went ahead of
+// its first PR. The first PR folds that fix in: tend closes the open PR with
+// a line saying so, opens the first PR with the fix inside, and never has
+// two open at once.
+func TestOnboardFold(t *testing.T) {
+ need(t, "node", "npm")
+ w := fresh(t, "node-catchup")
+ w.fetch.osv.ids = []string{"GHSA-3m7x-8p2r-6fjw"}
+ old, err := w.forge.CreatePR(t.Context(), core.PRInput{
+ Branch: "tend/npm-fixture-parser-1.0.1", Base: "main", Title: "Bump @fixture/parser to 1.0.1 (fixes GHSA-3m7x-8p2r-6fjw)",
+ Body: ``,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ res := w.tend("run").want(t, 0)
+ if !strings.HasPrefix(res.stdout, "tend: opened #2 Catch up: 1 security fix, 1 deprecated library, 3 unused dependencies ") {
+ t.Fatalf("run said %q\n%s", res.stdout, res.stderr)
+ }
+ cs, _ := w.forge.Comments(t.Context(), old.Number)
+ if w.forge.PR(old.Number).State != "closed" || len(cs) == 0 || !strings.HasPrefix(cs[0].Body, "Folded into tend's first pull request, which makes this change with the rest.") {
+ t.Errorf("#1 is %s, comments %+v", w.forge.PR(old.Number).State, cs)
+ }
+ if pr := w.forge.PR(2); pr.Branch != deliver.FirstBranch || !strings.Contains(pr.Body, "`@fixture/parser` 1.0.0 → 1.0.1: GHSA-3m7x-8p2r-6fjw (moderate)") {
+ t.Errorf("#2 = %+v", pr)
+ }
+ if st := w.state(); st.Onboard != "due" || st.Open == nil || st.Open.PR != 2 {
+ t.Errorf("state: onboard %q, open %+v", st.Onboard, st.Open)
+ }
+ if res := w.tend("run").want(t, 0); !strings.Contains(res.stdout, "waiting on PR #2") {
+ t.Errorf("second run: %q", res.stdout)
}
}
-// A repo with nothing to tidy gets a first PR all the same: the welcome, and
+// A repo with nothing to catch up on gets a first PR all the same: the welcome, and
// a tend.yml with every key commented out so the PR has something in it. A
// dry run shows that PR and remembers nothing.
func TestOnboardClean(t *testing.T) {
@@ -172,7 +266,7 @@ func TestOnboardClean(t *testing.T) {
w := fresh(t, "go-vuln")
w.fetch.osv.ids = nil
res := w.tend("run", "--dry-run").want(t, 0)
- if !strings.HasPrefix(res.stdout, "Set up tend: nothing to tidy up\n\nThanks for adding tend: ") || len(w.forge.All()) != 0 {
+ if !strings.HasPrefix(res.stdout, "Set up tend: nothing to catch up on\n\nThanks for adding tend: ") || len(w.forge.All()) != 0 {
t.Fatalf("dry run printed:\n%s", res.stdout)
}
if st := w.state(); st.Onboard != "" {
@@ -180,7 +274,7 @@ func TestOnboardClean(t *testing.T) {
}
res = w.tend("run").want(t, 0)
- if !strings.HasPrefix(res.stdout, "tend: opened #1 Set up tend: nothing to tidy up ") {
+ if !strings.HasPrefix(res.stdout, "tend: opened #1 Set up tend: nothing to catch up on ") {
t.Fatalf("run said %q\n%s", res.stdout, res.stderr)
}
pr := onlyPR(t, w)
@@ -201,7 +295,7 @@ func TestOnboardQuiet(t *testing.T) {
if res.stdout != "tend: up to date\n" || len(w.forge.All()) != 0 {
t.Fatalf("run said %q, %d PRs", res.stdout, len(w.forge.All()))
}
- if !strings.Contains(res.stderr, "onboarding is quiet, so there is no tidy-up PR; nothing in the project uses example.com/fixture/logs") {
+ if !strings.Contains(res.stderr, "onboarding is quiet, so there is no first PR; nothing in the project uses example.com/fixture/logs") {
t.Errorf("stderr:\n%s", res.stderr)
}
if res := w.tend("run").want(t, 0); strings.Contains(res.stderr, "onboarding is quiet") || w.state().Onboard != "quiet" {
@@ -223,13 +317,13 @@ func TestOnboardDropped(t *testing.T) {
{"nothing left", map[string]string{
"tend.yml": "cooldown: 3d\n",
"go.mod": "module example.com/gotidy\n\ngo 1.26\n\nrequire example.com/fixture/crypto v1.0.0\n",
- }, "Closing: nothing is left to tidy up."},
+ }, "Closing: nothing is left to catch up on."},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
w := fresh(t, "go-tidy")
w.fetch.osv.ids = nil
- if res := w.tend("run").want(t, 0); !strings.HasPrefix(res.stdout, "tend: opened #1 Tidy up: ") {
+ if res := w.tend("run").want(t, 0); !strings.HasPrefix(res.stdout, "tend: opened #1 Catch up: ") {
t.Fatalf("run said %q", res.stdout)
}
w.commit("Change course", tt.files)
@@ -258,7 +352,7 @@ func TestOnboardLostState(t *testing.T) {
t.Fatal(err)
}
w.commit("Add a readme", map[string]string{"README.md": "gotidy\n"})
- if res := w.tend("run").want(t, 0); !strings.HasPrefix(res.stdout, "tend: updated #1 Tidy up: remove 1 unused dependency ") {
+ if res := w.tend("run").want(t, 0); !strings.HasPrefix(res.stdout, "tend: updated #1 Catch up: 1 unused dependency ") {
t.Fatalf("after losing state: %q", res.stdout)
}
if st := w.state(); st.Onboard != "due" || len(w.forge.All()) != 1 {
@@ -292,7 +386,7 @@ func TestOnboardCheckLocal(t *testing.T) {
}
// tend init --now writes tend.yml and runs before it is committed. With
-// nothing to tidy, there is no first PR to add a second tend.yml.
+// nothing to catch up on, there is no first PR to add a second tend.yml.
func TestOnboardInitNow(t *testing.T) {
need(t, "go")
w := fresh(t, "go-vuln")
diff --git a/internal/e2e/testdata/TestCatchUpLegacy/1-body.md b/internal/e2e/testdata/TestCatchUpLegacy/1-body.md
new file mode 100644
index 0000000..fafb636
--- /dev/null
+++ b/internal/e2e/testdata/TestCatchUpLegacy/1-body.md
@@ -0,0 +1,65 @@
+Thanks for adding tend: it looks after the packages this repository depends on and the APIs its code calls. This first pull request starts catching the repository up: a test baseline, 1 security fix and 1 unused dependency. The rest comes in 3 more pull requests, one stage at a time, listed under Next stages and each proven the same way. Once the catch-up is done it opens one pull request at a time, only for changes that touch your code, and each one shows the build and test runs that prove it. Steer it with `tend.yml`, or comment `tend skip`, `tend retry` or `tend apply N` on its pull requests.
+
+Part of this pull request was written by a model. The vetting section below covers it.
+
+### Baseline
+
+This project's tests are too thin to prove the catch-up by: there is no test command. So this pull request first adds tests that pin down how the code behaves on main@BASE, and every proof from here on runs them:
+
+- `test/tend/characterization.js`: tests a model wrote of the current behavior
+- `test/tend/smoke.js`: loads each of the 3 modules that load on the base commit, and exits
+- `node --test test/tend/characterization.js test/tend/smoke.js` in `verify.test` in `tend.yml`, after the project's own test lines
+
+They pass on main@BASE: the base column of the proof below is that commit with these tests added.
+
+### Security
+
+npm:
+
+- `@fixture/parser` 1.0.0 → 1.0.1: GHSA-3m7x-8p2r-6fjw (moderate)
+
+### Unused
+
+Removed, since nothing in the project uses it:
+
+- `@fixture/colors` 1.0.0 in `package.json`
+
+### Next stages
+
+Each comes as a pull request of its own once this one is merged, proven the same way.
+
+2. Runtimes and build tooling
+ - `nodejs` 4 → 22 in `package.json`: the oldest nodejs the project supports, past its end of life.
+ - `nodejs` 4.9.1 → 24.22.0 in `.nvmrc`: nodejs 4 end of life 2018-04-30.
+3. Major upgrades
+ - `@fixture/web` 1.0.0 → 3.0.0 in `package.json`: a new major release.
+4. Migrations and replacements
+ - `request` 2.88.2 in `package.json`: deprecated, with no single replacement. tend takes the first of `undici`, `node-fetch` and `axios` its proof passes, in that order.
+
+### Proof
+
+| step | base (main@BASE) | patched |
+|---|---|---|
+| `npm ci` | ok · 0s | ok · 0s |
+| `node --test test/tend/characterization.js test/tend/smoke.js` | ok · 0s | ok · 0s |
+
+node --test test/tend/characterization.js test/tend/smoke.js (patched), end of its output
+
+```
+(output)
+```
+
+
+### Vetting
+
+- scope: 5 files, all explained by this change
+- symbols: 1/1 calls resolve in @fixture/parser@1.0.1 typings
+- lockfile: only @fixture/colors, @fixture/parser changed
+- debug: nothing added
+- comments: nothing added
+- dead: not run: nothing was removed
+- question: nothing to note
+- not applicable: fields, leftovers
+
+tend · comment `tend skip` or `tend retry`
+
diff --git a/internal/e2e/testdata/TestCatchUpLegacy/1-diff.patch b/internal/e2e/testdata/TestCatchUpLegacy/1-diff.patch
new file mode 100644
index 0000000..68b3d82
--- /dev/null
+++ b/internal/e2e/testdata/TestCatchUpLegacy/1-diff.patch
@@ -0,0 +1,118 @@
+diff --git a/package-lock.json b/package-lock.json
+index 0000000..0000000 100644
+--- a/package-lock.json
++++ b/package-lock.json
+@@ -8,7 +8,6 @@
+ "name": "legacy-shop",
+ "version": "0.3.0",
+ "dependencies": {
+- "@fixture/colors": "^1.0.0",
+ "@fixture/parser": "^1.0.0",
+ "@fixture/web": "^1.0.0",
+ "request": "^2.88.2"
+@@ -23,16 +22,10 @@
+ "integrity": "sha512-ZIwBr4VEYdqVoTRJsocxd2IE16hu066kzttVg/Rt67bamJUCRNNrYr/Xpqk6x/8YmZJTmQEqLuwIbdTXIrQ1tg==",
+ "license": "MIT"
+ },
+- "node_modules/@fixture/colors": {
+- "version": "1.0.0",
+- "resolved": "http://registry.test/@fixture/colors/-/colors-1.0.0.tgz",
+- "integrity": "sha512-BOV5JBLpdodwXdW2fVogsjN8xS1COd5n1xDFwIXlDrjy02LedRTA5wFbf++3tzi0NMzv8Kd0g2Rr5jn/aR5PLg==",
+- "license": "MIT"
+- },
+ "node_modules/@fixture/parser": {
+- "version": "1.0.0",
+- "resolved": "http://registry.test/@fixture/parser/-/parser-1.0.0.tgz",
+- "integrity": "sha512-xOFkFDZr2NwNTnhYNCt51sSwFUTx7XnUIWhjlXzUmS0s2kcQC/iSh0F5HbbzdXP5Gsush0Pb319YOy3Em8zRFQ==",
++ "version": "1.0.1",
++ "resolved": "http://registry.test/@fixture/parser/-/parser-1.0.1.tgz",
++ "integrity": "sha512-ZMn52td1H/XDe9HEEnY5G4LHwQAy7qOleU9bbEU2bcTDcPUmQmi3mCePBqqlgjYDd9JGi0boF/M/CeRkdMH7Sg==",
+ "license": "MIT",
+ "dependencies": {
+ "@fixture/archive": "^1.0.0"
+diff --git a/package.json b/package.json
+index 0000000..0000000 100644
+--- a/package.json
++++ b/package.json
+@@ -7,7 +7,6 @@
+ "node": ">=4"
+ },
+ "dependencies": {
+- "@fixture/colors": "^1.0.0",
+ "@fixture/parser": "^1.0.0",
+ "@fixture/web": "^1.0.0",
+ "request": "^2.88.2"
+diff --git a/tend.yml b/tend.yml
+new file mode 100644
+index 0000000..0000000
+--- /dev/null
++++ b/tend.yml
+@@ -0,0 +1,3 @@
++verify:
++ test:
++ - node --test test/tend/characterization.js test/tend/smoke.js
+diff --git a/test/tend/characterization.js b/test/tend/characterization.js
+new file mode 100644
+index 0000000..0000000
+--- /dev/null
++++ b/test/tend/characterization.js
+@@ -0,0 +1,29 @@
++'use strict'
++
++const test = require('node:test')
++const assert = require('node:assert')
++const app = require('../../src/app')
++const client = require('../../src/client')
++
++test('health answers ok', () => {
++ assert.strictEqual(app.handle('/health'), 'ok')
++})
++
++test('an order reads its amount from the query', () => {
++ assert.strictEqual(app.handle('/order', '42'), 42)
++})
++
++test('the server starts and stops', () => {
++ const server = app.server()
++ assert.strictEqual(typeof server.close, 'function')
++ server.close()
++})
++
++test('a price is read in cents from the price service', (t, done) => {
++ globalThis.fetch = async () => ({ status: 200, text: async () => '{"cents":1250}' })
++ client.price('sku-1', (err, cents) => {
++ assert.ifError(err)
++ assert.strictEqual(cents, 1250)
++ done()
++ })
++})
+diff --git a/test/tend/smoke.js b/test/tend/smoke.js
+new file mode 100644
+index 0000000..0000000
+--- /dev/null
++++ b/test/tend/smoke.js
+@@ -0,0 +1,24 @@
++'use strict'
++
++const test = require('node:test')
++const assert = require('node:assert')
++const { spawnSync } = require('node:child_process')
++const path = require('node:path')
++const { pathToFileURL } = require('node:url')
++
++const root = path.join(__dirname, '..', '..')
++
++const modules = [
++ 'src/app.js',
++ 'src/client.js',
++ 'src/order.js',
++]
++
++for (const m of modules) {
++ test('loads ' + m, () => {
++ const url = pathToFileURL(path.join(root, m)).href
++ const code = 'import(' + JSON.stringify(url) + ').then(() => process.exit(0), (e) => { process.stderr.write(String(e && e.stack || e)); process.exit(1) })'
++ const res = spawnSync(process.execPath, ['-e', code], { cwd: root, encoding: 'utf8', timeout: 30000 })
++ assert.strictEqual(res.status, 0, res.stderr)
++ })
++}
diff --git a/internal/e2e/testdata/TestCatchUpLegacy/2-body.md b/internal/e2e/testdata/TestCatchUpLegacy/2-body.md
new file mode 100644
index 0000000..e21f896
--- /dev/null
+++ b/internal/e2e/testdata/TestCatchUpLegacy/2-body.md
@@ -0,0 +1,38 @@
+This pull request carries on tend's catch-up with runtimes and build tooling: 1 runtime minimum and 1 end-of-life runtime. 2 more stages follow, listed under Next stages.
+
+### Runtimes and tooling
+
+- `nodejs` 4 → 22 in `package.json`: nodejs 4 end of life 2018-04-30
+- `nodejs` 4.9.1 → 24.22.0 in `.nvmrc`: nodejs 4 end of life 2018-04-30
+
+### Next stages
+
+Each comes as a pull request of its own once this one is merged, proven the same way.
+
+3. Major upgrades
+ - `@fixture/web` 1.0.0 → 3.0.0 in `package.json`: a new major release.
+4. Migrations and replacements
+ - `request` 2.88.2 in `package.json`: deprecated, with no single replacement. tend takes the first of `undici`, `node-fetch` and `axios` its proof passes, in that order.
+
+### Proof
+
+| step | base (main@BASE) | patched |
+|---|---|---|
+| `npm ci` | ok · 0s | ok · 0s |
+| `node --test test/tend/characterization.js test/tend/smoke.js` | ok · 0s | ok · 0s |
+
+node --test test/tend/characterization.js test/tend/smoke.js (patched), end of its output
+
+```
+(output)
+```
+
+
+### Vetting
+
+- scope: 3 files, all explained by this change
+- lockfile: only nodejs changed
+- not applicable: symbols, fields, leftovers, debug, comments, dead, question
+
+tend · comment `tend skip` or `tend retry`
+
diff --git a/internal/e2e/testdata/TestCatchUpLegacy/3-body.md b/internal/e2e/testdata/TestCatchUpLegacy/3-body.md
new file mode 100644
index 0000000..211ed3e
--- /dev/null
+++ b/internal/e2e/testdata/TestCatchUpLegacy/3-body.md
@@ -0,0 +1,43 @@
+This pull request carries on tend's catch-up with major upgrades: 1 major upgrade. 1 more stage follows, listed under Next stages.
+
+Part of this pull request was written by a model. The vetting section below covers it.
+
+### Upgrades
+
+- `@fixture/web` 1.0.0 → 3.0.0, by way of 2.0.0, each proven: a new major release
+ - `src/app.js:8` `app.configure(function () {` → `app.set('name', 'legacy-shop')`
+ - `src/app.js:23` `return web.createServer(app)` → `return app.createServer()`
+
+### Next stages
+
+Each comes as a pull request of its own once this one is merged, proven the same way.
+
+4. Migrations and replacements
+ - `request` 2.88.2 in `package.json`: deprecated, with no single replacement. tend takes the first of `undici`, `node-fetch` and `axios` its proof passes, in that order.
+
+### Proof
+
+| step | base (main@BASE) | patched |
+|---|---|---|
+| `npm ci` | ok · 0s | ok · 0s |
+| `node --test test/tend/characterization.js test/tend/smoke.js` | ok · 0s | ok · 0s |
+
+node --test test/tend/characterization.js test/tend/smoke.js (patched), end of its output
+
+```
+(output)
+```
+
+
+### Vetting
+
+- scope: 3 files, all explained by this change
+- lockfile: only @fixture/web changed
+- debug: nothing added
+- comments: nothing added
+- dead: nothing left unreferenced
+- question: nothing to note
+- not applicable: symbols, fields, leftovers
+
+tend · comment `tend skip` or `tend retry`
+
diff --git a/internal/e2e/testdata/TestCatchUpLegacy/3-diff.patch b/internal/e2e/testdata/TestCatchUpLegacy/3-diff.patch
new file mode 100644
index 0000000..a27b730
--- /dev/null
+++ b/internal/e2e/testdata/TestCatchUpLegacy/3-diff.patch
@@ -0,0 +1,61 @@
+diff --git a/package-lock.json b/package-lock.json
+index 0000000..0000000 100644
+--- a/package-lock.json
++++ b/package-lock.json
+@@ -9,7 +9,7 @@
+ "version": "0.3.0",
+ "dependencies": {
+ "@fixture/parser": "^1.0.0",
+- "@fixture/web": "^1.0.0",
++ "@fixture/web": "^3.0.0",
+ "request": "^2.88.2"
+ },
+ "engines": {
+@@ -32,9 +32,9 @@
+ }
+ },
+ "node_modules/@fixture/web": {
+- "version": "1.0.0",
+- "resolved": "http://registry.test/@fixture/web/-/web-1.0.0.tgz",
+- "integrity": "sha512-4a4BjMHn+ug3sMbGm6y+Sw4QHxkJY5tnlUjKN079KuWdddUcVGzB+sg3jzaOXoW8A/v4mBzGSU31q+yG2dnPBQ==",
++ "version": "3.0.0",
++ "resolved": "http://registry.test/@fixture/web/-/web-3.0.0.tgz",
++ "integrity": "sha512-zfT6bLUWzyF+a5iPnn4A/faveqFoSBQzmEaLcxP0YgXOShv9koXI70fqLYIEybptdKNNEzATkmfx5ngsAy3RxQ==",
+ "license": "MIT"
+ },
+ "node_modules/request": {
+diff --git a/package.json b/package.json
+index 0000000..0000000 100644
+--- a/package.json
++++ b/package.json
+@@ -8,7 +8,7 @@
+ },
+ "dependencies": {
+ "@fixture/parser": "^1.0.0",
+- "@fixture/web": "^1.0.0",
++ "@fixture/web": "^3.0.0",
+ "request": "^2.88.2"
+ }
+ }
+diff --git a/src/app.js b/src/app.js
+index 0000000..0000000 100644
+--- a/src/app.js
++++ b/src/app.js
+@@ -5,9 +5,7 @@ var order = require('./order')
+
+ var app = web()
+
+-app.configure(function () {
+- app.set('name', 'legacy-shop')
+-})
++app.set('name', 'legacy-shop')
+
+ app.get('/health', function () {
+ return 'ok'
+@@ -20,5 +18,5 @@ app.get('/order', function (query) {
+ module.exports = app
+
+ module.exports.server = function () {
+- return web.createServer(app)
++ return app.createServer()
+ }
diff --git a/internal/e2e/testdata/TestCatchUpLegacy/4-body.md b/internal/e2e/testdata/TestCatchUpLegacy/4-body.md
new file mode 100644
index 0000000..4222e4a
--- /dev/null
+++ b/internal/e2e/testdata/TestCatchUpLegacy/4-body.md
@@ -0,0 +1,36 @@
+This pull request carries on tend's catch-up with migrations and replacements: 1 replaced library. It is the last stage; after it, tend opens one pull request at a time, only for changes that touch your code.
+
+Part of this pull request was written by a model. The vetting section below covers it.
+
+### Deprecated
+
+- `request` 2.88.2 → `undici` 7.16.0, picked from 4 options: the catalog's recommended replacement
+ - `src/client.js:6` `request.get('https://prices.example.test/v1/' + sku, function (err, res, body) {` → `undici.request('https://prices.example.test/v1/' + sku).then(function (res) { …`
+
+### Proof
+
+| step | base (main@BASE) | patched |
+|---|---|---|
+| `npm ci` | ok · 0s | ok · 0s |
+| `node --test test/tend/characterization.js test/tend/smoke.js` | ok · 0s | ok · 0s |
+
+node --test test/tend/characterization.js test/tend/smoke.js (patched), end of its output
+
+```
+(output)
+```
+
+
+### Vetting
+
+- scope: 3 files, all explained by this change
+- symbols: 1/1 changed calls resolve in undici@7.16.0 typings
+- lockfile: only request, undici changed
+- debug: nothing added
+- comments: nothing added
+- dead: nothing left unreferenced
+- question: nothing to note
+- not applicable: fields, leftovers
+
+tend · comment `tend skip` or `tend retry`
+
diff --git a/internal/e2e/testdata/TestCatchUpLegacy/4-diff.patch b/internal/e2e/testdata/TestCatchUpLegacy/4-diff.patch
new file mode 100644
index 0000000..74ec9b2
--- /dev/null
+++ b/internal/e2e/testdata/TestCatchUpLegacy/4-diff.patch
@@ -0,0 +1,64 @@
+diff --git a/package-lock.json b/package-lock.json
+index 0000000..0000000 100644
+--- a/package-lock.json
++++ b/package-lock.json
+@@ -10,7 +10,7 @@
+ "dependencies": {
+ "@fixture/parser": "^1.0.0",
+ "@fixture/web": "^3.0.0",
+- "request": "^2.88.2"
++ "undici": "^7.16.0"
+ },
+ "engines": {
+ "node": ">=22"
+@@ -37,12 +37,11 @@
+ "integrity": "sha512-zfT6bLUWzyF+a5iPnn4A/faveqFoSBQzmEaLcxP0YgXOShv9koXI70fqLYIEybptdKNNEzATkmfx5ngsAy3RxQ==",
+ "license": "MIT"
+ },
+- "node_modules/request": {
+- "version": "2.88.2",
+- "resolved": "http://registry.test/request/-/request-2.88.2.tgz",
+- "integrity": "sha512-MT/OURJK1NgRwmcoLgJ8C7Be4sRkiVeIrzdKDjd0jMxGWHu3fk9MiS7PFrKzpeKI5fvsjH0c5yi6s1X7aT0qew==",
+- "deprecated": "request has been deprecated, see https://github.com/request/request/issues/3142",
+- "license": "Apache-2.0"
++ "node_modules/undici": {
++ "version": "7.16.0",
++ "resolved": "http://registry.test/undici/-/undici-7.16.0.tgz",
++ "integrity": "sha512-/8YM9y95TIGoWPvp5IjdAjKgcPlcWVdSXcwtKBbIxjg588+30c1di6xEuRJyvnodRtz/z3DKgxYFFD/tAIdtaQ==",
++ "license": "MIT"
+ }
+ }
+ }
+diff --git a/package.json b/package.json
+index 0000000..0000000 100644
+--- a/package.json
++++ b/package.json
+@@ -9,6 +9,6 @@
+ "dependencies": {
+ "@fixture/parser": "^1.0.0",
+ "@fixture/web": "^3.0.0",
+- "request": "^2.88.2"
++ "undici": "^7.16.0"
+ }
+ }
+diff --git a/src/client.js b/src/client.js
+index 0000000..0000000 100644
+--- a/src/client.js
++++ b/src/client.js
+@@ -1,10 +1,11 @@
+ 'use strict'
+
+-var request = require('request')
++var undici = require('undici')
+
+ exports.price = function (sku, cb) {
+- request.get('https://prices.example.test/v1/' + sku, function (err, res, body) {
+- if (err) return cb(err)
+- cb(null, JSON.parse(body).cents)
+- })
++ undici.request('https://prices.example.test/v1/' + sku).then(function (res) {
++ return res.body.json()
++ }).then(function (body) {
++ cb(null, body.cents)
++ }, cb)
+ }
diff --git a/internal/e2e/testdata/TestInit/tend.yml b/internal/e2e/testdata/TestInit/tend.yml
index e980463..236fedc 100644
--- a/internal/e2e/testdata/TestInit/tend.yml
+++ b/internal/e2e/testdata/TestInit/tend.yml
@@ -4,7 +4,7 @@
# base: "" # base branch; "" means the repo's default branch
# cooldown: 3d # skip releases younger than this; security fixes and deprecations do not wait
# schedule: 1d # how often watch runs and the workflow init --ci writes: 1h to 12h, 1d or 7d
-# onboarding: pr # the first run: pr (a tidy-up PR with a welcome) | quiet (no PR, just start) | off
+# onboarding: pr # the first run: pr (one catch-up PR with a welcome) | quiet (no PR, just start) | off
# ecosystems: [] # read only these, e.g. [npm, docker, actions]; [] means all
# updates: # which changes get a pull request; a breaking change always does
diff --git a/internal/e2e/testdata/TestInit/workflow.yml b/internal/e2e/testdata/TestInit/workflow.yml
index 0f50db8..1437ccf 100644
--- a/internal/e2e/testdata/TestInit/workflow.yml
+++ b/internal/e2e/testdata/TestInit/workflow.yml
@@ -5,7 +5,7 @@ on:
paths: [.github/workflows/tend.yml]
schedule: [{cron: "17 6 * * *"}]
workflow_dispatch:
-permissions: {contents: write, pull-requests: write}
+permissions: {contents: write, pull-requests: write, issues: write, checks: read, statuses: read}
concurrency: {group: tend, cancel-in-progress: false}
jobs:
tend:
diff --git a/internal/e2e/testdata/TestNodeChoice/body.md b/internal/e2e/testdata/TestNodeChoice/body.md
new file mode 100644
index 0000000..57bc976
--- /dev/null
+++ b/internal/e2e/testdata/TestNodeChoice/body.md
@@ -0,0 +1,61 @@
+## @fixture/pay 1.4.0 → 2.0.0
+
+**Why**: deprecation · 1.x is deprecated, use 2.x: charges.* was replaced by paymentIntents.*
+**Level**: major (1 → 2)
+
+### What changed upstream
+
+- **@fixture/pay 1.4.0 is deprecated** · [source](https://www.npmjs.com/package/@fixture/pay)
+ ```
+ 1.x is deprecated, use 2.x: charges.* was replaced by paymentIntents.*
+ ```
+
+### Touched in this repo
+
+- `src/billing.js:12` `return pay.charges.create({ amount, currency: 'usd', customer })` → `return pay.paymentIntents.create({ amount, currency: 'usd', customer })`
+- `src/billing.js:20` `return pay.charges.retrieve(id)` → `return pay.paymentIntents.retrieve(id)`
+- `package-lock.json`, `package.json`
+
+### Proof
+
+| step | base (main@BASE) | patched |
+|---|---|---|
+| `npm ci` | ok · 0s | ok · 0s |
+| `npm test` | ok · 0s | ok · 0s |
+
+npm test (patched), end of its output
+
+```
+(output)
+```
+
+
+### Vetting
+
+- scope: 3 files, all explained by this change
+- symbols: 2/2 changed calls resolve in @fixture/pay@2.0.0 typings
+- leftovers: no remaining references to `charges.`
+- lockfile: only @fixture/pay changed
+- debug: nothing added
+- dead: nothing left unreferenced
+- question: not run: no model configured
+- not applicable: fields, comments
+
+### Options
+
+tend took option 1 on its own: the rename the deprecation notice names. Comment `tend apply N` to have another instead.
+
+1. **Apply the rename hinted by the deprecation notice (charges.* -> paymentIntents.*)** (not mechanical) — Move to @fixture/pay 2.0.0 and rename the calls the notice names. The notice is prose, not a migration guide, so the proof decides whether the rename is all it takes. Applied in this PR.
+2. **Pin to 1.4.0 and ignore** — Stay on 1.4.0 and have tend stop proposing 2.0.0. `tend apply 2`
+
+ This goes into tend.yml:
+
+ ```yaml
+ ignore:
+ - name: "@fixture/pay"
+ versions: [">=2.0.0"]
+ reason: staying on 1.4.0
+ ```
+
+tend · comment `tend apply N`, `tend skip` or `tend retry`
+
diff --git a/internal/e2e/testdata/TestNodeChoice/diff.patch b/internal/e2e/testdata/TestNodeChoice/diff.patch
new file mode 100644
index 0000000..818b69e
--- /dev/null
+++ b/internal/e2e/testdata/TestNodeChoice/diff.patch
@@ -0,0 +1,59 @@
+diff --git a/package-lock.json b/package-lock.json
+index 0000000..0000000 100644
+--- a/package-lock.json
++++ b/package-lock.json
+@@ -8,15 +8,14 @@
+ "name": "node-sdk",
+ "version": "1.0.0",
+ "dependencies": {
+- "@fixture/pay": "^1.4.0",
++ "@fixture/pay": "^2.0.0",
+ "@fixture/util": "^1.0.0"
+ }
+ },
+ "node_modules/@fixture/pay": {
+- "version": "1.4.0",
+- "resolved": "http://registry.test/@fixture/pay/-/pay-1.4.0.tgz",
+- "integrity": "sha512-IvDx2NsarsLhToiU9iUjFJcwTH9Gkv7L6zYyjj6yExBwSRvCS+Ogxqz0bkCtO6jn6br1mUHfq7turpu3bzp0ng==",
+- "deprecated": "1.x is deprecated, use 2.x: charges.* was replaced by paymentIntents.*",
++ "version": "2.0.0",
++ "resolved": "http://registry.test/@fixture/pay/-/pay-2.0.0.tgz",
++ "integrity": "sha512-9YOBQh5wfKucuKjW1zBQaOFTOuTYivG3T2FVonYB1RfNWwJ6oGMDOp/vNdHD34SPRfkOGiF8yhf5epc28OQDEQ==",
+ "license": "MIT"
+ },
+ "node_modules/@fixture/util": {
+diff --git a/package.json b/package.json
+index 0000000..0000000 100644
+--- a/package.json
++++ b/package.json
+@@ -6,7 +6,7 @@
+ "test": "node --test"
+ },
+ "dependencies": {
+- "@fixture/pay": "^1.4.0",
++ "@fixture/pay": "^2.0.0",
+ "@fixture/util": "^1.0.0"
+ }
+ }
+diff --git a/src/billing.js b/src/billing.js
+index 0000000..0000000 100644
+--- a/src/billing.js
++++ b/src/billing.js
+@@ -9,7 +9,7 @@ function cents(dollars) {
+ async function charge(dollars, customer) {
+ const amount = cents(dollars)
+ if (amount <= 0) throw new RangeError('nothing to charge')
+- return pay.charges.create({ amount, currency: 'usd', customer })
++ return pay.paymentIntents.create({ amount, currency: 'usd', customer })
+ }
+
+ async function lookup(id) {
+@@ -17,7 +17,7 @@ async function lookup(id) {
+ throw new TypeError('lookup needs an id')
+ }
+
+- return pay.charges.retrieve(id)
++ return pay.paymentIntents.retrieve(id)
+ }
+
+ module.exports = { charge, lookup }
diff --git a/internal/e2e/testdata/TestNodeChoice/title.txt b/internal/e2e/testdata/TestNodeChoice/title.txt
new file mode 100644
index 0000000..625bfb4
--- /dev/null
+++ b/internal/e2e/testdata/TestNodeChoice/title.txt
@@ -0,0 +1 @@
+Migrate off deprecated @fixture/pay 1.x
diff --git a/internal/e2e/testdata/TestNodeDecision/applied-body.md b/internal/e2e/testdata/TestNodeDecision/applied-body.md
index d18e86c..2bd6fca 100644
--- a/internal/e2e/testdata/TestNodeDecision/applied-body.md
+++ b/internal/e2e/testdata/TestNodeDecision/applied-body.md
@@ -12,9 +12,9 @@
### Touched in this repo
-- `src/billing.js:12` `return pay.charges.create({ amount, currency: 'usd', customer })` → `return pay.paymentIntents.create({ amount, currency: 'usd', customer })`
-- `src/billing.js:20` `return pay.charges.retrieve(id)` → `return pay.paymentIntents.retrieve(id)`
-- `package-lock.json`, `package.json`
+- `src/billing.js:12` `return pay.charges.create({ amount, currency: 'usd', customer })`
+- `src/billing.js:20` `return pay.charges.retrieve(id)`
+- `tend.yml`
### Proof
@@ -32,18 +32,16 @@
### Vetting
-- scope: 3 files, all explained by this change
-- symbols: 2/2 changed calls resolve in @fixture/pay@2.0.0 typings
-- leftovers: no remaining references to `charges.`
-- lockfile: only @fixture/pay changed
-- debug: nothing added
-- dead: nothing left unreferenced
-- not applicable: fields, comments, question
+- scope: 1 file, explained by this change
+- symbols: 2/2 calls resolve in @fixture/pay@1.4.0 typings
+- leftovers: not run: the patch stays on the version in use
+- question: not run: no model configured
+- not applicable: fields, lockfile, debug, comments, dead
### Options
-1. **Apply the rename hinted by the deprecation notice (charges.* -> paymentIntents.*)** (not mechanical) — Move to @fixture/pay 2.0.0 and rename the calls the notice names. The notice is prose, not a migration guide, so the proof decides whether the rename is all it takes. Applied in this PR.
-2. **Pin to 1.4.0 and ignore** — Stay on 1.4.0 and have tend stop proposing 2.0.0. `tend apply 2`
+1. **Apply the rename hinted by the deprecation notice (charges.* -> paymentIntents.*)** (not mechanical) — Move to @fixture/pay 2.0.0 and rename the calls the notice names. The notice is prose, not a migration guide, so the proof decides whether the rename is all it takes. `tend apply 1`
+2. **Pin to 1.4.0 and ignore** — Stay on 1.4.0 and have tend stop proposing 2.0.0. Applied in this PR.
This goes into tend.yml:
diff --git a/internal/e2e/testdata/TestNodeDecision/applied-diff.patch b/internal/e2e/testdata/TestNodeDecision/applied-diff.patch
index 818b69e..58e82f5 100644
--- a/internal/e2e/testdata/TestNodeDecision/applied-diff.patch
+++ b/internal/e2e/testdata/TestNodeDecision/applied-diff.patch
@@ -1,59 +1,10 @@
-diff --git a/package-lock.json b/package-lock.json
-index 0000000..0000000 100644
---- a/package-lock.json
-+++ b/package-lock.json
-@@ -8,15 +8,14 @@
- "name": "node-sdk",
- "version": "1.0.0",
- "dependencies": {
-- "@fixture/pay": "^1.4.0",
-+ "@fixture/pay": "^2.0.0",
- "@fixture/util": "^1.0.0"
- }
- },
- "node_modules/@fixture/pay": {
-- "version": "1.4.0",
-- "resolved": "http://registry.test/@fixture/pay/-/pay-1.4.0.tgz",
-- "integrity": "sha512-IvDx2NsarsLhToiU9iUjFJcwTH9Gkv7L6zYyjj6yExBwSRvCS+Ogxqz0bkCtO6jn6br1mUHfq7turpu3bzp0ng==",
-- "deprecated": "1.x is deprecated, use 2.x: charges.* was replaced by paymentIntents.*",
-+ "version": "2.0.0",
-+ "resolved": "http://registry.test/@fixture/pay/-/pay-2.0.0.tgz",
-+ "integrity": "sha512-9YOBQh5wfKucuKjW1zBQaOFTOuTYivG3T2FVonYB1RfNWwJ6oGMDOp/vNdHD34SPRfkOGiF8yhf5epc28OQDEQ==",
- "license": "MIT"
- },
- "node_modules/@fixture/util": {
-diff --git a/package.json b/package.json
-index 0000000..0000000 100644
---- a/package.json
-+++ b/package.json
-@@ -6,7 +6,7 @@
- "test": "node --test"
- },
- "dependencies": {
-- "@fixture/pay": "^1.4.0",
-+ "@fixture/pay": "^2.0.0",
- "@fixture/util": "^1.0.0"
- }
- }
-diff --git a/src/billing.js b/src/billing.js
-index 0000000..0000000 100644
---- a/src/billing.js
-+++ b/src/billing.js
-@@ -9,7 +9,7 @@ function cents(dollars) {
- async function charge(dollars, customer) {
- const amount = cents(dollars)
- if (amount <= 0) throw new RangeError('nothing to charge')
-- return pay.charges.create({ amount, currency: 'usd', customer })
-+ return pay.paymentIntents.create({ amount, currency: 'usd', customer })
- }
-
- async function lookup(id) {
-@@ -17,7 +17,7 @@ async function lookup(id) {
- throw new TypeError('lookup needs an id')
- }
-
-- return pay.charges.retrieve(id)
-+ return pay.paymentIntents.retrieve(id)
- }
-
- module.exports = { charge, lookup }
+diff --git a/tend.yml b/tend.yml
+new file mode 100644
+index 0000000..0000000
+--- /dev/null
++++ b/tend.yml
+@@ -0,0 +1,4 @@
++ignore:
++ - name: "@fixture/pay"
++ versions: [">=2.0.0"]
++ reason: staying on 1.4.0
diff --git a/internal/e2e/testdata/TestNodeDeprecation/check.json b/internal/e2e/testdata/TestNodeDeprecation/check.json
index f4236d4..11c69e9 100644
--- a/internal/e2e/testdata/TestNodeDeprecation/check.json
+++ b/internal/e2e/testdata/TestNodeDeprecation/check.json
@@ -78,6 +78,7 @@
{
"detail": "Stay on 1.4.0 and have tend stop proposing 2.0.0.\n\nThis goes into tend.yml:\n\n```yaml\nignore:\n - name: \"@fixture/pay\"\n versions: [\">=2.0.0\"]\n reason: staying on 1.4.0\n```",
"safe": false,
+ "stay": true,
"title": "Pin to 1.4.0 and ignore",
"to": "1.4.0"
}
diff --git a/internal/e2e/testdata/TestOnboardCatchUp/body.md b/internal/e2e/testdata/TestOnboardCatchUp/body.md
new file mode 100644
index 0000000..234b583
--- /dev/null
+++ b/internal/e2e/testdata/TestOnboardCatchUp/body.md
@@ -0,0 +1,52 @@
+Thanks for adding tend: it looks after the packages this repository depends on and the APIs its code calls. This first pull request catches up in one go: 2 security fixes, 1 deprecated library and 3 unused dependencies. From now on it opens one pull request at a time, only for changes that touch your code, and each one shows the build and test runs that prove it. Steer it with `tend.yml`, or comment `tend skip`, `tend retry` or `tend apply N` on its pull requests.
+
+Part of this pull request was written by a model. The vetting section below covers it.
+
+### Security
+
+npm:
+
+- `@fixture/archive` 1.0.0 → 1.1.1 (transitive): GHSA-2c8f-9v3w-4hq7 (high); 1.1.0 fixes it, and the lockfile took the newest release its ranges allow
+- `@fixture/parser` 1.0.0 → 1.0.1: GHSA-3m7x-8p2r-6fjw (moderate)
+
+### Deprecated
+
+- `@fixture/pay` 1.4.0 → 2.0.0: 1.x is deprecated, use 2.x: charges.* was replaced by paymentIntents.*
+ - `src/billing.js:12` `return pay.charges.create({ amount, currency: 'usd', customer })` → `return pay.paymentIntents.create({ amount, currency: 'usd', customer })`
+ - `src/billing.js:20` `return pay.charges.retrieve(id)` → `return pay.paymentIntents.retrieve(id)`
+
+### Unused
+
+Removed, since nothing in the project uses them:
+
+- `@fixture/colors` 1.0.0 in `package.json`
+- `@fixture/strings` 1.0.0 in `package.json`
+- `@fixture/old-test-helper` 1.0.0 in `package.json`
+
+### Proof
+
+| step | base (main@BASE) | patched |
+|---|---|---|
+| `npm ci` | ok · 0s | ok · 0s |
+| `npm test` | ok · 0s | ok · 0s |
+
+npm test (patched), end of its output
+
+```
+(output)
+```
+
+
+### Vetting
+
+- scope: 3 files, all explained by this change
+- symbols: 3/3 calls resolve in @fixture/parser@1.0.1 typings, in @fixture/pay@2.0.0 typings
+- lockfile: only @fixture/colors, @fixture/strings, @fixture/old-test-helper, @fixture/archive, @fixture/parser, @fixture/pay changed
+- debug: nothing added
+- comments: nothing added
+- dead: nothing left unreferenced
+- question: nothing to note
+- not applicable: fields, leftovers
+
+tend · comment `tend skip` or `tend retry`
+
diff --git a/internal/e2e/testdata/TestOnboardCatchUp/diff.patch b/internal/e2e/testdata/TestOnboardCatchUp/diff.patch
new file mode 100644
index 0000000..a1e690d
--- /dev/null
+++ b/internal/e2e/testdata/TestOnboardCatchUp/diff.patch
@@ -0,0 +1,134 @@
+diff --git a/package-lock.json b/package-lock.json
+index 0000000..0000000 100644
+--- a/package-lock.json
++++ b/package-lock.json
+@@ -8,31 +8,22 @@
+ "name": "node-catchup",
+ "version": "1.0.0",
+ "dependencies": {
+- "@fixture/colors": "^1.0.0",
+ "@fixture/format": "^1.1.0",
+ "@fixture/parser": "^1.0.0",
+- "@fixture/pay": "^1.4.0",
++ "@fixture/pay": "^2.0.0",
+ "@fixture/plugin-host": "^1.0.0",
+- "@fixture/runtime": "^1.0.0",
+- "@fixture/strings": "^1.0.0"
++ "@fixture/runtime": "^1.0.0"
+ },
+ "devDependencies": {
+ "@fixture/linter": "^1.0.0",
+- "@fixture/old-test-helper": "^1.0.0",
+ "@types/fixture__pay": "^1.0.0",
+ "eslint-plugin-fixture": "^1.0.0"
+ }
+ },
+ "node_modules/@fixture/archive": {
+- "version": "1.0.0",
+- "resolved": "http://registry.test/@fixture/archive/-/archive-1.0.0.tgz",
+- "integrity": "sha512-ZIwBr4VEYdqVoTRJsocxd2IE16hu066kzttVg/Rt67bamJUCRNNrYr/Xpqk6x/8YmZJTmQEqLuwIbdTXIrQ1tg==",
+- "license": "MIT"
+- },
+- "node_modules/@fixture/colors": {
+- "version": "1.0.0",
+- "resolved": "http://registry.test/@fixture/colors/-/colors-1.0.0.tgz",
+- "integrity": "sha512-BOV5JBLpdodwXdW2fVogsjN8xS1COd5n1xDFwIXlDrjy02LedRTA5wFbf++3tzi0NMzv8Kd0g2Rr5jn/aR5PLg==",
++ "version": "1.1.1",
++ "resolved": "http://registry.test/@fixture/archive/-/archive-1.1.1.tgz",
++ "integrity": "sha512-1vMi1aAeqVjQYEw+kn5Gamp+dlkFmRMzSvE5V00S73mcqad3dePTkhyvxEJGBMK1KKmraxOGc4x0t/F9+a/h1A==",
+ "license": "MIT"
+ },
+ "node_modules/@fixture/format": {
+@@ -51,27 +42,19 @@
+ "fixture-lint": "cli.js"
+ }
+ },
+- "node_modules/@fixture/old-test-helper": {
+- "version": "1.0.0",
+- "resolved": "http://registry.test/@fixture/old-test-helper/-/old-test-helper-1.0.0.tgz",
+- "integrity": "sha512-dkXGzzC5b/wxzHdSCTUb/9WzzTXvNaJPFj8beaH8ExYmXg6/mgHjHRlgkjlgeKstmvL14k1ZOtDo8n1QvUEWEQ==",
+- "dev": true,
+- "license": "MIT"
+- },
+ "node_modules/@fixture/parser": {
+- "version": "1.0.0",
+- "resolved": "http://registry.test/@fixture/parser/-/parser-1.0.0.tgz",
+- "integrity": "sha512-xOFkFDZr2NwNTnhYNCt51sSwFUTx7XnUIWhjlXzUmS0s2kcQC/iSh0F5HbbzdXP5Gsush0Pb319YOy3Em8zRFQ==",
++ "version": "1.0.1",
++ "resolved": "http://registry.test/@fixture/parser/-/parser-1.0.1.tgz",
++ "integrity": "sha512-ZMn52td1H/XDe9HEEnY5G4LHwQAy7qOleU9bbEU2bcTDcPUmQmi3mCePBqqlgjYDd9JGi0boF/M/CeRkdMH7Sg==",
+ "license": "MIT",
+ "dependencies": {
+ "@fixture/archive": "^1.0.0"
+ }
+ },
+ "node_modules/@fixture/pay": {
+- "version": "1.4.0",
+- "resolved": "http://registry.test/@fixture/pay/-/pay-1.4.0.tgz",
+- "integrity": "sha512-IvDx2NsarsLhToiU9iUjFJcwTH9Gkv7L6zYyjj6yExBwSRvCS+Ogxqz0bkCtO6jn6br1mUHfq7turpu3bzp0ng==",
+- "deprecated": "1.x is deprecated, use 2.x: charges.* was replaced by paymentIntents.*",
++ "version": "2.0.0",
++ "resolved": "http://registry.test/@fixture/pay/-/pay-2.0.0.tgz",
++ "integrity": "sha512-9YOBQh5wfKucuKjW1zBQaOFTOuTYivG3T2FVonYB1RfNWwJ6oGMDOp/vNdHD34SPRfkOGiF8yhf5epc28OQDEQ==",
+ "license": "MIT"
+ },
+ "node_modules/@fixture/plugin-host": {
+@@ -89,12 +72,6 @@
+ "integrity": "sha512-V7ABsWxxqmuvCC/bjk8W3KGxo7S79COQm1WZ/r5FXWgGOB743ry6h15LuLrGrZkgkF9EFuRw7KjZYNKsbHDl5Q==",
+ "license": "MIT"
+ },
+- "node_modules/@fixture/strings": {
+- "version": "1.0.0",
+- "resolved": "http://registry.test/@fixture/strings/-/strings-1.0.0.tgz",
+- "integrity": "sha512-XVhP66Ypk9sJJasyIyV9tIHZHRVuUNsD58Jb3SEXLLC4yCPIUGLEMGV9qjDaL98lK9/eNDzalaD08Pi9cGDZ/Q==",
+- "license": "MIT"
+- },
+ "node_modules/@types/fixture__pay": {
+ "version": "1.0.0",
+ "resolved": "http://registry.test/@types/fixture__pay/-/fixture__pay-1.0.0.tgz",
+diff --git a/package.json b/package.json
+index 0000000..0000000 100644
+--- a/package.json
++++ b/package.json
+@@ -7,17 +7,14 @@
+ "lint": "fixture-lint src"
+ },
+ "dependencies": {
+- "@fixture/colors": "^1.0.0",
+ "@fixture/format": "^1.1.0",
+ "@fixture/parser": "^1.0.0",
+- "@fixture/pay": "^1.4.0",
++ "@fixture/pay": "^2.0.0",
+ "@fixture/plugin-host": "^1.0.0",
+- "@fixture/runtime": "^1.0.0",
+- "@fixture/strings": "^1.0.0"
++ "@fixture/runtime": "^1.0.0"
+ },
+ "devDependencies": {
+ "@fixture/linter": "^1.0.0",
+- "@fixture/old-test-helper": "^1.0.0",
+ "@types/fixture__pay": "^1.0.0",
+ "eslint-plugin-fixture": "^1.0.0"
+ }
+diff --git a/src/billing.js b/src/billing.js
+index 0000000..0000000 100644
+--- a/src/billing.js
++++ b/src/billing.js
+@@ -9,7 +9,7 @@ function cents(dollars) {
+ async function charge(dollars, customer) {
+ const amount = cents(dollars)
+ if (amount <= 0) throw new RangeError('nothing to charge')
+- return pay.charges.create({ amount, currency: 'usd', customer })
++ return pay.paymentIntents.create({ amount, currency: 'usd', customer })
+ }
+
+ async function lookup(id) {
+@@ -17,7 +17,7 @@ async function lookup(id) {
+ throw new TypeError('lookup needs an id')
+ }
+
+- return pay.charges.retrieve(id)
++ return pay.paymentIntents.retrieve(id)
+ }
+
+ module.exports = { charge, lookup }
diff --git a/internal/e2e/testdata/TestOnboardCatchUp/title.txt b/internal/e2e/testdata/TestOnboardCatchUp/title.txt
new file mode 100644
index 0000000..855e4da
--- /dev/null
+++ b/internal/e2e/testdata/TestOnboardCatchUp/title.txt
@@ -0,0 +1 @@
+Catch up: 2 security fixes, 1 deprecated library, 3 unused dependencies
diff --git a/internal/e2e/testdata/TestOnboardClean/body.md b/internal/e2e/testdata/TestOnboardClean/body.md
index 4a819f6..96f4f3a 100644
--- a/internal/e2e/testdata/TestOnboardClean/body.md
+++ b/internal/e2e/testdata/TestOnboardClean/body.md
@@ -1,8 +1,4 @@
-Thanks for adding tend: it looks after the packages this repository depends on and the APIs its code calls. Its first look found nothing to tidy up, so this pull request only adds a `tend.yml` with every key commented out. From now on it opens one pull request at a time, only for changes that touch your code, and each one shows the build and test runs that prove it. Steer it with `tend.yml`, or comment `tend skip`, `tend retry` or `tend apply N` on its pull requests.
-
-### What changed
-
-Adds `tend.yml` with every key commented out, so it changes nothing until you uncomment a line.
+Thanks for adding tend: it looks after the packages this repository depends on and the APIs its code calls. Its first look found nothing to catch up on, so this pull request only adds a `tend.yml` with every key commented out. From now on it opens one pull request at a time, only for changes that touch your code, and each one shows the build and test runs that prove it. Steer it with `tend.yml`, or comment `tend skip`, `tend retry` or `tend apply N` on its pull requests.
### Proof
@@ -25,4 +21,4 @@ Adds `tend.yml` with every key commented out, so it changes nothing until you un
- not applicable: symbols, fields, leftovers, lockfile, debug, comments, dead
tend · comment `tend skip` or `tend retry`
-
+
diff --git a/internal/e2e/testdata/TestOnboardClean/title.txt b/internal/e2e/testdata/TestOnboardClean/title.txt
index cbd6361..4a6e1ac 100644
--- a/internal/e2e/testdata/TestOnboardClean/title.txt
+++ b/internal/e2e/testdata/TestOnboardClean/title.txt
@@ -1 +1 @@
-Set up tend: nothing to tidy up
+Set up tend: nothing to catch up on
diff --git a/internal/e2e/testdata/TestOnboardGo/body.md b/internal/e2e/testdata/TestOnboardGo/body.md
index 31a1bc2..387cf11 100644
--- a/internal/e2e/testdata/TestOnboardGo/body.md
+++ b/internal/e2e/testdata/TestOnboardGo/body.md
@@ -1,13 +1,17 @@
-Thanks for adding tend: it looks after the packages this repository depends on and the APIs its code calls. This first pull request tidies up: it removes 1 dependency nothing in the project uses. From now on it opens one pull request at a time, only for changes that touch your code, and each one shows the build and test runs that prove it. Steer it with `tend.yml`, or comment `tend skip`, `tend retry` or `tend apply N` on its pull requests.
+Thanks for adding tend: it looks after the packages this repository depends on and the APIs its code calls. This first pull request catches up in one go: 1 security fix and 1 unused dependency. From now on it opens one pull request at a time, only for changes that touch your code, and each one shows the build and test runs that prove it. Steer it with `tend.yml`, or comment `tend skip`, `tend retry` or `tend apply N` on its pull requests.
-### What changed
+### Security
+
+go:
+
+- `example.com/fixture/crypto` v1.0.0 → v1.0.1: GO-2026-0001 (high)
+
+### Unused
Removed, since nothing in the project uses it:
- `example.com/fixture/logs` v1.0.0 in `go.mod`
-Files: `go.mod`, `go.sum`.
-
### Proof
| step | base (main@BASE) | patched |
@@ -25,8 +29,9 @@ Files: `go.mod`, `go.sum`.
### Vetting
- scope: 2 files, all explained by this change
+- symbols: 2/2 calls resolve (go doc)
- question: not run: no model configured
-- not applicable: symbols, fields, leftovers, lockfile, debug, comments, dead
+- not applicable: fields, leftovers, lockfile, debug, comments, dead
tend · comment `tend skip` or `tend retry`
-
+
diff --git a/internal/e2e/testdata/TestOnboardGo/diff.patch b/internal/e2e/testdata/TestOnboardGo/diff.patch
index 80d8b8a..6416dde 100644
--- a/internal/e2e/testdata/TestOnboardGo/diff.patch
+++ b/internal/e2e/testdata/TestOnboardGo/diff.patch
@@ -10,13 +10,15 @@ index 0000000..0000000 100644
- example.com/fixture/crypto v1.0.0
- example.com/fixture/logs v1.0.0
-)
-+require example.com/fixture/crypto v1.0.0
++require example.com/fixture/crypto v1.0.1
diff --git a/go.sum b/go.sum
index 0000000..0000000 100644
--- a/go.sum
+++ b/go.sum
@@ -1,4 +1,2 @@
- example.com/fixture/crypto v1.0.0 h1:vrBom59kTwQSYRLB5WOxm6l/4fr+33oT/5ezo63Dj88=
- example.com/fixture/crypto v1.0.0/go.mod h1:U2RqA19ltmzFBEbpvtP8yHQ/GHiK6ybzjiU47kMky7I=
+-example.com/fixture/crypto v1.0.0 h1:vrBom59kTwQSYRLB5WOxm6l/4fr+33oT/5ezo63Dj88=
+-example.com/fixture/crypto v1.0.0/go.mod h1:U2RqA19ltmzFBEbpvtP8yHQ/GHiK6ybzjiU47kMky7I=
-example.com/fixture/logs v1.0.0 h1:WkHBkWSzhQaoFYrCh0BDr36uZPNOAWlKoUWmkuIwOs4=
-example.com/fixture/logs v1.0.0/go.mod h1:w9mECgo9el/+0O+WFyCwGPnfQi3kqCpP95Y9HSbE2y0=
++example.com/fixture/crypto v1.0.1 h1:ydh+j9gKuIt3ihI9rSJsBsfF70FzHa0JwH6y+QXzqzE=
++example.com/fixture/crypto v1.0.1/go.mod h1:U2RqA19ltmzFBEbpvtP8yHQ/GHiK6ybzjiU47kMky7I=
diff --git a/internal/e2e/testdata/TestOnboardGo/title.txt b/internal/e2e/testdata/TestOnboardGo/title.txt
index 66e027d..e239eab 100644
--- a/internal/e2e/testdata/TestOnboardGo/title.txt
+++ b/internal/e2e/testdata/TestOnboardGo/title.txt
@@ -1 +1 @@
-Tidy up: remove 1 unused dependency
+Catch up: 1 security fix, 1 unused dependency
diff --git a/internal/e2e/testdata/TestOnboardNode/body.md b/internal/e2e/testdata/TestOnboardNode/body.md
index 69f9420..a94e89b 100644
--- a/internal/e2e/testdata/TestOnboardNode/body.md
+++ b/internal/e2e/testdata/TestOnboardNode/body.md
@@ -1,22 +1,20 @@
-Thanks for adding tend: it looks after the packages this repository depends on and the APIs its code calls. This first pull request tidies up: it removes 3 dependencies nothing in the project uses and moves the code off 1 deprecated library. From now on it opens one pull request at a time, only for changes that touch your code, and each one shows the build and test runs that prove it. Steer it with `tend.yml`, or comment `tend skip`, `tend retry` or `tend apply N` on its pull requests.
+Thanks for adding tend: it looks after the packages this repository depends on and the APIs its code calls. This first pull request catches up in one go: 1 deprecated library and 3 unused dependencies. From now on it opens one pull request at a time, only for changes that touch your code, and each one shows the build and test runs that prove it. Steer it with `tend.yml`, or comment `tend skip`, `tend retry` or `tend apply N` on its pull requests.
-### What changed
+Part of this pull request was written by a model. The vetting section below covers it.
-Removed, since nothing in the project uses them:
-
-- `@fixture/colors` 1.0.0 in `package.json`
-- `@fixture/strings` 1.0.0 in `package.json`
-- `@fixture/old-test-helper` 1.0.0 in `package.json`
-
-Moved off a deprecated library:
+### Deprecated
- `@fixture/pay` 1.4.0 → 2.0.0: 1.x is deprecated, use 2.x: charges.* was replaced by paymentIntents.*
- `src/billing.js:12` `return pay.charges.create({ amount, currency: 'usd', customer })` → `return pay.paymentIntents.create({ amount, currency: 'usd', customer })`
- `src/billing.js:20` `return pay.charges.retrieve(id)` → `return pay.paymentIntents.retrieve(id)`
-Files: `package-lock.json`, `package.json`, `src/billing.js`.
+### Unused
-Part of this change was written by a model. The vetting section below covers it.
+Removed, since nothing in the project uses them:
+
+- `@fixture/colors` 1.0.0 in `package.json`
+- `@fixture/strings` 1.0.0 in `package.json`
+- `@fixture/old-test-helper` 1.0.0 in `package.json`
### Proof
@@ -44,4 +42,4 @@ Part of this change was written by a model. The vetting section below covers it.
- not applicable: fields, leftovers
tend · comment `tend skip` or `tend retry`
-
+
diff --git a/internal/e2e/testdata/TestOnboardNode/check.txt b/internal/e2e/testdata/TestOnboardNode/check.txt
index 5b37d23..a53f4f9 100644
--- a/internal/e2e/testdata/TestOnboardNode/check.txt
+++ b/internal/e2e/testdata/TestOnboardNode/check.txt
@@ -1,4 +1,4 @@
tend: 2 queued, 0 skipped, no open PR
- 1 tidy first PR remove 3 unused · move off 1 deprecated
+ 1 first first PR move off 1 deprecated · remove 3 unused
2 deprecation @fixture/pay 1.4.0 → 2.0.0 2 sites
diff --git a/internal/e2e/testdata/TestOnboardNode/title.txt b/internal/e2e/testdata/TestOnboardNode/title.txt
index 1316764..d979a39 100644
--- a/internal/e2e/testdata/TestOnboardNode/title.txt
+++ b/internal/e2e/testdata/TestOnboardNode/title.txt
@@ -1 +1 @@
-Tidy up: remove 3 unused dependencies, move off 1 deprecated library
+Catch up: 1 deprecated library, 3 unused dependencies
diff --git a/internal/e2e/testdata/replies/legacy-baseline.md b/internal/e2e/testdata/replies/legacy-baseline.md
new file mode 100644
index 0000000..dd11f28
--- /dev/null
+++ b/internal/e2e/testdata/replies/legacy-baseline.md
@@ -0,0 +1,31 @@
+```js
+'use strict'
+
+const test = require('node:test')
+const assert = require('node:assert')
+const app = require('../../src/app')
+const client = require('../../src/client')
+
+test('health answers ok', () => {
+ assert.strictEqual(app.handle('/health'), 'ok')
+})
+
+test('an order reads its amount from the query', () => {
+ assert.strictEqual(app.handle('/order', '42'), 42)
+})
+
+test('the server starts and stops', () => {
+ const server = app.server()
+ assert.strictEqual(typeof server.close, 'function')
+ server.close()
+})
+
+test('a price is read in cents from the price service', (t, done) => {
+ globalThis.fetch = async () => ({ status: 200, text: async () => '{"cents":1250}' })
+ client.price('sku-1', (err, cents) => {
+ assert.ifError(err)
+ assert.strictEqual(cents, 1250)
+ done()
+ })
+})
+```
diff --git a/internal/e2e/testdata/replies/legacy-undici.diff b/internal/e2e/testdata/replies/legacy-undici.diff
new file mode 100644
index 0000000..5202be5
--- /dev/null
+++ b/internal/e2e/testdata/replies/legacy-undici.diff
@@ -0,0 +1,20 @@
+diff --git a/src/client.js b/src/client.js
+--- a/src/client.js
++++ b/src/client.js
+@@ -1,10 +1,11 @@
+ 'use strict'
+
+-var request = require('request')
++var undici = require('undici')
+
+ exports.price = function (sku, cb) {
+- request.get('https://prices.example.test/v1/' + sku, function (err, res, body) {
+- if (err) return cb(err)
+- cb(null, JSON.parse(body).cents)
+- })
++ undici.request('https://prices.example.test/v1/' + sku).then(function (res) {
++ return res.body.json()
++ }).then(function (body) {
++ cb(null, body.cents)
++ }, cb)
+ }
diff --git a/internal/e2e/testdata/replies/legacy-web-2.diff b/internal/e2e/testdata/replies/legacy-web-2.diff
new file mode 100644
index 0000000..9480551
--- /dev/null
+++ b/internal/e2e/testdata/replies/legacy-web-2.diff
@@ -0,0 +1,14 @@
+diff --git a/src/app.js b/src/app.js
+--- a/src/app.js
++++ b/src/app.js
+@@ -5,9 +5,7 @@ var order = require('./order')
+
+ var app = web()
+
+-app.configure(function () {
+- app.set('name', 'legacy-shop')
+-})
++app.set('name', 'legacy-shop')
+
+ app.get('/health', function () {
+ return 'ok'
diff --git a/internal/e2e/testdata/replies/legacy-web-3.diff b/internal/e2e/testdata/replies/legacy-web-3.diff
new file mode 100644
index 0000000..16313fd
--- /dev/null
+++ b/internal/e2e/testdata/replies/legacy-web-3.diff
@@ -0,0 +1,10 @@
+diff --git a/src/app.js b/src/app.js
+--- a/src/app.js
++++ b/src/app.js
+@@ -18,5 +18,5 @@ app.get('/order', function (query) {
+ module.exports = app
+
+ module.exports.server = function () {
+- return web.createServer(app)
++ return app.createServer()
+ }
diff --git a/internal/eco/actions.go b/internal/eco/actions.go
index d1be3c1..c21924e 100644
--- a/internal/eco/actions.go
+++ b/internal/eco/actions.go
@@ -347,7 +347,7 @@ func actionPin(repo, tag string) (sha, name string, err error) {
func (actions) Commands(root string, m core.Manifest) core.Commands { return core.Commands{} }
func (actions) Traits() core.Traits {
- return core.Traits{OSV: "GitHub Actions", Page: prefix("https://github.com/"), KeepShape: true}
+ return core.Traits{OSV: "GitHub Actions", Page: prefix("https://github.com/"), KeepShape: true, Tooling: true}
}
func (actions) Imports(d core.Dep) []string { return nil }
diff --git a/internal/eco/docker.go b/internal/eco/docker.go
index 00006ce..cd085f5 100644
--- a/internal/eco/docker.go
+++ b/internal/eco/docker.go
@@ -674,7 +674,7 @@ func dockerSetArg(p string, r dockerRef, to string) (bool, error) {
func (docker) Commands(root string, m core.Manifest) core.Commands { return core.Commands{} }
func (docker) Traits() core.Traits {
- return core.Traits{Page: dockerPage, KeepShape: true}
+ return core.Traits{Page: dockerPage, KeepShape: true, Tooling: true}
}
func dockerPage(name string) string {
diff --git a/internal/eco/lock.go b/internal/eco/lock.go
index 52fd914..71f9843 100644
--- a/internal/eco/lock.go
+++ b/internal/eco/lock.go
@@ -8,6 +8,7 @@ import (
"path"
"path/filepath"
"slices"
+ "strconv"
"strings"
"github.com/mohsensc/tend-cli/internal/core"
@@ -203,29 +204,57 @@ func lockedVersions(root, lock, ecosystem, name string) (map[string]bool, error)
return res, nil
}
-// lockedTo checks a targeted update against what it actually locked. Left to
-// itself the tool takes the newest release the ranges allow, which need not
-// be the release tend chose and proves: every version of name it brought in
-// must be to, and to must be locked.
-func lockedTo(root, lock, ecosystem, name, to string, before map[string]bool) error {
+// lockedTo checks a targeted update of a dep only the lockfile names against
+// what it actually locked. The tool moves such a dep to the newest release
+// its ranges allow, so to is a floor: every version of name the update
+// brought in must be to or later on to's major, and one of them must be
+// locked. It returns the newest one when that is past to, else "".
+func lockedTo(root, lock, ecosystem, name, to string, before map[string]bool) (string, error) {
after, err := lockedVersions(root, lock, ecosystem, name)
if err != nil {
- return err
+ return "", err
+ }
+ floor, ok := ver.Parse(to)
+ fits := func(v string) bool {
+ x, okX := ver.Parse(v)
+ if !ok || !okX {
+ return sameVersion(v, to)
+ }
+ return ver.Compare(x, floor) >= 0 && x.Major() == floor.Major()
}
- is := func(v string) bool { return sameVersion(v, to) }
- var other []string
+ var other, in []string
for _, v := range keys(after) {
- if !before[v] && !is(v) {
+ switch {
+ case before[v] && !fits(v):
+ case fits(v):
+ in = append(in, v)
+ default:
other = append(other, v)
}
}
switch {
case len(other) > 0:
- return fmt.Errorf("%s: the update locked %s at %s, not %s", lock, name, strings.Join(other, ", "), to)
- case !slices.ContainsFunc(keys(after), is):
- return fmt.Errorf("%s: the update did not lock %s at %s", lock, name, to)
+ return "", fmt.Errorf("%s: the update locked %s at %s, not %s or a later %s", lock, name, strings.Join(other, ", "), to, series(to))
+ case len(in) == 0:
+ return "", fmt.Errorf("%s: the update did not lock %s at %s or a later %s", lock, name, to, series(to))
+ }
+ slices.SortFunc(in, func(a, b string) int {
+ x, _ := ver.Parse(a)
+ y, _ := ver.Parse(b)
+ return ver.Compare(x, y)
+ })
+ if top := in[len(in)-1]; !sameVersion(top, to) {
+ return top, nil
+ }
+ return "", nil
+}
+
+// series names the major release line of v: "7.x" for 7.5.21.
+func series(v string) string {
+ if x, ok := ver.Parse(v); ok {
+ return strconv.Itoa(x.Major()) + ".x"
}
- return nil
+ return "release"
}
// lockLanded checks that the lockfile at lock pins name at to. A targeted
diff --git a/internal/eco/npm.go b/internal/eco/npm.go
index 2d9f6cb..9542628 100644
--- a/internal/eco/npm.go
+++ b/internal/eco/npm.go
@@ -587,12 +587,13 @@ func (n npm) Bump(ctx context.Context, root string, d core.Dep, to, toName strin
if err := runIn(ctx, root, path.Dir(m.Lock), nil, line); err != nil {
return nil, err
}
+ landed := ""
if targeted {
- if err := lockedTo(root, m.Lock, core.Npm, d.Name, to, before); err != nil {
+ if landed, err = lockedTo(root, m.Lock, core.Npm, d.Name, to, before); err != nil {
return nil, errors.Join(fmt.Errorf("%w; %s moves a transitive dep only to the newest release its ranges allow", err, m.Tool), snap.restore(root))
}
}
- return &core.Bump{Files: snap.changed(root), Locked: true}, nil
+ return &core.Bump{Files: snap.changed(root), Locked: true, Landed: landed}, nil
}
// lockAt locks deps, all of one manifest, at exactly to. Left to itself the
diff --git a/internal/eco/npm_test.go b/internal/eco/npm_test.go
index a150bb3..a8b5954 100644
--- a/internal/eco/npm_test.go
+++ b/internal/eco/npm_test.go
@@ -535,18 +535,21 @@ func lockTool(t *testing.T, name, from, to string) func(root string) []string {
}
}
-// A targeted update that locks anything but the chosen release fails the
-// bump and leaves the files as they were.
+// A targeted update may lock the chosen release or a later one of its
+// major, and says which; anything else fails the bump and leaves the files
+// as they were.
func TestNpmTargetedLockChecked(t *testing.T) {
tests := []struct {
fixture, tool, to, locks string
- err string
+ landed, err string
}{
- {"npm/lock-v3", "npm", "2.1.4", "2.1.4", ""},
- {"npm/lock-v3", "npm", "2.1.4", "2.1.9", "locked ms at 2.1.9, not 2.1.4"},
- {"npm/lock-v3", "npm", "2.1.4", "2.1.3", "did not lock ms at 2.1.4"},
- {"npm/pnpm-v9", "pnpm", "2.1.4", "2.1.9", "locked ms at 2.1.9, not 2.1.4"},
- {"npm/yarn-berry", "yarn", "2.1.4", "2.1.9", "locked ms at 2.1.9, not 2.1.4"},
+ {"npm/lock-v3", "npm", "2.1.4", "2.1.4", "", ""},
+ {"npm/lock-v3", "npm", "2.1.4", "2.1.9", "2.1.9", ""},
+ {"npm/lock-v3", "npm", "2.1.4", "3.0.0", "", "locked ms at 3.0.0, not 2.1.4 or a later 2.x"},
+ {"npm/lock-v3", "npm", "2.1.4", "2.1.3", "", "did not lock ms at 2.1.4 or a later 2.x"},
+ {"npm/pnpm-v9", "pnpm", "2.1.4", "2.1.9", "2.1.9", ""},
+ {"npm/pnpm-v9", "pnpm", "2.1.4", "3.0.0", "", "locked ms at 3.0.0, not 2.1.4 or a later 2.x"},
+ {"npm/yarn-berry", "yarn", "2.1.4", "2.1.9", "2.1.9", ""},
}
for _, tt := range tests {
t.Run(tt.fixture+"/"+tt.locks, func(t *testing.T) {
@@ -556,8 +559,8 @@ func TestNpmTargetedLockChecked(t *testing.T) {
before := treeSnapshot(t, root)
res, err := (npm{}).Bump(context.Background(), root, d, tt.to, "")
if tt.err == "" {
- if err != nil || !res.Locked {
- t.Fatalf("bump = %+v, %v", res, err)
+ if err != nil || !res.Locked || res.Landed != tt.landed {
+ t.Fatalf("bump = %+v, %v; want landed %q", res, err, tt.landed)
}
return
}
diff --git a/internal/eco/npm_unused.go b/internal/eco/npm_unused.go
index 344f293..ffc3f96 100644
--- a/internal/eco/npm_unused.go
+++ b/internal/eco/npm_unused.go
@@ -262,8 +262,8 @@ func npmPlugin(name string) (tool, short string, ok bool) {
return "", "", false
}
-// npmFacts are what a lockfile records about installed packages that a
-// tidy-up needs: the commands each installs, and which packages need it as
+// npmFacts are what a lockfile records about installed packages that the
+// first PR needs: the commands each installs, and which packages need it as
// a peer. known is false for a lockfile that does not record peers.
type npmFacts struct {
known bool
diff --git a/internal/eco/python.go b/internal/eco/python.go
index ce601cc..dcaaf74 100644
--- a/internal/eco/python.go
+++ b/internal/eco/python.go
@@ -505,7 +505,7 @@ func pyPinned(spec string) string {
// Imports has no project root, so Deps remembers what an installed virtualenv
// says each distribution provides (top_level.txt) for Imports to prefer, and
// the entry points and requirements it declares (entry_points.txt, METADATA)
-// for a tidy-up.
+// for the first PR.
var (
pyTopLevel sync.Map // dist -> []string
pyPoints sync.Map // dist -> pyEntryPoints
@@ -728,8 +728,8 @@ func (py python) Bump(ctx context.Context, root string, d core.Dep, to, toName s
targeted := !edited && !exact
line := pyLockLine(ctx, root, m, cmp.Or(toName, d.Name), to, targeted)
// Poetry's update takes the newest release the ranges allow, not the
- // one tend chose; what a targeted run locked is checked for every lock
- // that can be read back.
+ // one tend chose; what a targeted run locked is checked against it, as
+ // a floor, for every lock that can be read back.
check := targeted && slices.Contains([]string{"uv.lock", "poetry.lock"}, path.Base(m.Lock))
var before map[string]bool
if check {
@@ -746,12 +746,14 @@ func (py python) Bump(ctx context.Context, root string, d core.Dep, to, toName s
if err := runIn(ctx, root, path.Dir(m.Path), nil, line); err != nil {
return nil, err
}
+ landed := ""
if check {
- if err := lockedTo(root, m.Lock, core.Pip, d.Name, to, before); err != nil {
+ var err error
+ if landed, err = lockedTo(root, m.Lock, core.Pip, d.Name, to, before); err != nil {
return nil, errors.Join(err, snap.restore(root))
}
}
- return &core.Bump{Files: snap.changed(root), Locked: true}, nil
+ return &core.Bump{Files: snap.changed(root), Locked: true, Landed: landed}, nil
}
// lockAt locks name at exactly to with Poetry, which takes no version on the
@@ -896,16 +898,14 @@ func poetryLock(ctx context.Context, root, dir string) string {
func (python) Commands(root string, m core.Manifest) core.Commands {
dir := path.Dir(m.Path)
- var install, py string
+ install, py := "python3 -m venv .venv && .venv/bin/pip install "+pyPipArgs(root, m), pyRun(m)
switch m.Tool {
case "uv":
- install, py = "uv sync --frozen", "uv run python"
+ install = "uv sync --frozen"
case "poetry":
- install, py = "poetry install", "poetry run python"
+ install = "poetry install"
case "pipenv":
- install, py = "pipenv sync --dev", "pipenv run python"
- default:
- install, py = "python3 -m venv .venv && .venv/bin/pip install "+pyPipArgs(root, m), ".venv/bin/python"
+ install = "pipenv sync --dev"
}
c := core.Commands{Install: []string{inDir(dir, install)}}
if t := pyTestLine(root, m); t != "" {
@@ -914,6 +914,19 @@ func (python) Commands(root string, m core.Manifest) core.Commands {
return c
}
+// pyRun is the interpreter a manifest's tool runs the project's code with.
+func pyRun(m core.Manifest) string {
+ switch m.Tool {
+ case "uv":
+ return "uv run python"
+ case "poetry":
+ return "poetry run python"
+ case "pipenv":
+ return "pipenv run python"
+ }
+ return ".venv/bin/python"
+}
+
func pyPipArgs(root string, m core.Manifest) string {
dir := path.Dir(m.Path)
if path.Base(m.Path) == "pyproject.toml" {
diff --git a/internal/eco/python_test.go b/internal/eco/python_test.go
index 3e71097..059576e 100644
--- a/internal/eco/python_test.go
+++ b/internal/eco/python_test.go
@@ -246,15 +246,24 @@ func TestPythonBumpCommands(t *testing.T) {
}
}
-// poetry update takes the newest release the ranges allow; landing anything
-// but the chosen one fails the bump and leaves the files as they were.
+// poetry update takes the newest release the ranges allow. A later release
+// of the same major is taken and named; one past it fails the bump and
+// leaves the files as they were.
func TestPoetryTargetedLockChecked(t *testing.T) {
lockTool(t, "poetry", "2024.8.30", "2024.12.14")
root := copyTestdata(t, "python/projects")
d := depIn(t, python{}, root, "poetry/pyproject.toml", "certifi", false)
+ res, err := python{}.Bump(context.Background(), root, d, "2024.9.1", "")
+ if err != nil || res.Landed != "2024.12.14" {
+ t.Fatalf("bump = %+v, %v", res, err)
+ }
+
+ lockTool(t, "poetry", "2024.8.30", "2025.1.31")
+ root = copyTestdata(t, "python/projects")
+ d = depIn(t, python{}, root, "poetry/pyproject.toml", "certifi", false)
before := treeSnapshot(t, root)
- _, err := python{}.Bump(context.Background(), root, d, "2024.9.1", "")
- if err == nil || !strings.Contains(err.Error(), "locked certifi at 2024.12.14, not 2024.9.1") {
+ _, err = python{}.Bump(context.Background(), root, d, "2024.9.1", "")
+ if err == nil || !strings.Contains(err.Error(), "locked certifi at 2025.1.31, not 2024.9.1 or a later 2024.x") {
t.Fatalf("err = %v", err)
}
if !reflect.DeepEqual(before, treeSnapshot(t, root)) {
diff --git a/internal/eco/suite.go b/internal/eco/suite.go
new file mode 100644
index 0000000..c19683c
--- /dev/null
+++ b/internal/eco/suite.go
@@ -0,0 +1,195 @@
+package eco
+
+import (
+ "path"
+ "slices"
+ "strconv"
+ "strings"
+
+ "github.com/mohsensc/tend-cli/internal/core"
+ "github.com/mohsensc/tend-cli/internal/scan"
+)
+
+var (
+ _ core.Baseliner = npm{}
+ _ core.Baseliner = python{}
+ _ core.Baseliner = gomod{}
+)
+
+// smokeMax is how many modules a smoke test loads at most.
+const smokeMax = 50
+
+// unloaded hold code no smoke test should load: dependencies, build output
+// and what a build bundles from.
+var unloaded = []string{"node_modules", "vendor", "dist", "build", "out", "coverage", "public", "static", "assets", "docs", "examples", "fixtures", "migrations", ".venv", "venv", "site-packages", "__pycache__", "scripts", "bin"}
+
+// modules lists the code files under dir with one of exts that a smoke test
+// may load: not tests, not under unloaded, not minified, not a tool's config
+// file, and with a plain name. Paths are relative to dir.
+func modules(root, dir string, exts []string) []string {
+ files, err := Files(root)
+ if err != nil {
+ return nil
+ }
+ var res []string
+ for _, f := range files {
+ rel := f
+ if dir != "." {
+ var ok bool
+ if rel, ok = strings.CutPrefix(f, dir+"/"); !ok {
+ continue
+ }
+ }
+ base := path.Base(rel)
+ switch {
+ case !slices.Contains(exts, path.Ext(rel)), scan.IsTest(rel), strings.ContainsAny(rel, " '\"$`\\"),
+ strings.HasPrefix(base, "."), strings.Contains(base, ".min."), strings.Contains(base, ".config."),
+ strings.HasPrefix(base, "Gruntfile"), strings.HasPrefix(base, "gulpfile"), base == "setup.py", base == "conftest.py", base == "manage.py":
+ continue
+ }
+ if slices.ContainsFunc(strings.Split(path.Dir(rel), "/"), func(d string) bool { return slices.Contains(unloaded, d) }) {
+ continue
+ }
+ res = append(res, rel)
+ if len(res) == smokeMax {
+ break
+ }
+ }
+ return res
+}
+
+// Suite puts generated tests under test/tend next to the manifest, written
+// for node --test, which every maintained Node runs without a dependency.
+// A TypeScript project with no build script gets a typecheck too.
+func (npm) Suite(root string, m core.Manifest) *core.Suite {
+ dir := path.Dir(m.Path)
+ su := &core.Suite{
+ Lang: "JavaScript in CommonJS, run by `node --test`, with node:test and node:assert",
+ Smoke: path.Join(dir, "test/tend/smoke.js"),
+ Tests: path.Join(dir, "test/tend/characterization.js"),
+ Modules: modules(root, dir, []string{".js", ".cjs", ".mjs"}),
+ Load: func(mod string) string {
+ return inDir(dir, "node -e "+shArg(`import(require('node:url').pathToFileURL(require('node:path').resolve(`+strconv.Quote(mod)+`)).href).then(() => process.exit(0), (e) => { process.stderr.write(String(e && e.stack || e)); process.exit(1) })`))
+ },
+ Code: smokeJS,
+ Run: func(files []string) string {
+ return inDir(dir, "node --test "+shArgs(under(dir, files)))
+ },
+ }
+ info := npmReadInfo(root, m.Path)
+ if s, _ := info.Scripts["build"].(string); s == "" && onDisk(path.Join(root, dir), "tsconfig.json") {
+ su.Checks = []string{inDir(dir, "npx --no-install tsc --noEmit")}
+ }
+ return su
+}
+
+func smokeJS(mods []string) string {
+ var list strings.Builder
+ for _, m := range mods {
+ list.WriteString(" '" + m + "',\n")
+ }
+ return `'use strict'
+
+const test = require('node:test')
+const assert = require('node:assert')
+const { spawnSync } = require('node:child_process')
+const path = require('node:path')
+const { pathToFileURL } = require('node:url')
+
+const root = path.join(__dirname, '..', '..')
+
+const modules = [
+` + list.String() + `]
+
+for (const m of modules) {
+ test('loads ' + m, () => {
+ const url = pathToFileURL(path.join(root, m)).href
+ const code = 'import(' + JSON.stringify(url) + ').then(() => process.exit(0), (e) => { process.stderr.write(String(e && e.stack || e)); process.exit(1) })'
+ const res = spawnSync(process.execPath, ['-e', code], { cwd: root, encoding: 'utf8', timeout: 30000 })
+ assert.strictEqual(res.status, 0, res.stderr)
+ })
+}
+`
+}
+
+// Suite puts generated tests under tests/tend next to the manifest, as
+// unittest cases, which pytest collects as well.
+func (python) Suite(root string, m core.Manifest) *core.Suite {
+ dir, py := path.Dir(m.Path), pyRun(m)
+ return &core.Suite{
+ Lang: "Python, as unittest test cases",
+ Smoke: path.Join(dir, "tests/tend/test_smoke.py"),
+ Tests: path.Join(dir, "tests/tend/test_characterization.py"),
+ Modules: pyDotted(modules(root, dir, []string{".py"})),
+ Load: func(mod string) string {
+ return inDir(dir, py+" -c "+shArg("import "+mod))
+ },
+ Code: smokePy,
+ Run: func(files []string) string {
+ return inDir(dir, py+" -m unittest discover -s tests/tend -t .")
+ },
+ }
+}
+
+// pyDotted names the modules files are, by their dotted paths: a package's
+// __init__.py is the package.
+func pyDotted(files []string) []string {
+ var res []string
+ for _, f := range files {
+ m := strings.TrimSuffix(strings.TrimSuffix(f, ".py"), "/__init__")
+ if strings.ContainsAny(m, ".-") {
+ continue
+ }
+ res = append(res, strings.ReplaceAll(m, "/", "."))
+ }
+ return res
+}
+
+func smokePy(mods []string) string {
+ var list strings.Builder
+ for _, m := range mods {
+ list.WriteString(" " + strconv.Quote(m) + ",\n")
+ }
+ return `import os
+import subprocess
+import sys
+import unittest
+
+ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+MODULES = [
+` + list.String() + `]
+
+
+class Smoke(unittest.TestCase):
+ def test_modules_load(self):
+ for mod in MODULES:
+ with self.subTest(mod=mod):
+ res = subprocess.run([sys.executable, "-c", "import " + mod], cwd=ROOT, capture_output=True, text=True, timeout=60)
+ self.assertEqual(res.returncode, 0, res.stderr)
+`
+}
+
+// Suite puts characterization tests in the module's root package; go test
+// runs them and the build already loads every package, so there is neither
+// a smoke test nor a line to add.
+func (gomod) Suite(root string, m core.Manifest) *core.Suite {
+ dir := path.Dir(m.Path)
+ return &core.Suite{
+ Lang: "Go, as tests in the package of the files they cover, named tend_characterization_test.go in that package's directory",
+ Tests: path.Join(dir, "tend_characterization_test.go"),
+ Run: func([]string) string { return "" },
+ }
+}
+
+// under makes repo-relative paths relative to dir.
+func under(dir string, files []string) []string {
+ var res []string
+ for _, f := range files {
+ if dir != "." {
+ f = strings.TrimPrefix(f, dir+"/")
+ }
+ res = append(res, f)
+ }
+ return res
+}
diff --git a/internal/eco/toolchain.go b/internal/eco/toolchain.go
index d7af9b8..405182f 100644
--- a/internal/eco/toolchain.go
+++ b/internal/eco/toolchain.go
@@ -357,6 +357,6 @@ func lockEngines(p, from, to string) error {
func (toolchain) Commands(root string, m core.Manifest) core.Commands { return core.Commands{} }
-func (toolchain) Traits() core.Traits { return core.Traits{} }
+func (toolchain) Traits() core.Traits { return core.Traits{Tooling: true} }
func (toolchain) Imports(d core.Dep) []string { return nil }
diff --git a/internal/eco/unused.go b/internal/eco/unused.go
index 0a0caff..9414ac1 100644
--- a/internal/eco/unused.go
+++ b/internal/eco/unused.go
@@ -28,9 +28,9 @@ var (
)
// Unused sorts the direct dependencies no code imports into those nothing in
-// the project uses, which a tidy-up removes, and those that only look unused,
-// which it names and leaves alone, each with why. keep holds a dependency
-// back from both, as an ignore entry in tend.yml does.
+// the project uses, which the first PR removes, and those that only look
+// unused, which it names and leaves alone, each with why. keep holds a
+// dependency back from both, as an ignore entry in tend.yml does.
func Unused(inv *core.Inventory, keep func(core.Dep) bool) ([]core.Dep, []core.Aside, error) {
if inv.Index == nil {
return nil, nil, nil
diff --git a/internal/patch/agent.go b/internal/patch/agent.go
index 197aa70..8b83a92 100644
--- a/internal/patch/agent.go
+++ b/internal/patch/agent.go
@@ -53,6 +53,13 @@ var agentTools = []model.Tool{
Params: schema(map[string]any{"summary": str("what was changed, in a sentence")}, "summary")},
}
+// benchTools are the tools of a characterization: write in place of nothing
+// but the one test file to edit.
+var benchTools = append([]model.Tool{
+ {Name: "write", Description: "Create the test file, or replace all of it.",
+ Params: schema(map[string]any{"path": str("repo-relative path of the test file"), "content": str("the whole file")}, "path", "content")},
+}, agentTools...)
+
// session is one agent run over a worktree: what it may touch and what it did.
type session struct {
t *tree
@@ -64,6 +71,7 @@ type session struct {
edited []string
results []string // pass or fail of each run, in order
log *os.File
+ bench string // the one test file a characterization may write, "" for a migration
}
// work hands the remaining sites to a model that calls tools. It ends when the
@@ -71,6 +79,21 @@ type session struct {
// out; the model saying it is done is not enough.
func work(ctx context.Context, t *tree, in job, o Options, p *core.Patch, a model.Agent) error {
s := &session{t: t, in: in, o: o, ctx: ctx, counts: map[string]int{}}
+ brief, err := s.brief()
+ if err != nil {
+ return err
+ }
+ if err := s.loop(ctx, a, agentSystem, brief, agentTools, p); err != nil {
+ return err
+ }
+ p.Applied = append(p.Applied, "the model edited "+strings.Join(s.edited, ", "))
+ return nil
+}
+
+// loop runs the conversation until the model's done passes or the budget
+// runs out, logging each tool call to the transcript.
+func (s *session) loop(ctx context.Context, a model.Agent, system, brief string, tools []model.Tool, p *core.Patch) error {
+ o := s.o
if o.Transcript != "" {
if err := os.MkdirAll(filepath.Dir(o.Transcript), 0o755); err == nil {
s.log, _ = os.Create(o.Transcript)
@@ -79,10 +102,6 @@ func work(ctx context.Context, t *tree, in job, o Options, p *core.Patch, a mode
if s.log != nil {
defer s.log.Close()
}
- brief, err := s.brief()
- if err != nil {
- return err
- }
turns := []model.Turn{{Role: "user", Text: brief}}
used := 0
for {
@@ -92,7 +111,7 @@ func work(ctx context.Context, t *tree, in job, o Options, p *core.Patch, a mode
if o.Tokens > 0 && used >= o.Tokens {
return fmt.Errorf("the model spent its %d tokens (%s)", o.Tokens, s.summary())
}
- r, err := a.Chat(ctx, agentSystem, turns, agentTools)
+ r, err := a.Chat(ctx, system, turns, tools)
if err != nil {
return fmt.Errorf("%w (%s)", err, s.summary())
}
@@ -111,7 +130,6 @@ func work(ctx context.Context, t *tree, in job, o Options, p *core.Patch, a mode
if finished {
p.Model = true
p.Edited = s.edited
- p.Applied = append(p.Applied, "the model edited "+strings.Join(s.edited, ", "))
p.Note = s.summary()
o.logf("the model finished in %d steps", s.steps)
return nil
@@ -142,8 +160,8 @@ func (s *session) brief() (string, error) {
func (s *session) call(c model.ToolCall) (string, bool) {
s.counts[c.Name]++
var args struct {
- Path, Pattern, Glob, Old, New, Name, Summary string
- From, To int
+ Path, Pattern, Glob, Old, New, Name, Summary, Content string
+ From, To int
}
if err := json.Unmarshal(c.Args, &args); err != nil {
return "error: the arguments are not a JSON object: " + err.Error(), false
@@ -155,6 +173,11 @@ func (s *session) call(c model.ToolCall) (string, bool) {
return s.grep(args.Pattern, args.Glob), false
case "edit":
return s.edit(args.Path, args.Old, args.New), false
+ case "write":
+ if s.bench == "" {
+ break
+ }
+ return s.write(args.Path, args.Content), false
case "run":
cmds, ok := s.commands(args.Name)
if !ok {
@@ -277,7 +300,7 @@ func (s *session) edit(p, old, now string) string {
if err != nil {
return "error: " + err.Error()
}
- if !slices.Contains(s.in.allowed, rel) && !scan.IsTest(rel) {
+ if !slices.Contains(s.in.allowed, rel) && (s.bench != "" || !scan.IsTest(rel)) {
return "error: " + rel + " is not one of the files this change explains; edit the files listed at the start, or tests"
}
b := s.t.read(rel)
@@ -302,6 +325,25 @@ func (s *session) edit(p, old, now string) string {
return "edited " + rel
}
+// write creates the test file a characterization writes, or replaces it.
+func (s *session) write(p, content string) string {
+ rel, err := s.inside(p)
+ if err != nil {
+ return "error: " + err.Error()
+ }
+ if rel != s.bench {
+ return "error: write only creates " + s.bench
+ }
+ if err := place(s.t.wt, rel, content); err != nil {
+ return "error: " + err.Error()
+ }
+ delete(s.t.files, rel)
+ if !slices.Contains(s.edited, rel) {
+ s.edited = append(s.edited, rel)
+ }
+ return "wrote " + rel
+}
+
func (s *session) commands(name string) (core.Commands, bool) {
all := s.o.Commands
switch name {
@@ -342,7 +384,7 @@ func (s *session) run(cmds core.Commands) string {
// edited and how its runs of the commands went.
func (s *session) summary() string {
var parts []string
- for _, tool := range []string{"read", "grep", "edit", "run"} {
+ for _, tool := range []string{"read", "grep", "edit", "write", "run"} {
if n := s.counts[tool]; n > 0 {
parts = append(parts, plural(n, tool))
}
diff --git a/internal/patch/apply.go b/internal/patch/apply.go
index c409d7b..65987f7 100644
--- a/internal/patch/apply.go
+++ b/internal/patch/apply.go
@@ -22,7 +22,7 @@ type Options struct {
Option int // 0 = tend's choice; N = maintainer picked option N
Proven bool // the project's own build and tests will run on the result
// Strict makes a bump that would leave call sites for the proof to judge
- // a decision instead: a tidy-up carries only moves that are made.
+ // a decision instead: the first PR carries only changes that are made.
Strict bool
// Bumped is called once the deps are bumped, before codemods or a model
// touch the code.
@@ -168,7 +168,7 @@ func sites(n int) string {
// stays reports whether opt keeps the version in use: the way off a deprecation
// that is no way off at all.
func stays(ch *core.Change, opt *core.Option) bool {
- return opt.ToName == "" && opt.Codemod == nil && opt.To != "" && opt.To == from(ch.Deps[0])
+ return opt.Stay || opt.ToName == "" && opt.Codemod == nil && opt.To != "" && opt.To == from(ch.Deps[0])
}
// reusable reports whether idx still describes the worktree: the bump only moved
@@ -181,8 +181,12 @@ func reusable(idx core.ScanIndex, bumped []string) bool {
return !slices.ContainsFunc(bumped, func(f string) bool { return slices.Contains(files, f) })
}
-// choose returns the option to apply: the maintainer's pick, else the first safe one.
+// choose returns the option to apply: the maintainer's pick, else the one a
+// run took by its own rule, else the first safe one.
func choose(ch *core.Change, n int) (*core.Option, error) {
+ if n == 0 && ch.Choice != nil {
+ n = ch.Choice.N
+ }
if n > 0 {
if n > len(ch.Options) {
return nil, fmt.Errorf("patch: option %d of %d", n, len(ch.Options))
@@ -197,6 +201,17 @@ func choose(ch *core.Change, n int) (*core.Option, error) {
return nil, nil
}
+// Bare reports whether making ch is its bump and nothing more: there is a
+// release to move to, no option to apply, and no call site the bump could
+// leave for codemods or a model. Such a change is made again next to others
+// without being made on its own first.
+func Bare(ch *core.Change) bool {
+ if ch.API != nil || len(ch.Options) > 0 || ch.To == "" && ch.ToName == "" {
+ return false
+ }
+ return !needsCode(ch, nil) || len(core.Calls(ch)) == 0
+}
+
// needsCode reports whether sites left untouched by the deterministic steps must change.
// A safe option is trusted to be complete; the proof says whether it was.
func needsCode(ch *core.Change, opt *core.Option) bool {
diff --git a/internal/patch/bump.go b/internal/patch/bump.go
index 1164238..864ce60 100644
--- a/internal/patch/bump.go
+++ b/internal/patch/bump.go
@@ -83,8 +83,15 @@ func bump(ctx context.Context, wt string, deps []core.Dep, to, toName string, o
o.logf("bumped %s in %s", d.Name, strings.Join(files, ", "))
line := fmt.Sprintf("bumped %s %s -> %s", d.Name, from(d), to)
- if toName != "" {
+ switch {
+ case toName != "":
line = fmt.Sprintf("swapped %s for %s", d.Name, toName)
+ case b.Landed != "":
+ if p.Landed == nil {
+ p.Landed = map[string]string{}
+ }
+ p.Landed[d.Ecosystem+"/"+d.Name] = b.Landed
+ line = fmt.Sprintf("bumped %s %s -> %s, the newest release from %s its ranges allow", d.Name, from(d), b.Landed, to)
}
if len(files) > 0 {
line += " (" + strings.Join(files, ", ") + ")"
@@ -138,8 +145,8 @@ func from(d core.Dep) string {
}
// landed checks that the lockfile took the move: a direct dep sits at
-// exactly to, the release tend chose and proves; a transitive one has no
-// copy left at the version it moved from.
+// exactly to, the release tend chose and proves; a transitive one, for which
+// to is a floor, has no copy left at the version it moved from.
func landed(e core.Ecosystem, wt string, d core.Dep, to, toName string) error {
deps, err := e.Deps(wt, d.Manifest)
if err != nil {
diff --git a/internal/patch/characterize.go b/internal/patch/characterize.go
new file mode 100644
index 0000000..aa8a73f
--- /dev/null
+++ b/internal/patch/characterize.go
@@ -0,0 +1,166 @@
+package patch
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/mohsensc/tend-cli/internal/core"
+ "github.com/mohsensc/tend-cli/internal/gitx"
+ "github.com/mohsensc/tend-cli/internal/model"
+)
+
+// Bench is what characterization tests are written for: the file they go
+// in, the language they are written in, and the files whose behavior they
+// pin down.
+type Bench struct {
+ Path string
+ Lang string
+ Files []string
+}
+
+const benchRules = `Rules:
+- Write one test file, at the path given, and touch no other file.
+- Test what the files export, or what they serve when they start a server, and assert what the code does today, even where it looks wrong.
+- Never reach the network: stub fetch, HTTP clients and anything else that calls out.
+- Leave nothing running: close servers, clear timers.
+- Do not add comments or prints.`
+
+const benchAgent = `You write characterization tests: tests that pin down what code does today, so that a later change which alters its behavior makes them fail. You work through tools: read and grep to look around, write to create the test file, edit to change it, run to run the tests, and done when they pass.
+
+` + benchRules + `
+- Run the tests before you call done. done runs every command; when one fails you get its output and keep going.`
+
+const benchDiff = `You write characterization tests: tests that pin down what code does today, so that a later change which alters its behavior makes them fail.
+
+` + benchRules + `
+- Reply with the whole test file in one fenced code block, and nothing else.`
+
+// benchFile is how much of each file the prompt shows.
+const benchFile = 300
+
+// Characterize has the model write tests of how b.Files behave now, at
+// b.Path, and stops once the project's commands, which run them, pass on
+// the tree as it is: a model that calls tools runs them as it works; one
+// that does not gets the failure back while attempts remain. o.Prove runs
+// the commands.
+func Characterize(ctx context.Context, wt string, b Bench, o Options) (*core.Patch, error) {
+ if o.Model == nil || o.Prove == nil {
+ return nil, errors.New("characterization tests need a model and the project's commands")
+ }
+ t := &tree{wt: wt}
+ brief := benchBrief(t, b)
+ p := &core.Patch{}
+ if a, ok := o.Model.(model.Agent); ok {
+ s := &session{t: t, o: o, ctx: ctx, counts: map[string]int{}, bench: b.Path, in: job{allowed: []string{b.Path}}}
+ if err := s.loop(ctx, a, benchAgent, brief, benchTools, p); err != nil {
+ return nil, err
+ }
+ } else if err := benchText(ctx, t, b, brief, o, p); err != nil {
+ return nil, err
+ }
+ p.Model = true
+ p.Edited = []string{b.Path}
+ p.Applied = []string{"a model wrote tests of how the code behaves now (" + b.Path + ")"}
+ return p, nil
+}
+
+func benchBrief(t *tree, b Bench) string {
+ var s strings.Builder
+ fmt.Fprintf(&s, "Write characterization tests in %s, in the file %s, for these files, which are about to change:\n", b.Lang, b.Path)
+ for _, f := range b.Files {
+ src := t.read(f)
+ if src == nil {
+ continue
+ }
+ lines := strings.Split(strings.TrimSuffix(string(src), "\n"), "\n")
+ fmt.Fprintf(&s, "\n=== %s\n%s\n", f, strings.Join(lines[:min(len(lines), benchFile)], "\n"))
+ if len(lines) > benchFile {
+ fmt.Fprintf(&s, "(%d more lines)\n", len(lines)-benchFile)
+ }
+ }
+ return s.String()
+}
+
+// benchText asks a model without tools for the whole file, writes it, runs
+// the commands, and sends the failure back while attempts remain.
+func benchText(ctx context.Context, t *tree, b Bench, brief string, o Options, p *core.Patch) error {
+ n := max(o.Attempts, defaultAttempts)
+ retry := ""
+ var fails []string
+ for i := range n {
+ reply, err := o.Model.Complete(ctx, benchDiff, brief+retry)
+ if err != nil {
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ fails = append(fails, fmt.Sprintf("attempt %d: model %s: %v", i+1, o.Model.Name(), err))
+ continue
+ }
+ body := block(strings.ReplaceAll(reply, "\r\n", "\n"))
+ if strings.TrimSpace(body) == "" {
+ fails = append(fails, fmt.Sprintf("attempt %d: the reply holds no code block", i+1))
+ retry = "\n\nYour previous reply held no code block. Reply with the whole test file in one."
+ continue
+ }
+ if err := place(t.wt, b.Path, body); err != nil {
+ return err
+ }
+ // What is staged survives the clean-up after the commands run.
+ if _, err := gitx.Raw(ctx, t.wt, "add", "-A"); err != nil {
+ return err
+ }
+ run, err := o.Prove(ctx, o.Commands)
+ if err != nil {
+ return err
+ }
+ if run.Pass {
+ p.Note = fmt.Sprintf("%d %s", i+1, pick(i+1, "try", "tries"))
+ return nil
+ }
+ st := run.Last()
+ why := "the commands failed"
+ if st != nil {
+ why = fmt.Sprintf("%s exited %d\n%s", st.Cmd, st.Exit, tail(st.Tail, feedbackMax))
+ }
+ o.logf("characterization attempt %d: %s", i+1, strings.SplitN(why, "\n", 2)[0])
+ fails = append(fails, fmt.Sprintf("attempt %d: %s", i+1, strings.SplitN(why, "\n", 2)[0]))
+ retry = "\n\nThe tests you wrote fail on the code as it is, so they do not describe it:\n" + why + "\n\nReply with the whole corrected test file."
+ }
+ return errors.New(strings.Join(fails, "; "))
+}
+
+// block is the first fenced code block of a reply, whatever its language.
+func block(s string) string {
+ lines := strings.Split(s, "\n")
+ for i, ln := range lines {
+ if !strings.HasPrefix(strings.TrimSpace(ln), "```") {
+ continue
+ }
+ for j := i + 1; j < len(lines); j++ {
+ if strings.HasPrefix(strings.TrimSpace(lines[j]), "```") {
+ return strings.Join(lines[i+1:j], "\n")
+ }
+ }
+ }
+ return ""
+}
+
+// place writes a file in the worktree.
+func place(wt, rel, body string) error {
+ p := filepath.Join(wt, filepath.FromSlash(rel))
+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
+ return err
+ }
+ return os.WriteFile(p, []byte(strings.TrimRight(body, "\n")+"\n"), 0o644)
+}
+
+func pick(n int, one, many string) string {
+ if n == 1 {
+ return one
+ }
+ return many
+}
diff --git a/internal/patch/characterize_test.go b/internal/patch/characterize_test.go
new file mode 100644
index 0000000..2ad0f70
--- /dev/null
+++ b/internal/patch/characterize_test.go
@@ -0,0 +1,102 @@
+package patch
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/mohsensc/tend-cli/internal/core"
+ "github.com/mohsensc/tend-cli/internal/model"
+)
+
+// bench runs pass in order and says whether the tests file was there.
+type bench struct {
+ dir string
+ pass []bool
+ had []bool
+}
+
+func (b *bench) prove(ctx context.Context, cmds core.Commands) (*core.Run, error) {
+ _, err := os.Stat(filepath.Join(b.dir, "test", "tend", "characterization.js"))
+ b.had = append(b.had, err == nil)
+ ok := len(b.pass) > 0 && b.pass[0]
+ if len(b.pass) > 0 {
+ b.pass = b.pass[1:]
+ }
+ st := core.Step{Cmd: "node --test test/tend/characterization.js"}
+ if !ok {
+ st.Exit, st.Tail = 1, "AssertionError: expected 'ok', got 'OK'"
+ }
+ return &core.Run{Pass: ok, Steps: []core.Step{st}}, nil
+}
+
+var shop = Bench{Path: "test/tend/characterization.js", Lang: "JavaScript", Files: []string{"src/app.js"}}
+
+// A model without tools writes the whole file; when the tests fail on the
+// code as it is, the failure goes back and the next file replaces it.
+func TestCharacterizeText(t *testing.T) {
+ dir := repo(t, map[string]string{"src/app.js": "exports.health = () => 'OK'\n"})
+ b := &bench{dir: dir, pass: []bool{false, true}}
+ m := &model.Script{Replies: []string{
+ "```js\nconst assert = require('node:assert')\nassert.strictEqual(require('../../src/app').health(), 'ok')\n```",
+ "Here it is.\n\n```js\nconst assert = require('node:assert')\nassert.strictEqual(require('../../src/app').health(), 'OK')\n```\n",
+ }}
+ pt, err := Characterize(context.Background(), dir, shop, Options{Model: m, Prove: b.prove, Attempts: 2})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !pt.Model || pt.Edited[0] != shop.Path || pt.Applied[0] != "a model wrote tests of how the code behaves now (test/tend/characterization.js)" || pt.Note != "2 tries" {
+ t.Errorf("patch = %+v", pt)
+ }
+ if got := readFile(t, dir, shop.Path); !strings.Contains(got, "'OK')") {
+ t.Errorf("the file kept is not the one that passed:\n%s", got)
+ }
+ if !strings.Contains(m.Calls[0].Prompt, "=== src/app.js\nexports.health = () => 'OK'") {
+ t.Errorf("the prompt does not show the file:\n%s", m.Calls[0].Prompt)
+ }
+ if !strings.Contains(m.Calls[1].Prompt, "fail on the code as it is") || !strings.Contains(m.Calls[1].Prompt, "expected 'ok', got 'OK'") {
+ t.Errorf("the failure was not sent back:\n%s", m.Calls[1].Prompt)
+ }
+ if strings.Contains(run(t, dir, "status", "--porcelain"), "??") {
+ t.Error("the tests file is not staged, so the clean-up after a run would take it")
+ }
+
+ b = &bench{dir: dir, pass: []bool{false, false}}
+ m = &model.Script{Replies: []string{"```js\nx\n```", "no code at all"}}
+ if _, err := Characterize(context.Background(), dir, shop, Options{Model: m, Prove: b.prove}); err == nil || !strings.Contains(err.Error(), "attempt 2: the reply holds no code block") {
+ t.Errorf("err = %v", err)
+ }
+}
+
+// A model with tools writes the one file it may, runs the tests, and is done
+// once they pass; it may not edit the code under test.
+func TestCharacterizeAgent(t *testing.T) {
+ dir := repo(t, map[string]string{"src/app.js": "exports.health = () => 'OK'\n"})
+ b := &bench{dir: dir, pass: []bool{true}}
+ m := &model.Steps{Replies: []model.Reply{
+ calls(call("1", "edit", map[string]any{"path": "src/app.js", "old": "'OK'", "new": "'ok'"})),
+ calls(call("2", "write", map[string]any{"path": "src/other.test.js", "content": "x"})),
+ calls(call("3", "write", map[string]any{"path": shop.Path, "content": "require('node:assert')\n"})),
+ calls(call("4", "done", map[string]any{"summary": "pinned health"})),
+ }}
+ pt, err := Characterize(context.Background(), dir, shop, Options{Model: m, Prove: b.prove, Commands: core.Commands{Test: []string{"node --test"}}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if pt.Note != "4 steps: 1 edit, 2 writes; the commands passed" || len(b.had) != 1 || !b.had[0] {
+ t.Errorf("patch %+v, runs saw the file %v", pt, b.had)
+ }
+ if got := readFile(t, dir, "src/app.js"); got != "exports.health = () => 'OK'\n" {
+ t.Errorf("the code under test was edited:\n%s", got)
+ }
+ if _, err := os.Stat(filepath.Join(dir, "src", "other.test.js")); err == nil {
+ t.Error("a second file was written")
+ }
+ for i, want := range []string{"is not one of the files this change explains", "write only creates test/tend/characterization.js"} {
+ if got := m.Chats[i+1][len(m.Chats[i+1])-1].Text; !strings.Contains(got, want) {
+ t.Errorf("turn %d answered %q, want %q", i+1, got, want)
+ }
+ }
+}
diff --git a/internal/patch/pin.go b/internal/patch/pin.go
index df8fd7e..174d0a9 100644
--- a/internal/patch/pin.go
+++ b/internal/patch/pin.go
@@ -2,16 +2,19 @@ package patch
import (
"bytes"
+ "context"
"errors"
"fmt"
"os"
"path/filepath"
+ "slices"
"strings"
"gopkg.in/yaml.v3"
"github.com/mohsensc/tend-cli/internal/config"
"github.com/mohsensc/tend-cli/internal/core"
+ "github.com/mohsensc/tend-cli/internal/gitx"
)
// pin keeps d where it is by telling tend.yml to ignore to and everything
@@ -123,3 +126,92 @@ func blankOrComment(l string) bool {
t := strings.TrimSpace(l)
return t == "" || strings.HasPrefix(t, "#")
}
+
+// Test adds line to verify.test in the worktree's tend.yml, after tests,
+// the test lines the project runs now, since a list there replaces what
+// tend detects. The file is created when the project has none. It returns
+// the file it wrote.
+func Test(wt string, tests []string, line string) (string, error) {
+ name := "tend.yml"
+ if !exists(filepath.Join(wt, name)) && exists(filepath.Join(wt, ".github", "tend.yml")) {
+ name = ".github/tend.yml"
+ }
+ p := filepath.Join(wt, filepath.FromSlash(name))
+ src, err := os.ReadFile(p)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ return "", err
+ }
+ out, err := addTest(src, tests, line)
+ if err != nil {
+ return "", fmt.Errorf("%s: %w", name, err)
+ }
+ if _, err := config.Parse(out); err != nil {
+ return "", fmt.Errorf("%s: the test line would break it: %w", name, err)
+ }
+ return name, os.WriteFile(p, out, 0o644)
+}
+
+// addTest puts line at the end of verify.test, writing the list out from
+// tests when tend.yml sets none, and leaves every other line as it was.
+func addTest(src []byte, tests []string, line string) ([]byte, error) {
+ lines := strings.SplitAfter(string(src), "\n")
+ if len(lines) > 0 && lines[len(lines)-1] == "" {
+ lines = lines[:len(lines)-1]
+ }
+ if n := len(lines); n > 0 && !strings.HasSuffix(lines[n-1], "\n") {
+ lines[n-1] += "\n"
+ }
+ items := func(indent int, all []string) []string {
+ var res []string
+ for _, l := range all {
+ v, _ := yaml.Marshal(l)
+ res = append(res, strings.Repeat(" ", indent)+"- "+strings.TrimSpace(string(v))+"\n")
+ }
+ return res
+ }
+ block := func(indent int) []string {
+ return append([]string{strings.Repeat(" ", indent) + "test:\n"}, items(indent+2, append(slices.Clone(tests), line))...)
+ }
+ var doc yaml.Node
+ if err := yaml.Unmarshal(src, &doc); err != nil {
+ return nil, err
+ }
+ if len(doc.Content) == 0 {
+ return []byte(strings.Join(append(append(lines, "verify:\n"), block(2)...), "")), nil
+ }
+ top := doc.Content[0]
+ if top.Kind != yaml.MappingNode {
+ return nil, errors.New("not a mapping")
+ }
+ for i := 0; i+1 < len(top.Content); i += 2 {
+ key, val := top.Content[i], top.Content[i+1]
+ if key.Value != "verify" {
+ continue
+ }
+ if val.Kind != yaml.MappingNode || val.Style&yaml.FlowStyle != 0 || len(val.Content) == 0 {
+ return nil, errors.New("verify is written inline; add the test line by hand")
+ }
+ for j := 0; j+1 < len(val.Content); j += 2 {
+ k, v := val.Content[j], val.Content[j+1]
+ if k.Value != "test" {
+ continue
+ }
+ if v.Kind != yaml.SequenceNode || v.Style&yaml.FlowStyle != 0 || len(v.Content) == 0 {
+ return nil, errors.New("verify.test is written inline; add the test line by hand")
+ }
+ last := v.Content[len(v.Content)-1]
+ return join(lines, last.Line, items(last.Column-3, []string{line})), nil
+ }
+ return join(lines, key.Line, block(val.Content[0].Column-1)), nil
+ }
+ return []byte(strings.Join(append(append(lines, "verify:\n"), block(2)...), "")), nil
+}
+
+// Put applies a diff tend made earlier to the worktree, such as the test
+// baseline a catch-up PR adds before anything else.
+func Put(ctx context.Context, wt, diff string) error {
+ if _, err := (gitx.Cmd{Dir: wt, Stdin: diff}).Run(ctx, "apply", "--whitespace=nowarn", "-"); err != nil {
+ return fmt.Errorf("patch: %w", err)
+ }
+ return nil
+}
diff --git a/internal/patch/pin_test.go b/internal/patch/pin_test.go
index 9b8198f..99cd9d1 100644
--- a/internal/patch/pin_test.go
+++ b/internal/patch/pin_test.go
@@ -91,3 +91,40 @@ func TestPinWholePackage(t *testing.T) {
t.Errorf("tend.yml:\n%s", got)
}
}
+
+// The baseline's line goes after the project's own test lines, into the
+// list tend.yml has or a new one, and every other line stays.
+func TestAddTest(t *testing.T) {
+ line := "node --test test/tend/smoke.js"
+ tests := []struct {
+ name, in, want string
+ own []string
+ }{
+ {"no file", "", "verify:\n test:\n - node --test test/tend/smoke.js\n", nil},
+ {"own lines", "cooldown: 5d\n", "cooldown: 5d\nverify:\n test:\n - npm test\n - node --test test/tend/smoke.js\n", []string{"npm test"}},
+ {"verify without test", "verify:\n timeout: 30m\n# done\n", "verify:\n test:\n - node --test test/tend/smoke.js\n timeout: 30m\n# done\n", nil},
+ {"a test list", "verify:\n test:\n - npm test\n timeout: 30m\n", "verify:\n test:\n - npm test\n - node --test test/tend/smoke.js\n timeout: 30m\n", []string{"npm test"}},
+ {"a line that needs quotes", "", "verify:\n test:\n - '- node --test x.js'\n", nil},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ l := line
+ if tt.name == "a line that needs quotes" {
+ l = "- node --test x.js"
+ }
+ got, err := addTest([]byte(tt.in), tt.own, l)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(got) != tt.want {
+ t.Errorf("got\n%s\nwant\n%s", got, tt.want)
+ }
+ if _, err := config.Parse(got); err != nil {
+ t.Errorf("does not parse: %v", err)
+ }
+ })
+ }
+ if _, err := addTest([]byte("verify: {test: [npm test]}\n"), nil, line); err == nil {
+ t.Error("an inline verify was rewritten")
+ }
+}
diff --git a/internal/patch/remove.go b/internal/patch/remove.go
index 0c11991..cf9635c 100644
--- a/internal/patch/remove.go
+++ b/internal/patch/remove.go
@@ -57,11 +57,11 @@ func Remove(ctx context.Context, wt string, deps []core.Dep, o Options, p *core.
return nil
}
-// Redo makes ch's move on wt again: the bump through the native tool, then
-// code, the edits its first making put on top of the bump, as a diff. It is
-// how a tidy-up rebuilds a move next to other parts without asking a model
-// a second time.
-func Redo(ctx context.Context, wt string, ch *core.Change, code string, o Options) error {
+// Redo makes ch on wt again: the bump through the native tool, then code,
+// the edits its first making put on top of the bump, as a diff, and says
+// what it did in p. It is how tend's first PR builds a change next to the
+// others without asking a model a second time.
+func Redo(ctx context.Context, wt string, ch *core.Change, code string, o Options, p *core.Patch) error {
opt, err := choose(ch, o.Option)
if err != nil {
return err
@@ -70,7 +70,7 @@ func Redo(ctx context.Context, wt string, ch *core.Change, code string, o Option
if opt != nil {
to, toName = cmp.Or(opt.To, to), cmp.Or(opt.ToName, toName)
}
- if _, err := bump(ctx, wt, ch.Deps, to, toName, o, &core.Patch{}); err != nil {
+ if _, err := bump(ctx, wt, ch.Deps, to, toName, o, p); err != nil {
return err
}
if code == "" {
diff --git a/internal/patch/remove_test.go b/internal/patch/remove_test.go
index b38dd05..544b711 100644
--- a/internal/patch/remove_test.go
+++ b/internal/patch/remove_test.go
@@ -102,7 +102,7 @@ func TestRedo(t *testing.T) {
t.Fatal("the worktree is not back on its base")
}
- if err := Redo(context.Background(), f.dir, f.ch, code, f.opts(nil)); err != nil {
+ if err := Redo(context.Background(), f.dir, f.ch, code, f.opts(nil), &core.Patch{}); err != nil {
t.Fatal(err)
}
if !strings.Contains(readFile(t, f.dir, "package.json"), `"^2.0.0"`) || !strings.Contains(readFile(t, f.dir, "src/billing.js"), "paymentIntents") {
@@ -111,7 +111,7 @@ func TestRedo(t *testing.T) {
run(t, f.dir, "reset", "-q", "--hard", "HEAD")
writeFile(t, f.dir, "src/billing.js", "// rewritten since\n")
- if err := Redo(context.Background(), f.dir, f.ch, code, f.opts(nil)); err == nil || !strings.Contains(err.Error(), "no longer apply") {
+ if err := Redo(context.Background(), f.dir, f.ch, code, f.opts(nil), &core.Patch{}); err == nil || !strings.Contains(err.Error(), "no longer apply") {
t.Errorf("redo onto a file that moved on: %v", err)
}
}
diff --git a/internal/plan/choose.go b/internal/plan/choose.go
new file mode 100644
index 0000000..936873e
--- /dev/null
+++ b/internal/plan/choose.go
@@ -0,0 +1,56 @@
+package plan
+
+import (
+ "slices"
+
+ "github.com/mohsensc/tend-cli/internal/core"
+)
+
+// tries is how many options tend makes and proves on its own before it
+// stays put.
+const tries = 3
+
+// Try is an option tend tries on its own, and the rule that put it where
+// it is in the order.
+type Try struct {
+ N int // 1-based, into the change's Options
+ Why string
+}
+
+// Ranked lists the options tend tries on its own for a change, in order:
+// only those that move somewhere, a replacement only when it has a release
+// to move to, one the project already depends on first, then in the order
+// the options come, which for a replacement is the catalog's: recommended
+// first, then by how widely each is used. Staying put is never tried; it is
+// what happens when none of these is proven.
+func Ranked(ch *core.Change, deps []core.Dep) []Try {
+ var res []Try
+ had := func(o core.Option) bool {
+ return o.ToName != "" && slices.ContainsFunc(deps, func(d core.Dep) bool { return d.Direct && d.Name == o.ToName })
+ }
+ rec := slices.IndexFunc(ch.Options, func(o core.Option) bool { return o.ToName != "" })
+ for i, o := range ch.Options {
+ var why string
+ switch {
+ case o.Stay, o.ToName != "" && o.To == "":
+ continue
+ case had(o):
+ why = "the project already depends on " + o.ToName
+ case i == rec:
+ why = "the catalog's recommended replacement"
+ case o.ToName != "":
+ why = "the next replacement in the catalog's order"
+ case o.Codemod != nil:
+ why = "the rename the deprecation notice names"
+ case o.To != "" && len(ch.Deps) > 0 && o.To != Current(ch.Deps[0]):
+ why = "a release past the deprecated one"
+ default:
+ continue
+ }
+ res = append(res, Try{N: i + 1, Why: why})
+ }
+ slices.SortStableFunc(res, func(a, b Try) int {
+ return boolInt(!had(ch.Options[a.N-1])) - boolInt(!had(ch.Options[b.N-1]))
+ })
+ return res[:min(len(res), tries)]
+}
diff --git a/internal/plan/first.go b/internal/plan/first.go
new file mode 100644
index 0000000..1345641
--- /dev/null
+++ b/internal/plan/first.go
@@ -0,0 +1,226 @@
+package plan
+
+import (
+ "cmp"
+ "slices"
+
+ "github.com/mohsensc/tend-cli/internal/config"
+ "github.com/mohsensc/tend-cli/internal/core"
+ "github.com/mohsensc/tend-cli/internal/eco"
+ "github.com/mohsensc/tend-cli/internal/scan"
+)
+
+// Spread is how many call sites a change may touch and still go into a
+// catch-up stage before the last. Past it the edit is a migration, which
+// waits until the libraries and runtimes it is written against are current.
+const Spread = 10
+
+// The stages of a catch-up, in the order tend takes them. Tier says which a
+// change belongs to.
+const (
+ Fixes = 1 // security fixes, API changes, moves off what is deprecated now
+ Runtimes = 2 // runtime pins, base images, CI Actions and build tools
+ Majors = 3 // releases that are only new, majors above all
+ Migrations = 4 // wide migrations, and choices between replacements
+ Last = Migrations
+)
+
+// StageName says what a stage does, as a PR names it.
+func StageName(k int) string {
+ switch k {
+ case Fixes:
+ return "fixes"
+ case Runtimes:
+ return "runtimes and build tooling"
+ case Majors:
+ return "major upgrades"
+ case Migrations:
+ return "migrations and replacements"
+ }
+ return ""
+}
+
+// Tier is the catch-up stage a queued change belongs to. The first rule that
+// matches wins: a migration past Spread call sites, or a choice between
+// replacements, waits for the last stage; an API change and a security fix
+// come first; what pins the project's runtime or build comes next, then the
+// releases that are only new; any other move off something deprecated is a
+// fix.
+func Tier(ch *core.Change) int {
+ switch {
+ case len(core.Calls(ch)) > Spread:
+ return Migrations
+ case ch.API == nil && ch.To == "" && ch.ToName == "":
+ return Migrations
+ case ch.API != nil || ch.Kind == core.Security:
+ return Fixes
+ case tooling(ch):
+ return Runtimes
+ case ch.Kind == core.Breaking || ch.Kind == core.Update:
+ return Majors
+ }
+ return Fixes
+}
+
+// tooling reports whether every dep a change moves is something the project
+// runs or builds on rather than code it calls: a runtime pin or minimum, a
+// base image, an Action, or a dev dependency nothing outside the tests calls,
+// such as a compiler, a bundler or a test runner.
+func tooling(ch *core.Change) bool {
+ if len(ch.Deps) == 0 {
+ return false
+ }
+ code := slices.ContainsFunc(core.Calls(ch), func(s core.Site) bool { return !scan.IsTest(s.File) })
+ for _, d := range ch.Deps {
+ if !traits(d).Tooling && !d.Min && (!d.Dev || code) {
+ return false
+ }
+ }
+ return true
+}
+
+// First is tend's first PR on a repo as one change: the lowest stage of the
+// catch-up with anything in it, the direct dependencies nothing uses, those
+// that only look unused, and the rest of the queue, each in the stage it
+// waits for. It is nil when it would change nothing: nothing to make or
+// remove, and a tend.yml already there for a welcome PR to add.
+func First(inv *core.Inventory, p *Plan, cfg *config.Config, configured bool) (*core.Change, error) {
+ gone, kept, err := eco.Unused(inv, cfg.Keeps)
+ if err != nil {
+ return nil, err
+ }
+ b := stage(p, 0, gone)
+ b.Unused, b.Kept = gone, kept
+ if len(b.Changes)+len(b.Unused)+len(b.Next) == 0 && configured {
+ return nil, nil
+ }
+ ch := &core.Change{ID: core.FirstID, Kind: core.First, Batch: b}
+ Refit(ch)
+ return ch, nil
+}
+
+// Next is the catch-up PR for the first stage past after with anything in
+// it, carrying what is left of the stages before it too, or nil when no
+// stage past after has anything left.
+func Next(p *Plan, after int) *core.Change {
+ if lowest(p.Queue, after) == 0 {
+ return nil
+ }
+ b := stage(p, after, nil)
+ ch := &core.Change{ID: core.StageID(b.Stage), Kind: core.First, Batch: b}
+ Refit(ch)
+ return ch
+}
+
+// stage is the batch of the first stage past after with anything in it:
+// every queued change of that stage or an earlier one, and the rest of the
+// queue, each under the stage it waits for. A change on a package another
+// change in the batch moves waits for the next stage.
+func stage(p *Plan, after int, gone []core.Dep) *core.Batch {
+ var queue []core.Change
+ for _, ch := range p.Queue {
+ if ch.Kind != core.First && !removed(&ch, gone) {
+ queue = append(queue, ch)
+ }
+ }
+ b := &core.Batch{Stage: cmp.Or(lowest(queue, after), max(after+1, Fixes))}
+ var held []core.Dep
+ for _, ch := range queue {
+ t := Tier(&ch)
+ switch {
+ case t > b.Stage:
+ b.Next = append(b.Next, core.Later{Change: ch, Stage: t})
+ case slices.ContainsFunc(ch.Deps, func(d core.Dep) bool { return slices.ContainsFunc(held, same(d)) }):
+ b.Next = append(b.Next, core.Later{Change: ch, Why: "another change here moves the same package, so this one comes after it"})
+ default:
+ held = append(held, ch.Deps...)
+ b.Changes = append(b.Changes, ch)
+ }
+ }
+ for i := range b.Next {
+ if b.Next[i].Stage == 0 {
+ b.Next[i].Stage = After(b)
+ }
+ }
+ return b
+}
+
+// lowest is the lowest stage past after that a queued change belongs to,
+// 0 when there is none.
+func lowest(queue []core.Change, after int) int {
+ res := 0
+ for _, ch := range queue {
+ if t := Tier(&ch); ch.Kind != core.First && t > after && (res == 0 || t < res) {
+ res = t
+ }
+ }
+ return res
+}
+
+// After is the stage that comes after a batch's own: the lowest one its
+// queue has changes waiting in, 0 when none, which ends the catch-up.
+func After(b *core.Batch) int {
+ res := 0
+ for _, l := range b.Next {
+ if l.Stage > b.Stage && (res == 0 || l.Stage < res) {
+ res = l.Stage
+ }
+ }
+ return res
+}
+
+// removed reports whether everything ch moves is a dependency the first PR
+// removes, which needs no fix or move of its own.
+func removed(ch *core.Change, gone []core.Dep) bool {
+ return len(ch.Deps) > 0 && !slices.ContainsFunc(ch.Deps, func(d core.Dep) bool {
+ return !slices.ContainsFunc(gone, same(d))
+ })
+}
+
+// same matches a dependency declared in the same manifest as d.
+func same(d core.Dep) func(core.Dep) bool {
+ return func(x core.Dep) bool {
+ return x.Ecosystem == d.Ecosystem && x.Name == d.Name && x.Manifest.Path == d.Manifest.Path
+ }
+}
+
+// Refit sets a catch-up PR's deps and sites from what its batch carries: the
+// dependencies it removes and moves, a swap's new package among them, and the
+// call sites its changes touch. Vetting reads them like any change's.
+func Refit(ch *core.Change) {
+ b := ch.Batch
+ deps := slices.Clone(b.Unused)
+ var sites []core.Site
+ for _, c := range b.Changes {
+ deps = append(deps, c.Deps...)
+ if name, to := Target(&c); len(c.Deps) > 0 && name != c.Deps[0].Name {
+ d := c.Deps[0]
+ d.Name, d.Version, d.Req, d.Line = name, to, "", 0
+ deps = append(deps, d)
+ }
+ sites = append(sites, c.Sites...)
+ }
+ ch.Deps, ch.Sites = deps, sortSites(sites)
+}
+
+// Target is the package a change moves its first dep to and the release,
+// its own or that of the option a run took.
+func Target(ch *core.Change) (string, string) {
+ name, to := "", ch.To
+ if len(ch.Deps) > 0 {
+ name = ch.Deps[0].Name
+ }
+ if ch.ToName != "" {
+ name = ch.ToName
+ }
+ if c := ch.Choice; c != nil && c.N <= len(ch.Options) {
+ o := ch.Options[c.N-1]
+ if o.ToName != "" {
+ name = o.ToName
+ }
+ if o.To != "" {
+ to = o.To
+ }
+ }
+ return name, to
+}
diff --git a/internal/plan/first_test.go b/internal/plan/first_test.go
new file mode 100644
index 0000000..942d883
--- /dev/null
+++ b/internal/plan/first_test.go
@@ -0,0 +1,264 @@
+package plan
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "slices"
+ "testing"
+ "time"
+
+ "github.com/mohsensc/tend-cli/internal/config"
+ "github.com/mohsensc/tend-cli/internal/core"
+)
+
+// A repo with one package nothing uses and a queue of every kind: the first
+// PR carries the fixes and the removal, and plans the rest stage by stage:
+// the base image and the runtime minimum next, then the major, then the
+// migration past Spread call sites and the choice between replacements.
+func TestFirst(t *testing.T) {
+ root := t.TempDir()
+ for name, body := range map[string]string{
+ "package.json": `{"dependencies": {"left-pad": "^1.0.0", "@fixture/pay": "^1.4.0"}}`,
+ "package-lock.json": `{"lockfileVersion": 3, "packages": {"": {}, "node_modules/left-pad": {"version": "1.3.0"}, "node_modules/@fixture/pay": {"version": "1.4.0"}}}`,
+ "src/billing.js": "const pay = require('@fixture/pay')\npay.charges.create({})\n",
+ } {
+ p := filepath.Join(root, filepath.FromSlash(name))
+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ cfg := config.Default()
+ inv, _, err := Inventory(root, cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var pay, pad core.Dep
+ for _, d := range inv.Deps {
+ switch d.Name {
+ case "@fixture/pay":
+ pay = d
+ case "left-pad":
+ pad = d
+ }
+ }
+ site := func(file string, line int) core.Site { return core.Site{File: file, Line: line, Chain: []string{"x"}} }
+ var many []core.Site
+ for i := range Spread + 1 {
+ many = append(many, site("src/report.js", i+1))
+ }
+ lodash := core.Dep{Ecosystem: core.Npm, Name: "lodash", Version: "4.17.20", Direct: true, Manifest: core.Manifest{Path: "package.json"}}
+ node := core.Dep{Ecosystem: core.Docker, Name: "library/node", Direct: true, Manifest: core.Manifest{Path: "Dockerfile"}}
+ engines := core.Dep{Ecosystem: core.Toolchain, Name: "nodejs", Direct: true, Min: true, Manifest: core.Manifest{Path: "package.json"}}
+ vitest := core.Dep{Ecosystem: core.Npm, Name: "vitest", Version: "1.6.0", Direct: true, Manifest: core.Manifest{Path: "package.json"}}
+ moment := core.Dep{Ecosystem: core.Npm, Name: "moment", Version: "2.30.1", Direct: true, Manifest: core.Manifest{Path: "package.json"}}
+ request := core.Dep{Ecosystem: core.Npm, Name: "request", Version: "2.88.2", Direct: true, Manifest: core.Manifest{Path: "package.json"}}
+ p := &Plan{Queue: []core.Change{
+ {ID: "npm/lodash@4.17.21", Kind: core.Security, Deps: []core.Dep{lodash}, To: "4.17.21", Sites: []core.Site{site("src/a.js", 1)}},
+ {ID: "npm/@fixture/pay@2.0.0", Kind: core.Deprecation, Deps: []core.Dep{pay}, To: "2.0.0", Sites: []core.Site{site("src/billing.js", 2)}},
+ {ID: "docker/library/node@22", Kind: core.Deprecation, Deps: []core.Dep{node}, To: "22", Sites: []core.Site{{File: "Dockerfile", Line: 1}}},
+ {ID: "npm/@fixture/pay@1.4.0", Kind: core.Deprecation, Deps: []core.Dep{pay}, To: "1.4.0"},
+ {ID: "toolchain/nodejs@20", Kind: core.Deprecation, Deps: []core.Dep{engines}, To: "20"},
+ {ID: "npm/moment@", Kind: core.Deprecation, Deps: []core.Dep{moment}, Options: []core.Option{{Title: "Migrate to dayjs"}}},
+ {ID: "npm/request->undici@6.19.8", Kind: core.Deprecation, Deps: []core.Dep{request}, ToName: "undici", To: "6.19.8", Sites: many},
+ {ID: "npm/vitest@3.2.4", Kind: core.Breaking, Level: "major", Deps: []core.Dep{vitest}, To: "3.2.4", Sites: []core.Site{site("test/a.test.js", 1)}},
+ // deprecated and unused: the first PR removes it rather than moves off it
+ {ID: "npm/left-pad@1.3.0", Kind: core.Deprecation, Deps: []core.Dep{pad}, To: "1.3.0", Evidence: []core.Evidence{{Source: "registry"}}},
+ }}
+
+ ch, err := First(inv, p, cfg, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b := ch.Batch
+ if ch.ID != core.FirstID || ch.Kind != core.First || len(b.Unused) != 1 || b.Unused[0].Name != "left-pad" {
+ t.Fatalf("first = %+v", ch)
+ }
+ var made []string
+ for _, c := range b.Changes {
+ made = append(made, c.ID)
+ }
+ if want := []string{"npm/lodash@4.17.21", "npm/@fixture/pay@2.0.0"}; !slices.Equal(made, want) || b.Stage != Fixes {
+ t.Errorf("stage %d made %q, want %q", b.Stage, made, want)
+ }
+ stage := map[string]int{}
+ why := map[string]string{}
+ for _, l := range b.Next {
+ stage[l.Change.ID], why[l.Change.ID] = l.Stage, l.Why
+ }
+ for id, want := range map[string]int{
+ "docker/library/node@22": Runtimes,
+ "npm/@fixture/pay@1.4.0": Runtimes,
+ "toolchain/nodejs@20": Runtimes,
+ "npm/vitest@3.2.4": Majors,
+ "npm/moment@": Migrations,
+ "npm/request->undici@6.19.8": Migrations,
+ } {
+ if stage[id] != want {
+ t.Errorf("%s waits for stage %d, want %d", id, stage[id], want)
+ }
+ }
+ if w := why["npm/@fixture/pay@1.4.0"]; w != "another change here moves the same package, so this one comes after it" || why["npm/vitest@3.2.4"] != "" {
+ t.Errorf("why = %q", why)
+ }
+ if len(b.Next) != 6 || After(b) != Runtimes {
+ t.Errorf("next = %+v, after %d", b.Next, After(b))
+ }
+ if names := core.Names(ch); !slices.Equal(names, []string{"left-pad", "lodash", "@fixture/pay"}) || len(ch.Sites) != 2 {
+ t.Errorf("deps %q, sites %+v", names, ch.Sites)
+ }
+
+ cfg.Ignore = []config.Ignore{{Name: "left-pad", Versions: []string{">=2"}}}
+ if ch, _ := First(inv, p, cfg, false); len(ch.Batch.Unused) != 0 {
+ t.Errorf("an ignore entry did not hold left-pad back: %+v", ch.Batch.Unused)
+ }
+ if ch, _ := First(inv, &Plan{Queue: p.Queue[4:8]}, cfg, true); ch == nil || ch.Batch.Stage != Runtimes || len(ch.Batch.Changes) != 1 || len(ch.Batch.Next) != 3 {
+ t.Errorf("with nothing to fix, the first PR is the next stage: %+v", ch)
+ }
+ if ch, _ := First(inv, &Plan{}, cfg, true); ch != nil {
+ t.Errorf("a first PR with nothing to make and a tend.yml already there: %+v", ch)
+ }
+ if ch, _ := First(inv, &Plan{}, cfg, false); ch == nil || len(ch.Deps) != 0 {
+ t.Errorf("a repo with nothing to catch up on still gets its welcome: %+v", ch)
+ }
+}
+
+// A swap brings its new package into the change, where vetting looks for
+// the new calls and the lockfile's new entries.
+func TestRefit(t *testing.T) {
+ req := core.Dep{Ecosystem: core.Npm, Name: "request", Version: "2.88.0", Line: 4, Direct: true}
+ ch := &core.Change{Kind: core.First, Batch: &core.Batch{
+ Unused: []core.Dep{{Ecosystem: core.Npm, Name: "left-pad"}},
+ Changes: []core.Change{{Deps: []core.Dep{req}, ToName: "undici", To: "6.19.8", Sites: []core.Site{{File: "b.js", Line: 3}, {File: "a.js", Line: 9}}}},
+ }}
+ Refit(ch)
+ if names := core.Names(ch); !slices.Equal(names, []string{"left-pad", "request", "undici"}) {
+ t.Errorf("deps %q", names)
+ }
+ if u := ch.Deps[2]; u.Version != "6.19.8" || u.Line != 0 || !u.Direct {
+ t.Errorf("undici = %+v", u)
+ }
+ if ch.Sites[0].File != "a.js" {
+ t.Errorf("sites %+v are not sorted", ch.Sites)
+ }
+}
+
+// Each stage takes what is left of the ones before it, and none is left
+// once nothing past the last stage that landed waits.
+func TestNext(t *testing.T) {
+ dep := func(name string) core.Dep {
+ return core.Dep{Ecosystem: core.Npm, Name: name, Version: "1.0.0", Direct: true, Manifest: core.Manifest{Path: "package.json"}}
+ }
+ fix := core.Change{ID: "npm/a@1.0.1", Kind: core.Security, Deps: []core.Dep{dep("a")}, To: "1.0.1"}
+ major := core.Change{ID: "npm/b@3.0.0", Kind: core.Breaking, Level: "major", Deps: []core.Dep{dep("b")}, To: "3.0.0", Sites: []core.Site{{File: "src/b.js", Line: 1}}}
+ choice := core.Change{ID: "npm/c@", Kind: core.Deprecation, Deps: []core.Dep{dep("c")}, Options: []core.Option{{Title: "Switch to d", ToName: "d", To: "2.0.0"}}}
+ p := &Plan{Queue: []core.Change{fix, major, choice}}
+
+ ch := Next(p, Fixes)
+ if ch == nil || ch.ID != core.StageID(Majors) || ch.Batch.Stage != Majors {
+ t.Fatalf("after the fixes: %+v", ch)
+ }
+ var made []string
+ for _, c := range ch.Batch.Changes {
+ made = append(made, c.ID)
+ }
+ if !slices.Equal(made, []string{"npm/a@1.0.1", "npm/b@3.0.0"}) || len(ch.Batch.Next) != 1 || ch.Batch.Next[0].Stage != Migrations {
+ t.Errorf("stage 3 makes %q and leaves %+v", made, ch.Batch.Next)
+ }
+ if ch := Next(p, Majors); ch == nil || ch.Batch.Stage != Migrations || len(ch.Batch.Changes) != 3 || After(ch.Batch) != 0 {
+ t.Errorf("the last stage: %+v", ch)
+ }
+ if ch := Next(&Plan{Queue: []core.Change{fix}}, Majors); ch != nil {
+ t.Errorf("only a fix left after stage 3: %+v", ch)
+ }
+}
+
+// The rules put each change in one stage, the first that matches winning.
+func TestTier(t *testing.T) {
+ site := func(file string) core.Site { return core.Site{File: file, Line: 1} }
+ lib := core.Dep{Ecosystem: core.Npm, Name: "lib", Version: "1.0.0", Direct: true}
+ tool := core.Dep{Ecosystem: core.Npm, Name: "webpack", Version: "4.0.0", Direct: true, Dev: true}
+ var many []core.Site
+ for i := range Spread + 1 {
+ many = append(many, core.Site{File: "src/a.js", Line: i + 1})
+ }
+ for _, tt := range []struct {
+ name string
+ ch core.Change
+ want int
+ }{
+ {"security", core.Change{Kind: core.Security, Deps: []core.Dep{lib}, To: "1.0.1"}, Fixes},
+ {"security past Spread", core.Change{Kind: core.Security, Deps: []core.Dep{lib}, To: "2.0.0", Sites: many}, Migrations},
+ {"api", core.Change{Kind: core.Breaking, API: &core.APIChange{Provider: "x"}}, Fixes},
+ {"deprecated version", core.Change{Kind: core.Deprecation, Deps: []core.Dep{lib}, To: "2.0.0"}, Fixes},
+ {"no single replacement", core.Change{Kind: core.Deprecation, Deps: []core.Dep{lib}}, Migrations},
+ {"runtime pin", core.Change{Kind: core.Deprecation, Deps: []core.Dep{{Ecosystem: core.Toolchain, Name: "nodejs"}}, To: "24"}, Runtimes},
+ {"base image", core.Change{Kind: core.Deprecation, Deps: []core.Dep{{Ecosystem: core.Docker, Name: "library/node"}}, To: "24"}, Runtimes},
+ {"build tool", core.Change{Kind: core.Breaking, Level: "major", Deps: []core.Dep{tool}, To: "5.0.0", Sites: []core.Site{site("test/build.test.js")}}, Runtimes},
+ {"dev dep the code calls", core.Change{Kind: core.Breaking, Level: "major", Deps: []core.Dep{tool}, To: "5.0.0", Sites: []core.Site{site("src/build.js")}}, Majors},
+ {"major", core.Change{Kind: core.Breaking, Level: "major", Deps: []core.Dep{lib}, To: "3.0.0", Sites: []core.Site{site("src/a.js")}}, Majors},
+ } {
+ if got := Tier(&tt.ch); got != tt.want {
+ t.Errorf("%s: stage %d, want %d", tt.name, got, tt.want)
+ }
+ }
+}
+
+// tend tries a dependency the project has first, then the catalog's order,
+// and never staying put or a replacement with no release to move to.
+func TestRanked(t *testing.T) {
+ ch := &core.Change{Deps: []core.Dep{{Name: "request", Version: "2.88.2"}}, Options: []core.Option{
+ {Title: "Switch to undici", ToName: "undici", To: "7.16.0"},
+ {Title: "Switch to gone", ToName: "gone"},
+ {Title: "Switch to axios", ToName: "axios", To: "1.12.2"},
+ {Title: "Pin to 2.88.2 and ignore", To: "2.88.2"},
+ }}
+ var got []string
+ for _, x := range Ranked(ch, nil) {
+ got = append(got, fmt.Sprintf("%d %s", x.N, x.Why))
+ }
+ if want := []string{"1 the catalog's recommended replacement", "3 the next replacement in the catalog's order"}; !slices.Equal(got, want) {
+ t.Errorf("ranked %q, want %q", got, want)
+ }
+ got = nil
+ for _, x := range Ranked(ch, []core.Dep{{Name: "axios", Direct: true}}) {
+ got = append(got, fmt.Sprintf("%d %s", x.N, x.Why))
+ }
+ if want := []string{"3 the project already depends on axios", "1 the catalog's recommended replacement"}; !slices.Equal(got, want) {
+ t.Errorf("with axios in use, ranked %q, want %q", got, want)
+ }
+ rename := &core.Change{Deps: []core.Dep{{Name: "pay", Version: "1.4.0"}}, To: "2.0.0", Options: []core.Option{
+ {Title: "Apply the rename", To: "2.0.0", Codemod: &core.Codemod{Renames: map[string]string{"a": "b"}}},
+ {Title: "Pin to 1.4.0 and ignore", To: "1.4.0"},
+ }}
+ if r := Ranked(rename, nil); len(r) != 1 || r[0].N != 1 {
+ t.Errorf("rename ranked %+v", r)
+ }
+}
+
+// A major two or more behind can climb through the newest release of each
+// major in between; a runtime never does, and one major behind has no step.
+func TestSteps(t *testing.T) {
+ now := time.Date(2026, 10, 21, 0, 0, 0, 0, time.UTC)
+ old := now.AddDate(-1, 0, 0)
+ m := &core.Meta{Releases: []core.Release{
+ {Version: "1.0.0", Time: old}, {Version: "2.0.0", Time: old}, {Version: "2.4.1", Time: old}, {Version: "3.0.0", Time: old},
+ {Version: "3.1.0", Time: old}, {Version: "4.0.0-rc.1", Time: old, Pre: true}, {Version: "4.0.0", Time: old},
+ }}
+ web := core.Dep{Ecosystem: core.Npm, Name: "web", Version: "1.0.0", Direct: true}
+ b := &builder{in: Input{Cfg: config.Default(), Now: now}, meta: map[pkg]*core.Meta{{core.Npm, "web"}: m}}
+ if got := b.steps(&core.Change{Deps: []core.Dep{web}, To: "4.0.0"}); !slices.Equal(got, []string{"2.4.1", "3.1.0"}) {
+ t.Errorf("steps = %q", got)
+ }
+ if got := b.steps(&core.Change{Deps: []core.Dep{web}, To: "2.4.1"}); got != nil {
+ t.Errorf("one major: %q", got)
+ }
+ node := core.Dep{Ecosystem: core.Toolchain, Name: "nodejs", Version: "16.20.2"}
+ b.meta[pkg{core.Toolchain, "nodejs"}] = &core.Meta{Releases: []core.Release{{Version: "18.0.0"}, {Version: "20.0.0"}, {Version: "24.0.0"}}}
+ if got := b.steps(&core.Change{Deps: []core.Dep{node}, To: "24.0.0"}); got != nil {
+ t.Errorf("a runtime climbs: %q", got)
+ }
+}
diff --git a/internal/plan/hints.go b/internal/plan/hints.go
index 09197f5..b340d5c 100644
--- a/internal/plan/hints.go
+++ b/internal/plan/hints.go
@@ -109,13 +109,15 @@ func stay(d core.Dep, to string) core.Option {
Title: "Pin to " + at + " and ignore",
Detail: fmt.Sprintf("Stay on %s %s and have tend stop proposing anything for it, security fixes included, until the entry is removed.\n\nThis goes into tend.yml:\n\n"+
"```yaml\nignore:\n - name: %q\n reason: staying on %s\n```", d.Name, at, d.Name, at),
- To: at,
+ To: at,
+ Stay: true,
}
}
return core.Option{
Title: "Pin to " + at + " and ignore",
Detail: fmt.Sprintf("Stay on %s and have tend stop proposing %s.\n\nThis goes into tend.yml:\n\n"+
"```yaml\nignore:\n - name: %q\n versions: [\">=%s\"]\n reason: staying on %s\n```", at, to, d.Name, to, at),
- To: at,
+ To: at,
+ Stay: true,
}
}
diff --git a/internal/plan/merge.go b/internal/plan/merge.go
index c7ac162..29fb3ef 100644
--- a/internal/plan/merge.go
+++ b/internal/plan/merge.go
@@ -325,13 +325,13 @@ func repoKey(s string) string {
return strings.TrimSuffix(strings.TrimSuffix(strings.ToLower(strings.TrimPrefix(s, "git+")), "/"), ".git")
}
-// kindRank puts a tidy-up straight after security work: it is tend's first
-// PR, and only a security fix may go ahead of it.
+// kindRank puts tend's first PR ahead of everything: the security fixes it
+// can make are part of it.
func kindRank(k core.Kind) int {
switch k {
- case core.Security:
+ case core.First:
return 0
- case core.Tidy:
+ case core.Security:
return 1
case core.Breaking:
return 2
@@ -358,7 +358,7 @@ func sevRank(s string) int {
// soon is how close a sunset has to be for a deprecation to rank as breaking.
const soon = 30 * 24 * time.Hour
-// Rank orders a queue: kind (security, the tidy-up, a removed API, a
+// Rank orders a queue: kind (the first PR, security, a removed API, a
// deprecation, a major bump, an update), severity, nearest sunset, most
// sites, oldest upstream change, then id so the order never depends on map
// iteration.
diff --git a/internal/plan/pick.go b/internal/plan/pick.go
index 6eb0709..6ddfe75 100644
--- a/internal/plan/pick.go
+++ b/internal/plan/pick.go
@@ -30,6 +30,9 @@ func (b *builder) drop(ch *core.Change) (reason, detail string) {
return "cooldown", fmt.Sprintf("released %s, cooldown is %s", ch.Published.UTC().Format(time.DateOnly), cfg.Cooldown)
}
if p, ok := parked(st, ch); ok {
+ if p.Reason == "reverted" {
+ return "parked", p.Detail
+ }
return "parked", fmt.Sprintf("#%d was closed without merging", p.PR)
}
if why := transitiveOnly(ch); why != "" {
@@ -78,8 +81,9 @@ func subjects(ch *core.Change) []core.Dep {
return ch.Deps
}
-// parked finds a rejection of this change at the same or a newer target. A
-// preempted change is not parked: it comes back by itself.
+// parked finds a rejection of this change at the same or a newer target, a
+// maintainer's or that of the CI that made tend revert it. A preempted
+// change is not parked: it comes back by itself.
func parked(st *state.State, ch *core.Change) (state.Parked, bool) {
if st == nil {
return state.Parked{}, false
@@ -87,7 +91,7 @@ func parked(st *state.State, ch *core.Change) (state.Parked, bool) {
var res state.Parked
found := false
for id, p := range st.Parked {
- if p.Reason != "rejected" || core.Subject(id) != core.Subject(ch.ID) || ver.Less(p.To, ch.To) {
+ if p.Reason == "preempted" || core.Subject(id) != core.Subject(ch.ID) || ver.Less(p.To, ch.To) {
continue
}
if !found || p.PR > res.PR {
@@ -181,8 +185,9 @@ func OpenID(pr *core.PR, st *state.State) string {
var marker = regexp.MustCompile(`\n"}
}
@@ -950,9 +950,11 @@ func TestPick(t *testing.T) {
{name: "security preempts a vanished change", queue: []core.Change{sec}, open: pr(4, "npm/q@1.0.0"), pick: "npm/a@1.0.1", preempt: "#4"},
{name: "security never preempts security", queue: []core.Change{sec, sec2}, open: pr(5, "npm/b@2.0.1"), pick: "npm/b@2.0.1"},
{name: "newer target replaces", queue: []core.Change{brkNewer}, open: pr(6, "npm/c@3.0.0"), pick: "npm/c@3.1.0", preempt: "#6"},
- {name: "the tidy-up goes first", queue: []core.Change{tidy, brk}, pick: core.TidyID},
- {name: "the open tidy-up holds the rest back", queue: []core.Change{tidy, brk}, open: pr(1, core.TidyID), pick: core.TidyID},
- {name: "security preempts the tidy-up", queue: []core.Change{sec, tidy}, open: pr(1, core.TidyID), pick: "npm/a@1.0.1", preempt: "#1"},
+ {name: "the first PR goes first", queue: []core.Change{first, brk}, pick: core.FirstID},
+ {name: "the open first PR holds the rest back", queue: []core.Change{first, brk}, open: pr(1, core.FirstID), pick: core.FirstID},
+ {name: "security does not preempt the first PR", queue: []core.Change{first, sec}, open: pr(1, core.FirstID), pick: core.FirstID},
+ {name: "the first PR folds an open security fix in", queue: []core.Change{first, sec}, open: pr(4, "npm/a@1.0.1"), pick: core.FirstID, preempt: "#4"},
+ {name: "the first PR folds any open PR in", queue: []core.Change{first, brk}, open: pr(4, "npm/z@1.0.0"), pick: core.FirstID, preempt: "#4"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
diff --git a/internal/plan/registry.go b/internal/plan/registry.go
index 8dc8767..b72c69e 100644
--- a/internal/plan/registry.go
+++ b/internal/plan/registry.go
@@ -229,6 +229,9 @@ func (b *builder) swap(ctx context.Context, d core.Dep, m *core.Meta, ev core.Ev
ch.Options = []core.Option{*one}
case ok:
ch.Options = opts
+ for i := range ch.Options {
+ ch.Options[i].To = b.latest(ctx, d.Ecosystem, ch.Options[i].ToName)
+ }
}
}
if name == "" {
@@ -258,6 +261,31 @@ func (b *builder) latest(ctx context.Context, eco, name string) string {
return rel.Version
}
+// steps are the rungs a major bump of more than one major can climb when
+// the jump to its target fails: the release candidate would pick within
+// each major in between, ascending. A runtime or an image is not climbed:
+// the lines in between are past their end of life too.
+func (b *builder) steps(ch *core.Change) []string {
+ if ch.API != nil || ch.ToName != "" || ch.To == "" || len(ch.Deps) == 0 || traits(ch.Deps[0]).Tooling {
+ return nil
+ }
+ d := ch.Deps[0]
+ cur, ok1 := ver.Parse(Current(d))
+ to, ok2 := ver.Parse(ch.To)
+ m := b.meta[pkg{d.Ecosystem, d.Name}]
+ if !ok1 || !ok2 || m == nil || to.Major()-cur.Major() < 2 {
+ return nil
+ }
+ var res []string
+ for major := cur.Major() + 1; major < to.Major(); major++ {
+ rel, ok := candidate(d, m, b.in.Now, b.cooldown(), major)
+ if v, _ := ver.Parse(rel.Version); ok && v.Major() == major {
+ res = append(res, rel.Version)
+ }
+ }
+ return res
+}
+
// typesCap keeps @types/x on the major of x: the typings follow the package,
// never lead it.
func (b *builder) typesCap(d core.Dep) int {
diff --git a/internal/plan/tidy.go b/internal/plan/tidy.go
deleted file mode 100644
index ac5bf25..0000000
--- a/internal/plan/tidy.go
+++ /dev/null
@@ -1,76 +0,0 @@
-package plan
-
-import (
- "slices"
-
- "github.com/mohsensc/tend-cli/internal/config"
- "github.com/mohsensc/tend-cli/internal/core"
- "github.com/mohsensc/tend-cli/internal/eco"
-)
-
-// Tidy is tend's first PR on a repo as one change: the direct dependencies
-// nothing uses, those that only look unused, and the deprecated libraries in
-// the queue, which it moves off as their own changes would. It is nil when
-// it would change nothing: no dependency to remove, no library to move, and
-// a tend.yml already there for a welcome PR to add.
-func Tidy(inv *core.Inventory, p *Plan, cfg *config.Config, configured bool) (*core.Change, error) {
- gone, kept, err := eco.Unused(inv, cfg.Keeps)
- if err != nil {
- return nil, err
- }
- var moves []core.Change
- for _, ch := range p.Queue {
- if library(&ch) && !slices.ContainsFunc(gone, same(ch.Deps[0])) {
- moves = append(moves, ch)
- }
- }
- if len(gone) == 0 && len(moves) == 0 && configured {
- return nil, nil
- }
- ch := &core.Change{ID: core.TidyID, Kind: core.Tidy, Cleanup: &core.Cleanup{Unused: gone, Kept: kept, Moves: moves}}
- Refit(ch)
- return ch, nil
-}
-
-// same matches a dependency declared in the same manifest as d. A
-// deprecated package the tidy-up removes needs no move off it.
-func same(d core.Dep) func(core.Dep) bool {
- return func(x core.Dep) bool {
- return x.Ecosystem == d.Ecosystem && x.Name == d.Name && x.Manifest.Path == d.Manifest.Path
- }
-}
-
-// library reports a change that moves the code off a deprecated package it
-// imports. Base images, Actions, runtimes, APIs and calls a runtime warned
-// about keep PRs of their own.
-func library(ch *core.Change) bool {
- if ch.Kind != core.Deprecation || ch.API != nil || len(ch.Deps) == 0 || !ch.Deps[0].Direct {
- return false
- }
- e := eco.ByName(ch.Deps[0].Ecosystem)
- if e == nil || len(e.Imports(ch.Deps[0])) == 0 {
- return false
- }
- return slices.ContainsFunc(ch.Evidence, func(ev core.Evidence) bool {
- return ev.Source == "registry" || ev.Source == "archived"
- })
-}
-
-// Refit sets a tidy change's deps and sites from what its cleanup carries:
-// the dependencies it removes and moves, a swap's new package among them, and
-// the call sites the moves touch. Vetting reads them like any change's.
-func Refit(ch *core.Change) {
- c := ch.Cleanup
- deps := slices.Clone(c.Unused)
- var sites []core.Site
- for _, m := range c.Moves {
- deps = append(deps, m.Deps...)
- if m.ToName != "" {
- d := m.Deps[0]
- d.Name, d.Version, d.Req, d.Line = m.ToName, m.To, "", 0
- deps = append(deps, d)
- }
- sites = append(sites, m.Sites...)
- }
- ch.Deps, ch.Sites = deps, sortSites(sites)
-}
diff --git a/internal/plan/tidy_test.go b/internal/plan/tidy_test.go
deleted file mode 100644
index 6018e71..0000000
--- a/internal/plan/tidy_test.go
+++ /dev/null
@@ -1,102 +0,0 @@
-package plan
-
-import (
- "os"
- "path/filepath"
- "slices"
- "testing"
-
- "github.com/mohsensc/tend-cli/internal/config"
- "github.com/mohsensc/tend-cli/internal/core"
-)
-
-// A repo with one package nothing uses and one deprecated package the code
-// calls, next to the deprecations a tidy-up leaves to PRs of their own.
-func TestTidy(t *testing.T) {
- root := t.TempDir()
- for name, body := range map[string]string{
- "package.json": `{"dependencies": {"left-pad": "^1.0.0", "@fixture/pay": "^1.4.0"}}`,
- "package-lock.json": `{"lockfileVersion": 3, "packages": {"": {}, "node_modules/left-pad": {"version": "1.3.0"}, "node_modules/@fixture/pay": {"version": "1.4.0"}}}`,
- "src/billing.js": "const pay = require('@fixture/pay')\npay.charges.create({})\n",
- } {
- p := filepath.Join(root, filepath.FromSlash(name))
- if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
- t.Fatal(err)
- }
- }
- cfg := config.Default()
- inv, _, err := Inventory(root, cfg)
- if err != nil {
- t.Fatal(err)
- }
- var pay, pad core.Dep
- for _, d := range inv.Deps {
- switch d.Name {
- case "@fixture/pay":
- pay = d
- case "left-pad":
- pad = d
- }
- }
- registry := []core.Evidence{{Source: "registry", Title: "@fixture/pay 1.4.0 is deprecated"}}
- move := core.Change{ID: "npm/@fixture/pay@2.0.0", Kind: core.Deprecation, Deps: []core.Dep{pay}, To: "2.0.0", Evidence: registry,
- Sites: []core.Site{{File: "src/billing.js", Line: 2, Chain: []string{"pay", "charges", "create"}}}}
- node := core.Dep{Ecosystem: core.Docker, Name: "library/node", Direct: true}
- p := &Plan{Queue: []core.Change{
- {ID: "npm/@fixture/pay@1.4.0", Kind: core.Deprecation, Deps: []core.Dep{pay}, To: "1.4.0", Evidence: []core.Evidence{{Source: "runtime"}}},
- move,
- {ID: "docker/library/node@22", Kind: core.Deprecation, Deps: []core.Dep{node}, To: "22", Evidence: []core.Evidence{{Source: "eol"}}},
- {ID: "npm/@fixture/pay@1.4.1", Kind: core.Security, Deps: []core.Dep{pay}, To: "1.4.1"},
- // deprecated and unused: the tidy-up removes it rather than moves off it
- {ID: "npm/left-pad@1.3.0", Kind: core.Deprecation, Deps: []core.Dep{pad}, To: "1.3.0", Evidence: []core.Evidence{{Source: "registry"}}},
- }}
-
- ch, err := Tidy(inv, p, cfg, false)
- if err != nil {
- t.Fatal(err)
- }
- c := ch.Cleanup
- if ch.ID != core.TidyID || ch.Kind != core.Tidy || len(c.Unused) != 1 || c.Unused[0].Name != "left-pad" {
- t.Fatalf("tidy = %+v", ch)
- }
- if len(c.Moves) != 1 || c.Moves[0].ID != move.ID {
- t.Errorf("moves = %+v, want only the registry deprecation", c.Moves)
- }
- if names := core.Names(ch); !slices.Equal(names, []string{"left-pad", "@fixture/pay"}) || len(ch.Sites) != 1 {
- t.Errorf("deps %q, sites %+v", names, ch.Sites)
- }
-
- cfg.Ignore = []config.Ignore{{Name: "left-pad", Versions: []string{">=2"}}}
- if ch, _ := Tidy(inv, p, cfg, false); len(ch.Cleanup.Unused) != 0 {
- t.Errorf("an ignore entry did not hold left-pad back: %+v", ch.Cleanup.Unused)
- }
- if ch, _ := Tidy(inv, &Plan{}, cfg, true); ch != nil {
- t.Errorf("a tidy-up with nothing to change and a tend.yml already there: %+v", ch)
- }
- if ch, _ := Tidy(inv, &Plan{}, cfg, false); ch == nil || len(ch.Deps) != 0 {
- t.Errorf("a repo with nothing to tidy still gets its welcome: %+v", ch)
- }
-}
-
-// A swap brings its new package into the change, where vetting looks for
-// the new calls and the lockfile's new entries.
-func TestRefit(t *testing.T) {
- req := core.Dep{Ecosystem: core.Npm, Name: "request", Version: "2.88.0", Line: 4, Direct: true}
- ch := &core.Change{Kind: core.Tidy, Cleanup: &core.Cleanup{
- Unused: []core.Dep{{Ecosystem: core.Npm, Name: "left-pad"}},
- Moves: []core.Change{{Deps: []core.Dep{req}, ToName: "undici", To: "6.19.8", Sites: []core.Site{{File: "b.js", Line: 3}, {File: "a.js", Line: 9}}}},
- }}
- Refit(ch)
- if names := core.Names(ch); !slices.Equal(names, []string{"left-pad", "request", "undici"}) {
- t.Errorf("deps %q", names)
- }
- if u := ch.Deps[2]; u.Version != "6.19.8" || u.Line != 0 || !u.Direct {
- t.Errorf("undici = %+v", u)
- }
- if ch.Sites[0].File != "a.js" {
- t.Errorf("sites %+v are not sorted", ch.Sites)
- }
-}
diff --git a/internal/scan/index.go b/internal/scan/index.go
index f6be4a6..a32304b 100644
--- a/internal/scan/index.go
+++ b/internal/scan/index.go
@@ -446,6 +446,50 @@ func (x *Index) Files() []string {
return res
}
+// Reached reports whether a test reaches the file p: a JavaScript or
+// TypeScript test names a relative path that resolves to it, a Python test
+// imports the module it is, or a Go test sits in its package's directory.
+// In the other languages a test whose file name holds p's base name counts,
+// as FooTest.java does for Foo.java.
+func (x *Index) Reached(p string) bool {
+ stem := strings.TrimSuffix(p, path.Ext(p))
+ for _, f := range x.files {
+ if f.File == p || !IsTest(f.File) {
+ continue
+ }
+ switch strings.TrimSuffix(f.Lang, "?") {
+ case "go":
+ if path.Dir(f.File) == path.Dir(p) {
+ return true
+ }
+ case "js":
+ for _, l := range f.lits {
+ if !strings.HasPrefix(l.Text, ".") {
+ continue
+ }
+ r := path.Join(path.Dir(f.File), l.Text)
+ if r == p || r == stem || path.Join(r, "index") == stem {
+ return true
+ }
+ }
+ case "python":
+ for _, im := range f.imps {
+ for _, q := range im.quals {
+ m := strings.ReplaceAll(q, ".", "/")
+ if stem == m || strings.HasSuffix(stem, "/"+m) || stem == m+"/__init__" || strings.HasSuffix(stem, "/"+m+"/__init__") {
+ return true
+ }
+ }
+ }
+ default:
+ if strings.Contains(strings.ToLower(path.Base(f.File)), strings.ToLower(path.Base(stem))) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
// Notes lists the files left out or only partly read, and why.
func (x *Index) Notes() []string { return x.notes }
diff --git a/internal/scan/index_test.go b/internal/scan/index_test.go
index bb967f6..fd6faef 100644
--- a/internal/scan/index_test.go
+++ b/internal/scan/index_test.go
@@ -664,3 +664,46 @@ client.charges.create
t.Errorf("Uses\n got %q\nwant %q", got, want)
}
}
+
+// A file counts as reached when a test names its path, imports its module or
+// shares its Go package; one no test touches does not.
+func TestReached(t *testing.T) {
+ root := t.TempDir()
+ files := map[string]string{
+ "src/app.js": "module.exports = {}\n",
+ "src/lib/index.js": "module.exports = {}\n",
+ "src/alone.js": "module.exports = {}\n",
+ "test/app.test.js": "const app = require('../src/app')\nconst lib = require('../src/lib')\n",
+ "shop/billing.py": "def charge(): pass\n",
+ "shop/orders.py": "def order(): pass\n",
+ "tests/test_billing.py": "from shop.billing import charge\n",
+ "pkg/a/a.go": "package a\n",
+ "pkg/a/a_test.go": "package a\n",
+ "pkg/b/b.go": "package b\n",
+ "src/main/java/shop/Cart.java": "class Cart {}\n",
+ "src/test/java/shop/CartTest.java": "class CartTest {}\n",
+ }
+ for name, body := range files {
+ p := filepath.Join(root, filepath.FromSlash(name))
+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ x, err := Build(Options{Root: root})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for p, want := range map[string]bool{
+ "src/app.js": true, "src/lib/index.js": true, "src/alone.js": false,
+ "shop/billing.py": true, "shop/orders.py": false,
+ "pkg/a/a.go": true, "pkg/b/b.go": false,
+ "src/main/java/shop/Cart.java": true,
+ } {
+ if got := x.Reached(p); got != want {
+ t.Errorf("Reached(%s) = %v, want %v", p, got, want)
+ }
+ }
+}
diff --git a/internal/selfupdate/install_test.go b/internal/selfupdate/install_test.go
index 69a844e..e4eaf39 100644
--- a/internal/selfupdate/install_test.go
+++ b/internal/selfupdate/install_test.go
@@ -208,6 +208,14 @@ func TestInstallScript(t *testing.T) {
})
}
+ t.Run("the newest of a major still uploading", func(t *testing.T) {
+ fx := newInstallFixture(t)
+ fx.add(t, "v1.10.0").noSig = true
+ fx.add(t, "v1.9.5")
+ fx.start(t)
+ runInstall(t, fx, []string{"GITHUB_ACTION_REF=v1"}, "ok", "1.9.5")
+ })
+
t.Run("token goes to the API and not to downloads", func(t *testing.T) {
fx := newInstallFixture(t)
fx.add(t, "v1.2.0")
diff --git a/internal/state/state.go b/internal/state/state.go
index c10918d..2100930 100644
--- a/internal/state/state.go
+++ b/internal/state/state.go
@@ -28,9 +28,15 @@ type State struct {
Release Release // the last self-update check
// Onboard is where tend's first PR on the repo stands: "" until a run
// looks, due while it is coming or open, then how that ended: merged,
- // closed, clean (nothing to tidy), before (tend was here before), quiet,
+ // closed, clean (nothing to catch up on), before (tend was here before), quiet,
// off, or commit (no PRs to open).
Onboard string `json:",omitempty"`
+ // Stage is how far the catch-up after the first PR got: the stage of
+ // the last catch-up PR that merged or commit that landed, 4 once the
+ // catch-up is over, 0 before it starts or when tend began here before
+ // it had stages.
+ Stage int `json:",omitempty"`
+ Issue Issue
Updated time.Time
path string
@@ -51,7 +57,8 @@ type BaseRun struct {
type Parked struct {
PR int
- Reason string // rejected|preempted
+ Reason string // rejected|preempted|reverted
+ Detail string `json:",omitempty"` // reverted: the commit and the checks that failed
To string
At time.Time
}
@@ -61,6 +68,18 @@ type OpenPR struct {
PR int
Branch, Base, Commit string
At time.Time
+ // Holds, for the first PR, is every queued change it was built from,
+ // made or left for later, so one that appears after it opened brings
+ // it up to date.
+ Holds []string `json:",omitempty"`
+ Stage int `json:",omitempty"` // a catch-up PR's stage
+}
+
+// Issue is tend's tracking issue as tend last wrote it.
+type Issue struct {
+ Number int `json:",omitempty"`
+ Body string `json:",omitempty"`
+ Open bool `json:",omitempty"`
}
type Snap struct {
diff --git a/internal/vet/commands.go b/internal/vet/commands.go
new file mode 100644
index 0000000..44f89c6
--- /dev/null
+++ b/internal/vet/commands.go
@@ -0,0 +1,34 @@
+package vet
+
+import (
+ "context"
+ "slices"
+
+ "github.com/mohsensc/tend-cli/internal/core"
+)
+
+// commands: does the patch change what the project's install, build or test
+// runs? The proof ran the lines the base has, so a patch that rewrites a
+// test script, say to one that always passes, proved nothing about the lines
+// it leaves behind.
+func commands(ctx context.Context, p *pass) ([]core.Finding, string) {
+ in := p.in
+ if in.Detect == nil || in.Patch.Decision {
+ return nil, na
+ }
+ now := in.Detect()
+ var res []core.Finding
+ for _, x := range []struct {
+ what string
+ was, then []string
+ }{
+ {"install", in.Commands.Install, now.Install},
+ {"build", in.Commands.Build, now.Build},
+ {"test", in.Commands.Test, now.Test},
+ } {
+ if !slices.Equal(x.was, x.then) {
+ res = append(res, finding("commands", "", 0, "flagged", "the patch changes the %s lines from %q to %q; the proof ran the first", x.what, x.was, x.then))
+ }
+ }
+ return res, ""
+}
diff --git a/internal/vet/commands_test.go b/internal/vet/commands_test.go
new file mode 100644
index 0000000..af59264
--- /dev/null
+++ b/internal/vet/commands_test.go
@@ -0,0 +1,49 @@
+package vet
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ "github.com/mohsensc/tend-cli/internal/core"
+)
+
+// A patch that rewrites what the project's tests run, as a model rewriting
+// a failing test script to one that passes would, is flagged and makes the
+// PR a draft; one that leaves the lines alone says nothing about them.
+func TestCommands(t *testing.T) {
+ base := core.Commands{Install: []string{"npm ci"}, Test: []string{"npm test"}}
+ dir, sha, diff := worktree(t,
+ map[string]string{"package.json": `{"scripts": {"test": "node --test"}}` + "\n"},
+ map[string]string{"package.json": `{"scripts": {"test": "echo ok"}}` + "\n"})
+ in := Input{Dir: dir, Base: sha, Change: &core.Change{Kind: core.Breaking}, Patch: &core.Patch{Diff: diff, Files: []string{"package.json"}},
+ Index: &index{dir: dir}, Commands: base}
+ for _, tt := range []struct {
+ name string
+ now core.Commands
+ flag string
+ check bool
+ }{
+ {"the same lines", base, "", false},
+ {"a test line changed", core.Commands{Install: []string{"npm ci"}, Test: []string{"echo ok"}}, `the patch changes the test lines from ["npm test"] to ["echo ok"]; the proof ran the first`, true},
+ } {
+ in.Detect = func() core.Commands { return tt.now }
+ vt, err := Check(context.Background(), in)
+ if err != nil {
+ t.Fatal(err)
+ }
+ listed := strings.Contains(strings.Join(vt.Checks, "\n"), "commands")
+ var flags []string
+ for _, f := range vt.Findings {
+ if f.Check == "commands" {
+ flags = append(flags, f.Msg)
+ }
+ }
+ if listed != tt.check || strings.Join(flags, "") != tt.flag {
+ t.Errorf("%s: checks %q, flags %q", tt.name, vt.Checks, flags)
+ }
+ if tt.check && vt.Verdict != "draft" {
+ t.Errorf("%s: verdict %s", tt.name, vt.Verdict)
+ }
+ }
+}
diff --git a/internal/vet/leftovers.go b/internal/vet/leftovers.go
index d3127d0..75b3ebf 100644
--- a/internal/vet/leftovers.go
+++ b/internal/vet/leftovers.go
@@ -18,6 +18,10 @@ func leftovers(ctx context.Context, p *pass) ([]core.Finding, string) {
if p.in.Patch.Decision {
return nil, "nothing was applied"
}
+ opt := p.in.applied()
+ if opt != nil && (opt.Stay || opt.ToName == "" && opt.Codemod == nil && len(ch.Deps) > 0 && opt.To == ch.Deps[0].Version) {
+ return nil, "the patch stays on the version in use"
+ }
if p.in.Index == nil {
return nil, "no scan index"
}
@@ -45,7 +49,7 @@ func leftovers(ctx context.Context, p *pass) ([]core.Finding, string) {
if slices.ContainsFunc(ch.Evidence, func(e core.Evidence) bool { return e.Source == "runtime" }) {
return warnedAgain(p)
}
- swap := ch.ToName != "" && len(ch.Deps) > 0
+ swap := (ch.ToName != "" || opt != nil && opt.ToName != "") && len(ch.Deps) > 0
if !swap && len(renames) == 0 && len(paths) == 0 && len(flds) == 0 {
return nil, na
}
diff --git a/internal/vet/questions.go b/internal/vet/questions.go
index 5c5ce74..7833dd8 100644
--- a/internal/vet/questions.go
+++ b/internal/vet/questions.go
@@ -210,16 +210,16 @@ func questionPrompt(p *pass, b batch) (string, map[int]string) {
return sb.String(), shown
}
-// upstream joins what the change quotes from upstream, its moves' included,
+// upstream joins what the change quotes from upstream, its batch's included,
// cut at notesChars.
func upstream(ch *core.Change) string {
if ch == nil {
return ""
}
all := []*core.Change{ch}
- if ch.Cleanup != nil {
- for i := range ch.Cleanup.Moves {
- all = append(all, &ch.Cleanup.Moves[i])
+ if ch.Batch != nil {
+ for i := range ch.Batch.Changes {
+ all = append(all, &ch.Batch.Changes[i])
}
}
var parts []string
diff --git a/internal/vet/questions_test.go b/internal/vet/questions_test.go
index e1fd57c..35d0840 100644
--- a/internal/vet/questions_test.go
+++ b/internal/vet/questions_test.go
@@ -120,7 +120,7 @@ func TestQuestions(t *testing.T) {
// What upstream said, what earlier checks verified and the new
// declarations go in the prompt; overlapping context is shown once.
- in.Change = &core.Change{Kind: core.Tidy, Cleanup: &core.Cleanup{Moves: []core.Change{{Evidence: []core.Evidence{{Title: "pay 1.4.0 is deprecated", Text: "charges.* was replaced by paymentIntents.*"}}}}}}
+ in.Change = &core.Change{Kind: core.First, Batch: &core.Batch{Changes: []core.Change{{Evidence: []core.Evidence{{Title: "pay 1.4.0 is deprecated", Text: "charges.* was replaced by paymentIntents.*"}}}}}}
in.Proof = &core.Proof{Patched: &core.Run{Pass: true}}
m = &quiz{}
in.Model = m
diff --git a/internal/vet/section.go b/internal/vet/section.go
index 20786eb..3426d4d 100644
--- a/internal/vet/section.go
+++ b/internal/vet/section.go
@@ -9,7 +9,8 @@ import (
// Verdict is reject when symbols, fields or scope found something left
// unresolved and the patched proof fails; draft when symbols, fields,
-// leftovers or lockfile left a flag, or the baseline already fails; else pass.
+// leftovers, lockfile or commands left a flag, or the baseline already
+// fails; else pass.
// Call it again after re-running the proof on a worktree that vetting changed.
func Verdict(v *core.Vetting, proof *core.Proof) string {
hard, soft := false, false
@@ -22,7 +23,7 @@ func Verdict(v *core.Vetting, proof *core.Proof) string {
hard = true
}
switch f.Check {
- case "symbols", "fields", "leftovers", "lockfile":
+ case "symbols", "fields", "leftovers", "lockfile", "commands":
soft = true
}
}
diff --git a/internal/vet/symbols.go b/internal/vet/symbols.go
index 70843d1..681ae68 100644
--- a/internal/vet/symbols.go
+++ b/internal/vet/symbols.go
@@ -189,7 +189,9 @@ var (
func (r *resolver) npm(names []string, s core.Site) (status, string, string) {
pkg, chain, ok := r.importOf(names, s)
if !ok {
- return unknown, "import not found", ""
+ // The call goes through a value the code made, such as an app a
+ // factory returned, whose members no export declares.
+ return none, "", ""
}
if len(chain) == 0 {
return none, "", ""
@@ -536,7 +538,7 @@ func goImports(file string) map[string]string {
func (r *resolver) pip(names []string, s core.Site) (status, string, string) {
mod, chain, ok := r.importOf(names, s)
if !ok {
- return unknown, "import not found", ""
+ return none, "", ""
}
if len(chain) == 0 {
return none, "", ""
diff --git a/internal/vet/vet.go b/internal/vet/vet.go
index c8c9cb5..3ec7a9b 100644
--- a/internal/vet/vet.go
+++ b/internal/vet/vet.go
@@ -26,26 +26,49 @@ type Input struct {
Fetch core.Fetcher
Spec *api.Doc // API changes: the provider's current spec, nil when it could not be loaded
Hosts []string // API changes: the provider's hosts, to find endpoint literals still in use
+ Option int // the option a maintainer picked, 0 for none
+ // Commands are the project's install, build and test lines as the base
+ // has them, which the proof ran; Detect reads them again from the
+ // patched worktree. Nil skips the question.
+ Commands core.Commands
+ Detect func() core.Commands
+}
+
+// applied is the option the patch carries: the maintainer's pick, else the
+// one tend took by its own rule, nil for none.
+func (in Input) applied() *core.Option {
+ ch, n := in.Change, in.Option
+ if n == 0 && ch.Choice != nil {
+ n = ch.Choice.N
+ }
+ if n < 1 || n > len(ch.Options) {
+ return nil
+ }
+ return &ch.Options[n-1]
}
// A check asks one question of the patch. It returns what it verified, or why
-// it could not run.
+// it could not run. A quiet check is left out of the list when it finds
+// nothing: its question rarely arises, and a line saying so on every PR is
+// noise.
type check struct {
- name string
- fn func(context.Context, *pass) (res []core.Finding, skip string)
+ name string
+ fn func(context.Context, *pass) (res []core.Finding, skip string)
+ quiet bool
}
// scope runs first, so no later check reports a file it reverts.
var checks = []check{
- {"scope", scope},
- {"symbols", symbols},
- {"fields", fields},
- {"leftovers", leftovers},
- {"lockfile", lockfile},
- {"debug", debug},
- {"comments", comments},
- {"dead", dead},
- {"question", questions},
+ {name: "scope", fn: scope},
+ {name: "symbols", fn: symbols},
+ {name: "fields", fn: fields},
+ {name: "leftovers", fn: leftovers},
+ {name: "lockfile", fn: lockfile},
+ {name: "debug", fn: debug},
+ {name: "comments", fn: comments},
+ {name: "commands", fn: commands, quiet: true},
+ {name: "dead", fn: dead},
+ {name: "question", fn: questions},
}
// pass is the state the checks share: the patch as a parsed diff, kept current
@@ -77,6 +100,9 @@ func Check(ctx context.Context, in Input) (*core.Vetting, error) {
for _, c := range checks {
p.note = ""
found, skip := c.fn(ctx, p)
+ if c.quiet && len(found) == 0 {
+ continue
+ }
switch {
case skip == na:
res.Checks = append(res.Checks, c.name+": "+na)
diff --git a/testdata/npmreg/@fixture/archive/1.0.0/index.js b/testdata/npmreg/@fixture/archive/1.0.0/index.js
new file mode 100644
index 0000000..15cbd28
--- /dev/null
+++ b/testdata/npmreg/@fixture/archive/1.0.0/index.js
@@ -0,0 +1,3 @@
+'use strict'
+
+exports.pack = (s) => String(s)
diff --git a/testdata/npmreg/@fixture/archive/1.0.0/package.json b/testdata/npmreg/@fixture/archive/1.0.0/package.json
new file mode 100644
index 0000000..4a1e6f9
--- /dev/null
+++ b/testdata/npmreg/@fixture/archive/1.0.0/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "@fixture/archive",
+ "version": "1.0.0",
+ "main": "index.js",
+ "license": "MIT"
+}
diff --git a/testdata/npmreg/@fixture/archive/1.1.0/index.js b/testdata/npmreg/@fixture/archive/1.1.0/index.js
new file mode 100644
index 0000000..d8f8469
--- /dev/null
+++ b/testdata/npmreg/@fixture/archive/1.1.0/index.js
@@ -0,0 +1,3 @@
+'use strict'
+
+exports.pack = (s) => String(s).replace(/\.\.\//g, '')
diff --git a/testdata/npmreg/@fixture/archive/1.1.0/package.json b/testdata/npmreg/@fixture/archive/1.1.0/package.json
new file mode 100644
index 0000000..4fb1e6f
--- /dev/null
+++ b/testdata/npmreg/@fixture/archive/1.1.0/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "@fixture/archive",
+ "version": "1.1.0",
+ "main": "index.js",
+ "license": "MIT"
+}
diff --git a/testdata/npmreg/@fixture/archive/1.1.1/index.js b/testdata/npmreg/@fixture/archive/1.1.1/index.js
new file mode 100644
index 0000000..d8f8469
--- /dev/null
+++ b/testdata/npmreg/@fixture/archive/1.1.1/index.js
@@ -0,0 +1,3 @@
+'use strict'
+
+exports.pack = (s) => String(s).replace(/\.\.\//g, '')
diff --git a/testdata/npmreg/@fixture/archive/1.1.1/package.json b/testdata/npmreg/@fixture/archive/1.1.1/package.json
new file mode 100644
index 0000000..cb9da90
--- /dev/null
+++ b/testdata/npmreg/@fixture/archive/1.1.1/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "@fixture/archive",
+ "version": "1.1.1",
+ "main": "index.js",
+ "license": "MIT"
+}
diff --git a/testdata/npmreg/@fixture/archive/meta.json b/testdata/npmreg/@fixture/archive/meta.json
new file mode 100644
index 0000000..0857460
--- /dev/null
+++ b/testdata/npmreg/@fixture/archive/meta.json
@@ -0,0 +1,13 @@
+{
+ "name": "@fixture/archive",
+ "dist-tags": {
+ "latest": "1.1.1"
+ },
+ "time": {
+ "created": "2025-06-01T09:00:00.000Z",
+ "modified": "2026-10-16T09:00:00.000Z",
+ "1.0.0": "2025-06-01T09:00:00.000Z",
+ "1.1.0": "2026-10-12T09:00:00.000Z",
+ "1.1.1": "2026-10-16T09:00:00.000Z"
+ }
+}
diff --git a/testdata/npmreg/@fixture/format/1.1.0/index.js b/testdata/npmreg/@fixture/format/1.1.0/index.js
new file mode 100644
index 0000000..ab4f380
--- /dev/null
+++ b/testdata/npmreg/@fixture/format/1.1.0/index.js
@@ -0,0 +1,3 @@
+'use strict'
+
+exports.money = (n) => '$' + Number(n).toFixed(2)
diff --git a/testdata/npmreg/@fixture/format/1.1.0/package.json b/testdata/npmreg/@fixture/format/1.1.0/package.json
new file mode 100644
index 0000000..fe16d2c
--- /dev/null
+++ b/testdata/npmreg/@fixture/format/1.1.0/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "@fixture/format",
+ "version": "1.1.0",
+ "main": "index.js",
+ "license": "MIT"
+}
diff --git a/testdata/npmreg/@fixture/format/1.1.1/index.js b/testdata/npmreg/@fixture/format/1.1.1/index.js
new file mode 100644
index 0000000..f40ab62
--- /dev/null
+++ b/testdata/npmreg/@fixture/format/1.1.1/index.js
@@ -0,0 +1,3 @@
+'use strict'
+
+exports.money = (n) => 'USD ' + Number(n).toFixed(2)
diff --git a/testdata/npmreg/@fixture/format/1.1.1/package.json b/testdata/npmreg/@fixture/format/1.1.1/package.json
new file mode 100644
index 0000000..92f9208
--- /dev/null
+++ b/testdata/npmreg/@fixture/format/1.1.1/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "@fixture/format",
+ "version": "1.1.1",
+ "main": "index.js",
+ "license": "MIT"
+}
diff --git a/testdata/npmreg/@fixture/format/meta.json b/testdata/npmreg/@fixture/format/meta.json
new file mode 100644
index 0000000..430640d
--- /dev/null
+++ b/testdata/npmreg/@fixture/format/meta.json
@@ -0,0 +1,12 @@
+{
+ "name": "@fixture/format",
+ "dist-tags": {
+ "latest": "1.1.1"
+ },
+ "time": {
+ "created": "2025-06-01T09:00:00.000Z",
+ "modified": "2026-10-14T09:00:00.000Z",
+ "1.1.0": "2025-06-01T09:00:00.000Z",
+ "1.1.1": "2026-10-14T09:00:00.000Z"
+ }
+}
diff --git a/testdata/npmreg/@fixture/parser/1.0.0/index.js b/testdata/npmreg/@fixture/parser/1.0.0/index.js
new file mode 100644
index 0000000..a4642a6
--- /dev/null
+++ b/testdata/npmreg/@fixture/parser/1.0.0/index.js
@@ -0,0 +1,5 @@
+'use strict'
+
+const { pack } = require('@fixture/archive')
+
+exports.parse = (s) => ({ amount: Number(s), raw: pack(s) })
diff --git a/testdata/npmreg/@fixture/parser/1.0.0/package.json b/testdata/npmreg/@fixture/parser/1.0.0/package.json
new file mode 100644
index 0000000..3a0a873
--- /dev/null
+++ b/testdata/npmreg/@fixture/parser/1.0.0/package.json
@@ -0,0 +1,9 @@
+{
+ "name": "@fixture/parser",
+ "version": "1.0.0",
+ "main": "index.js",
+ "license": "MIT",
+ "dependencies": {
+ "@fixture/archive": "^1.0.0"
+ }
+}
diff --git a/testdata/npmreg/@fixture/parser/1.0.1/index.js b/testdata/npmreg/@fixture/parser/1.0.1/index.js
new file mode 100644
index 0000000..13287d0
--- /dev/null
+++ b/testdata/npmreg/@fixture/parser/1.0.1/index.js
@@ -0,0 +1,8 @@
+'use strict'
+
+const { pack } = require('@fixture/archive')
+
+exports.parse = (s) => {
+ if (typeof s !== 'string') throw new TypeError('parse needs a string')
+ return { amount: Number(s), raw: pack(s) }
+}
diff --git a/testdata/npmreg/@fixture/parser/1.0.1/package.json b/testdata/npmreg/@fixture/parser/1.0.1/package.json
new file mode 100644
index 0000000..535b993
--- /dev/null
+++ b/testdata/npmreg/@fixture/parser/1.0.1/package.json
@@ -0,0 +1,9 @@
+{
+ "name": "@fixture/parser",
+ "version": "1.0.1",
+ "main": "index.js",
+ "license": "MIT",
+ "dependencies": {
+ "@fixture/archive": "^1.0.0"
+ }
+}
diff --git a/testdata/npmreg/@fixture/parser/meta.json b/testdata/npmreg/@fixture/parser/meta.json
new file mode 100644
index 0000000..a70caf4
--- /dev/null
+++ b/testdata/npmreg/@fixture/parser/meta.json
@@ -0,0 +1,12 @@
+{
+ "name": "@fixture/parser",
+ "dist-tags": {
+ "latest": "1.0.1"
+ },
+ "time": {
+ "created": "2025-06-01T09:00:00.000Z",
+ "modified": "2026-10-15T09:00:00.000Z",
+ "1.0.0": "2025-06-01T09:00:00.000Z",
+ "1.0.1": "2026-10-15T09:00:00.000Z"
+ }
+}
diff --git a/testdata/npmreg/@fixture/web/1.0.0/index.js b/testdata/npmreg/@fixture/web/1.0.0/index.js
new file mode 100644
index 0000000..edf6633
--- /dev/null
+++ b/testdata/npmreg/@fixture/web/1.0.0/index.js
@@ -0,0 +1,16 @@
+'use strict'
+
+function web() {
+ const routes = {}
+ const settings = {}
+ return {
+ configure(fn) { fn() },
+ set(key, value) { settings[key] = value },
+ get(path, handler) { routes[path] = handler },
+ handle(path, query) { return routes[path](query) },
+ }
+}
+
+web.createServer = (app) => ({ app, close() {} })
+
+module.exports = web
diff --git a/testdata/npmreg/@fixture/web/1.0.0/package.json b/testdata/npmreg/@fixture/web/1.0.0/package.json
new file mode 100644
index 0000000..d308e66
--- /dev/null
+++ b/testdata/npmreg/@fixture/web/1.0.0/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "@fixture/web",
+ "version": "1.0.0",
+ "main": "index.js",
+ "license": "MIT"
+}
diff --git a/testdata/npmreg/@fixture/web/2.0.0/index.js b/testdata/npmreg/@fixture/web/2.0.0/index.js
new file mode 100644
index 0000000..674b4b0
--- /dev/null
+++ b/testdata/npmreg/@fixture/web/2.0.0/index.js
@@ -0,0 +1,15 @@
+'use strict'
+
+function web() {
+ const routes = {}
+ const settings = {}
+ return {
+ set(key, value) { settings[key] = value },
+ get(path, handler) { routes[path] = handler },
+ handle(path, query) { return routes[path](query) },
+ }
+}
+
+web.createServer = (app) => ({ app, close() {} })
+
+module.exports = web
diff --git a/testdata/npmreg/@fixture/web/2.0.0/package.json b/testdata/npmreg/@fixture/web/2.0.0/package.json
new file mode 100644
index 0000000..6bab506
--- /dev/null
+++ b/testdata/npmreg/@fixture/web/2.0.0/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "@fixture/web",
+ "version": "2.0.0",
+ "main": "index.js",
+ "license": "MIT"
+}
diff --git a/testdata/npmreg/@fixture/web/3.0.0/index.js b/testdata/npmreg/@fixture/web/3.0.0/index.js
new file mode 100644
index 0000000..45f0ca0
--- /dev/null
+++ b/testdata/npmreg/@fixture/web/3.0.0/index.js
@@ -0,0 +1,15 @@
+'use strict'
+
+function web() {
+ const routes = {}
+ const settings = {}
+ const app = {
+ set(key, value) { settings[key] = value },
+ get(path, handler) { routes[path] = handler },
+ handle(path, query) { return routes[path](query) },
+ createServer() { return { app, close() {} } },
+ }
+ return app
+}
+
+module.exports = web
diff --git a/testdata/npmreg/@fixture/web/3.0.0/package.json b/testdata/npmreg/@fixture/web/3.0.0/package.json
new file mode 100644
index 0000000..998fc9f
--- /dev/null
+++ b/testdata/npmreg/@fixture/web/3.0.0/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "@fixture/web",
+ "version": "3.0.0",
+ "main": "index.js",
+ "license": "MIT"
+}
diff --git a/testdata/npmreg/@fixture/web/meta.json b/testdata/npmreg/@fixture/web/meta.json
new file mode 100644
index 0000000..1c0bca5
--- /dev/null
+++ b/testdata/npmreg/@fixture/web/meta.json
@@ -0,0 +1,13 @@
+{
+ "name": "@fixture/web",
+ "dist-tags": {
+ "latest": "3.0.0"
+ },
+ "time": {
+ "created": "2012-03-01T09:00:00.000Z",
+ "modified": "2025-05-01T09:00:00.000Z",
+ "1.0.0": "2012-03-01T09:00:00.000Z",
+ "2.0.0": "2016-04-01T09:00:00.000Z",
+ "3.0.0": "2025-05-01T09:00:00.000Z"
+ }
+}
diff --git a/testdata/npmreg/axios/1.12.2/index.js b/testdata/npmreg/axios/1.12.2/index.js
new file mode 100644
index 0000000..74c954d
--- /dev/null
+++ b/testdata/npmreg/axios/1.12.2/index.js
@@ -0,0 +1,6 @@
+'use strict'
+
+exports.get = async (url) => {
+ const res = await fetch(url)
+ return { status: res.status, data: JSON.parse(await res.text()) }
+}
diff --git a/testdata/npmreg/axios/1.12.2/package.json b/testdata/npmreg/axios/1.12.2/package.json
new file mode 100644
index 0000000..bab2576
--- /dev/null
+++ b/testdata/npmreg/axios/1.12.2/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "axios",
+ "version": "1.12.2",
+ "main": "index.js",
+ "license": "MIT"
+}
diff --git a/testdata/npmreg/axios/meta.json b/testdata/npmreg/axios/meta.json
new file mode 100644
index 0000000..2b6a749
--- /dev/null
+++ b/testdata/npmreg/axios/meta.json
@@ -0,0 +1,11 @@
+{
+ "name": "axios",
+ "dist-tags": {
+ "latest": "1.12.2"
+ },
+ "time": {
+ "created": "2014-08-29T09:00:00.000Z",
+ "modified": "2025-09-14T09:00:00.000Z",
+ "1.12.2": "2025-09-14T09:00:00.000Z"
+ }
+}
diff --git a/testdata/npmreg/node-fetch/2.7.0/index.js b/testdata/npmreg/node-fetch/2.7.0/index.js
new file mode 100644
index 0000000..ee1d9ec
--- /dev/null
+++ b/testdata/npmreg/node-fetch/2.7.0/index.js
@@ -0,0 +1,3 @@
+'use strict'
+
+module.exports = (url, init) => fetch(url, init)
diff --git a/testdata/npmreg/node-fetch/2.7.0/package.json b/testdata/npmreg/node-fetch/2.7.0/package.json
new file mode 100644
index 0000000..4251bad
--- /dev/null
+++ b/testdata/npmreg/node-fetch/2.7.0/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "node-fetch",
+ "version": "2.7.0",
+ "main": "index.js",
+ "license": "MIT"
+}
diff --git a/testdata/npmreg/node-fetch/3.3.2/index.js b/testdata/npmreg/node-fetch/3.3.2/index.js
new file mode 100644
index 0000000..ee1d9ec
--- /dev/null
+++ b/testdata/npmreg/node-fetch/3.3.2/index.js
@@ -0,0 +1,3 @@
+'use strict'
+
+module.exports = (url, init) => fetch(url, init)
diff --git a/testdata/npmreg/node-fetch/3.3.2/package.json b/testdata/npmreg/node-fetch/3.3.2/package.json
new file mode 100644
index 0000000..f889a7a
--- /dev/null
+++ b/testdata/npmreg/node-fetch/3.3.2/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "node-fetch",
+ "version": "3.3.2",
+ "main": "index.js",
+ "license": "MIT"
+}
diff --git a/testdata/npmreg/node-fetch/meta.json b/testdata/npmreg/node-fetch/meta.json
new file mode 100644
index 0000000..6a90925
--- /dev/null
+++ b/testdata/npmreg/node-fetch/meta.json
@@ -0,0 +1,12 @@
+{
+ "name": "node-fetch",
+ "dist-tags": {
+ "latest": "3.3.2"
+ },
+ "time": {
+ "created": "2015-01-27T09:00:00.000Z",
+ "modified": "2023-07-25T09:00:00.000Z",
+ "2.7.0": "2023-08-23T09:00:00.000Z",
+ "3.3.2": "2023-07-25T09:00:00.000Z"
+ }
+}
diff --git a/testdata/npmreg/request/2.88.2/index.js b/testdata/npmreg/request/2.88.2/index.js
new file mode 100644
index 0000000..9bcc84f
--- /dev/null
+++ b/testdata/npmreg/request/2.88.2/index.js
@@ -0,0 +1,5 @@
+'use strict'
+
+exports.get = (url, cb) => {
+ fetch(url).then((res) => res.text().then((body) => cb(null, { statusCode: res.status }, body)), cb)
+}
diff --git a/testdata/npmreg/request/2.88.2/package.json b/testdata/npmreg/request/2.88.2/package.json
new file mode 100644
index 0000000..1a232e5
--- /dev/null
+++ b/testdata/npmreg/request/2.88.2/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "request",
+ "version": "2.88.2",
+ "main": "index.js",
+ "license": "Apache-2.0"
+}
diff --git a/testdata/npmreg/request/meta.json b/testdata/npmreg/request/meta.json
new file mode 100644
index 0000000..721b13c
--- /dev/null
+++ b/testdata/npmreg/request/meta.json
@@ -0,0 +1,14 @@
+{
+ "name": "request",
+ "dist-tags": {
+ "latest": "2.88.2"
+ },
+ "time": {
+ "created": "2011-01-28T09:00:00.000Z",
+ "modified": "2020-02-11T09:00:00.000Z",
+ "2.88.2": "2020-02-11T09:00:00.000Z"
+ },
+ "deprecated": {
+ "2.88.2": "request has been deprecated, see https://github.com/request/request/issues/3142"
+ }
+}
diff --git a/testdata/npmreg/undici/7.16.0/index.js b/testdata/npmreg/undici/7.16.0/index.js
new file mode 100644
index 0000000..cddca4c
--- /dev/null
+++ b/testdata/npmreg/undici/7.16.0/index.js
@@ -0,0 +1,7 @@
+'use strict'
+
+exports.request = async (url) => {
+ const res = await fetch(url)
+ const text = await res.text()
+ return { statusCode: res.status, body: { text: async () => text, json: async () => JSON.parse(text) } }
+}
diff --git a/testdata/npmreg/undici/7.16.0/package.json b/testdata/npmreg/undici/7.16.0/package.json
new file mode 100644
index 0000000..0a05c26
--- /dev/null
+++ b/testdata/npmreg/undici/7.16.0/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "undici",
+ "version": "7.16.0",
+ "main": "index.js",
+ "license": "MIT"
+}
diff --git a/testdata/npmreg/undici/meta.json b/testdata/npmreg/undici/meta.json
new file mode 100644
index 0000000..5c84880
--- /dev/null
+++ b/testdata/npmreg/undici/meta.json
@@ -0,0 +1,11 @@
+{
+ "name": "undici",
+ "dist-tags": {
+ "latest": "7.16.0"
+ },
+ "time": {
+ "created": "2018-03-01T09:00:00.000Z",
+ "modified": "2025-09-01T09:00:00.000Z",
+ "7.16.0": "2025-09-01T09:00:00.000Z"
+ }
+}
diff --git a/testdata/projects/node-catchup/.eslintrc.json b/testdata/projects/node-catchup/.eslintrc.json
new file mode 100644
index 0000000..fbf2792
--- /dev/null
+++ b/testdata/projects/node-catchup/.eslintrc.json
@@ -0,0 +1,4 @@
+{
+ "root": true,
+ "plugins": ["fixture"]
+}
diff --git a/testdata/projects/node-catchup/.gitignore b/testdata/projects/node-catchup/.gitignore
new file mode 100644
index 0000000..c2658d7
--- /dev/null
+++ b/testdata/projects/node-catchup/.gitignore
@@ -0,0 +1 @@
+node_modules/
diff --git a/testdata/projects/node-catchup/.npmrc b/testdata/projects/node-catchup/.npmrc
new file mode 100644
index 0000000..12c177e
--- /dev/null
+++ b/testdata/projects/node-catchup/.npmrc
@@ -0,0 +1 @@
+registry={{registry}}
diff --git a/testdata/projects/node-catchup/package-lock.json b/testdata/projects/node-catchup/package-lock.json
new file mode 100644
index 0000000..5d327f4
--- /dev/null
+++ b/testdata/projects/node-catchup/package-lock.json
@@ -0,0 +1,113 @@
+{
+ "name": "node-catchup",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "node-catchup",
+ "version": "1.0.0",
+ "dependencies": {
+ "@fixture/colors": "^1.0.0",
+ "@fixture/format": "^1.1.0",
+ "@fixture/parser": "^1.0.0",
+ "@fixture/pay": "^1.4.0",
+ "@fixture/plugin-host": "^1.0.0",
+ "@fixture/runtime": "^1.0.0",
+ "@fixture/strings": "^1.0.0"
+ },
+ "devDependencies": {
+ "@fixture/linter": "^1.0.0",
+ "@fixture/old-test-helper": "^1.0.0",
+ "@types/fixture__pay": "^1.0.0",
+ "eslint-plugin-fixture": "^1.0.0"
+ }
+ },
+ "node_modules/@fixture/archive": {
+ "version": "1.0.0",
+ "resolved": "{{registry}}@fixture/archive/-/archive-1.0.0.tgz",
+ "integrity": "{{integrity @fixture/archive@1.0.0}}",
+ "license": "MIT"
+ },
+ "node_modules/@fixture/colors": {
+ "version": "1.0.0",
+ "resolved": "{{registry}}@fixture/colors/-/colors-1.0.0.tgz",
+ "integrity": "{{integrity @fixture/colors@1.0.0}}",
+ "license": "MIT"
+ },
+ "node_modules/@fixture/format": {
+ "version": "1.1.0",
+ "resolved": "{{registry}}@fixture/format/-/format-1.1.0.tgz",
+ "integrity": "{{integrity @fixture/format@1.1.0}}",
+ "license": "MIT"
+ },
+ "node_modules/@fixture/linter": {
+ "version": "1.0.0",
+ "resolved": "{{registry}}@fixture/linter/-/linter-1.0.0.tgz",
+ "integrity": "{{integrity @fixture/linter@1.0.0}}",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "fixture-lint": "cli.js"
+ }
+ },
+ "node_modules/@fixture/old-test-helper": {
+ "version": "1.0.0",
+ "resolved": "{{registry}}@fixture/old-test-helper/-/old-test-helper-1.0.0.tgz",
+ "integrity": "{{integrity @fixture/old-test-helper@1.0.0}}",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@fixture/parser": {
+ "version": "1.0.0",
+ "resolved": "{{registry}}@fixture/parser/-/parser-1.0.0.tgz",
+ "integrity": "{{integrity @fixture/parser@1.0.0}}",
+ "license": "MIT",
+ "dependencies": {
+ "@fixture/archive": "^1.0.0"
+ }
+ },
+ "node_modules/@fixture/pay": {
+ "version": "1.4.0",
+ "resolved": "{{registry}}@fixture/pay/-/pay-1.4.0.tgz",
+ "integrity": "{{integrity @fixture/pay@1.4.0}}",
+ "deprecated": "1.x is deprecated, use 2.x: charges.* was replaced by paymentIntents.*",
+ "license": "MIT"
+ },
+ "node_modules/@fixture/plugin-host": {
+ "version": "1.0.0",
+ "resolved": "{{registry}}@fixture/plugin-host/-/plugin-host-1.0.0.tgz",
+ "integrity": "{{integrity @fixture/plugin-host@1.0.0}}",
+ "license": "MIT",
+ "peerDependencies": {
+ "@fixture/runtime": "^1.0.0"
+ }
+ },
+ "node_modules/@fixture/runtime": {
+ "version": "1.0.0",
+ "resolved": "{{registry}}@fixture/runtime/-/runtime-1.0.0.tgz",
+ "integrity": "{{integrity @fixture/runtime@1.0.0}}",
+ "license": "MIT"
+ },
+ "node_modules/@fixture/strings": {
+ "version": "1.0.0",
+ "resolved": "{{registry}}@fixture/strings/-/strings-1.0.0.tgz",
+ "integrity": "{{integrity @fixture/strings@1.0.0}}",
+ "license": "MIT"
+ },
+ "node_modules/@types/fixture__pay": {
+ "version": "1.0.0",
+ "resolved": "{{registry}}@types/fixture__pay/-/fixture__pay-1.0.0.tgz",
+ "integrity": "{{integrity @types/fixture__pay@1.0.0}}",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/eslint-plugin-fixture": {
+ "version": "1.0.0",
+ "resolved": "{{registry}}eslint-plugin-fixture/-/eslint-plugin-fixture-1.0.0.tgz",
+ "integrity": "{{integrity eslint-plugin-fixture@1.0.0}}",
+ "dev": true,
+ "license": "MIT"
+ }
+ }
+}
diff --git a/testdata/projects/node-catchup/package.json b/testdata/projects/node-catchup/package.json
new file mode 100644
index 0000000..00cebbb
--- /dev/null
+++ b/testdata/projects/node-catchup/package.json
@@ -0,0 +1,24 @@
+{
+ "name": "node-catchup",
+ "version": "1.0.0",
+ "private": true,
+ "scripts": {
+ "test": "node --test",
+ "lint": "fixture-lint src"
+ },
+ "dependencies": {
+ "@fixture/colors": "^1.0.0",
+ "@fixture/format": "^1.1.0",
+ "@fixture/parser": "^1.0.0",
+ "@fixture/pay": "^1.4.0",
+ "@fixture/plugin-host": "^1.0.0",
+ "@fixture/runtime": "^1.0.0",
+ "@fixture/strings": "^1.0.0"
+ },
+ "devDependencies": {
+ "@fixture/linter": "^1.0.0",
+ "@fixture/old-test-helper": "^1.0.0",
+ "@types/fixture__pay": "^1.0.0",
+ "eslint-plugin-fixture": "^1.0.0"
+ }
+}
diff --git a/testdata/projects/node-catchup/src/billing.js b/testdata/projects/node-catchup/src/billing.js
new file mode 100644
index 0000000..f8272fb
--- /dev/null
+++ b/testdata/projects/node-catchup/src/billing.js
@@ -0,0 +1,23 @@
+'use strict'
+
+const pay = require('@fixture/pay')
+
+function cents(dollars) {
+ return Math.round(dollars * 100)
+}
+
+async function charge(dollars, customer) {
+ const amount = cents(dollars)
+ if (amount <= 0) throw new RangeError('nothing to charge')
+ return pay.charges.create({ amount, currency: 'usd', customer })
+}
+
+async function lookup(id) {
+ if (typeof id !== 'string' || id === '') {
+ throw new TypeError('lookup needs an id')
+ }
+
+ return pay.charges.retrieve(id)
+}
+
+module.exports = { charge, lookup }
diff --git a/testdata/projects/node-catchup/src/plugins.js b/testdata/projects/node-catchup/src/plugins.js
new file mode 100644
index 0000000..f2b9f7f
--- /dev/null
+++ b/testdata/projects/node-catchup/src/plugins.js
@@ -0,0 +1,5 @@
+'use strict'
+
+const host = require('@fixture/plugin-host')
+
+module.exports = () => host.load(['audit'])
diff --git a/testdata/projects/node-catchup/src/report.js b/testdata/projects/node-catchup/src/report.js
new file mode 100644
index 0000000..3e6b4ca
--- /dev/null
+++ b/testdata/projects/node-catchup/src/report.js
@@ -0,0 +1,6 @@
+'use strict'
+
+const { parse } = require('@fixture/parser')
+const { money } = require('@fixture/format')
+
+module.exports = (s) => money(parse(s).amount)
diff --git a/testdata/projects/node-catchup/test/billing.test.js b/testdata/projects/node-catchup/test/billing.test.js
new file mode 100644
index 0000000..bd6687d
--- /dev/null
+++ b/testdata/projects/node-catchup/test/billing.test.js
@@ -0,0 +1,33 @@
+'use strict'
+
+const test = require('node:test')
+const assert = require('node:assert')
+const { charge, lookup } = require('../src/billing')
+
+function stub() {
+ const calls = []
+ globalThis.fetch = async (url, init) => {
+ calls.push({ url, method: init.method, body: init.body && JSON.parse(init.body) })
+ return { ok: true, status: 200, json: async () => ({ id: 'pay_1', amount: 500 }) }
+ }
+ return calls
+}
+
+test('charge sends the amount in cents', async () => {
+ const calls = stub()
+ assert.deepStrictEqual(await charge(5, 'cus_1'), { id: 'pay_1', amount: 500 })
+ assert.strictEqual(calls[0].method, 'POST')
+ assert.strictEqual(calls[0].body.amount, 500)
+ assert.strictEqual(calls[0].body.customer, 'cus_1')
+})
+
+test('lookup asks for one payment', async () => {
+ const calls = stub()
+ await lookup('pay_1')
+ assert.strictEqual(calls[0].method, 'GET')
+ assert.match(calls[0].url, /\/pay_1$/)
+})
+
+test('lookup needs an id', async () => {
+ await assert.rejects(lookup(''), TypeError)
+})
diff --git a/testdata/projects/node-catchup/test/report.test.js b/testdata/projects/node-catchup/test/report.test.js
new file mode 100644
index 0000000..63eafab
--- /dev/null
+++ b/testdata/projects/node-catchup/test/report.test.js
@@ -0,0 +1,9 @@
+'use strict'
+
+const test = require('node:test')
+const assert = require('node:assert')
+const report = require('../src/report')
+
+test('reports an amount in dollars', () => {
+ assert.strictEqual(report('5'), '$5.00')
+})
diff --git a/testdata/projects/node-legacy/.gitignore b/testdata/projects/node-legacy/.gitignore
new file mode 100644
index 0000000..c2658d7
--- /dev/null
+++ b/testdata/projects/node-legacy/.gitignore
@@ -0,0 +1 @@
+node_modules/
diff --git a/testdata/projects/node-legacy/.npmrc b/testdata/projects/node-legacy/.npmrc
new file mode 100644
index 0000000..12c177e
--- /dev/null
+++ b/testdata/projects/node-legacy/.npmrc
@@ -0,0 +1 @@
+registry={{registry}}
diff --git a/testdata/projects/node-legacy/.nvmrc b/testdata/projects/node-legacy/.nvmrc
new file mode 100644
index 0000000..5b341fd
--- /dev/null
+++ b/testdata/projects/node-legacy/.nvmrc
@@ -0,0 +1 @@
+4.9.1
diff --git a/testdata/projects/node-legacy/package-lock.json b/testdata/projects/node-legacy/package-lock.json
new file mode 100644
index 0000000..c8fab6b
--- /dev/null
+++ b/testdata/projects/node-legacy/package-lock.json
@@ -0,0 +1,55 @@
+{
+ "name": "legacy-shop",
+ "version": "0.3.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "legacy-shop",
+ "version": "0.3.0",
+ "dependencies": {
+ "@fixture/colors": "^1.0.0",
+ "@fixture/parser": "^1.0.0",
+ "@fixture/web": "^1.0.0",
+ "request": "^2.88.2"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/@fixture/archive": {
+ "version": "1.0.0",
+ "resolved": "{{registry}}@fixture/archive/-/archive-1.0.0.tgz",
+ "integrity": "{{integrity @fixture/archive@1.0.0}}",
+ "license": "MIT"
+ },
+ "node_modules/@fixture/colors": {
+ "version": "1.0.0",
+ "resolved": "{{registry}}@fixture/colors/-/colors-1.0.0.tgz",
+ "integrity": "{{integrity @fixture/colors@1.0.0}}",
+ "license": "MIT"
+ },
+ "node_modules/@fixture/parser": {
+ "version": "1.0.0",
+ "resolved": "{{registry}}@fixture/parser/-/parser-1.0.0.tgz",
+ "integrity": "{{integrity @fixture/parser@1.0.0}}",
+ "license": "MIT",
+ "dependencies": {
+ "@fixture/archive": "^1.0.0"
+ }
+ },
+ "node_modules/@fixture/web": {
+ "version": "1.0.0",
+ "resolved": "{{registry}}@fixture/web/-/web-1.0.0.tgz",
+ "integrity": "{{integrity @fixture/web@1.0.0}}",
+ "license": "MIT"
+ },
+ "node_modules/request": {
+ "version": "2.88.2",
+ "resolved": "{{registry}}request/-/request-2.88.2.tgz",
+ "integrity": "{{integrity request@2.88.2}}",
+ "deprecated": "request has been deprecated, see https://github.com/request/request/issues/3142",
+ "license": "Apache-2.0"
+ }
+ }
+}
diff --git a/testdata/projects/node-legacy/package.json b/testdata/projects/node-legacy/package.json
new file mode 100644
index 0000000..72a2f7f
--- /dev/null
+++ b/testdata/projects/node-legacy/package.json
@@ -0,0 +1,15 @@
+{
+ "name": "legacy-shop",
+ "version": "0.3.0",
+ "private": true,
+ "main": "src/app.js",
+ "engines": {
+ "node": ">=4"
+ },
+ "dependencies": {
+ "@fixture/colors": "^1.0.0",
+ "@fixture/parser": "^1.0.0",
+ "@fixture/web": "^1.0.0",
+ "request": "^2.88.2"
+ }
+}
diff --git a/testdata/projects/node-legacy/src/app.js b/testdata/projects/node-legacy/src/app.js
new file mode 100644
index 0000000..bd8f784
--- /dev/null
+++ b/testdata/projects/node-legacy/src/app.js
@@ -0,0 +1,24 @@
+'use strict'
+
+var web = require('@fixture/web')
+var order = require('./order')
+
+var app = web()
+
+app.configure(function () {
+ app.set('name', 'legacy-shop')
+})
+
+app.get('/health', function () {
+ return 'ok'
+})
+
+app.get('/order', function (query) {
+ return order.read(query).amount
+})
+
+module.exports = app
+
+module.exports.server = function () {
+ return web.createServer(app)
+}
diff --git a/testdata/projects/node-legacy/src/client.js b/testdata/projects/node-legacy/src/client.js
new file mode 100644
index 0000000..52db2a2
--- /dev/null
+++ b/testdata/projects/node-legacy/src/client.js
@@ -0,0 +1,10 @@
+'use strict'
+
+var request = require('request')
+
+exports.price = function (sku, cb) {
+ request.get('https://prices.example.test/v1/' + sku, function (err, res, body) {
+ if (err) return cb(err)
+ cb(null, JSON.parse(body).cents)
+ })
+}
diff --git a/testdata/projects/node-legacy/src/order.js b/testdata/projects/node-legacy/src/order.js
new file mode 100644
index 0000000..f7042af
--- /dev/null
+++ b/testdata/projects/node-legacy/src/order.js
@@ -0,0 +1,7 @@
+'use strict'
+
+var parser = require('@fixture/parser')
+
+exports.read = function (query) {
+ return parser.parse(query)
+}
diff --git a/testdata/recorded/e2e/osv/GHSA-2c8f-9v3w-4hq7.json b/testdata/recorded/e2e/osv/GHSA-2c8f-9v3w-4hq7.json
new file mode 100644
index 0000000..0ca538e
--- /dev/null
+++ b/testdata/recorded/e2e/osv/GHSA-2c8f-9v3w-4hq7.json
@@ -0,0 +1,14 @@
+{
+ "id": "GHSA-2c8f-9v3w-4hq7",
+ "summary": "Path traversal in pack",
+ "details": "pack keeps ../ in the names it writes, so an archive can write outside the directory it is unpacked into. 1.1.0 strips it.",
+ "published": "2026-10-17T12:00:00Z",
+ "modified": "2026-10-17T12:00:00Z",
+ "database_specific": {"severity": "HIGH"},
+ "affected": [
+ {
+ "package": {"name": "@fixture/archive", "ecosystem": "npm"},
+ "ranges": [{"type": "SEMVER", "events": [{"introduced": "0"}, {"fixed": "1.1.0"}]}]
+ }
+ ]
+}
diff --git a/testdata/recorded/e2e/osv/GHSA-3m7x-8p2r-6fjw.json b/testdata/recorded/e2e/osv/GHSA-3m7x-8p2r-6fjw.json
new file mode 100644
index 0000000..c257df4
--- /dev/null
+++ b/testdata/recorded/e2e/osv/GHSA-3m7x-8p2r-6fjw.json
@@ -0,0 +1,14 @@
+{
+ "id": "GHSA-3m7x-8p2r-6fjw",
+ "summary": "Prototype pollution in parse",
+ "details": "parse copies __proto__ keys from its input onto the result. 1.0.1 checks its input.",
+ "published": "2026-10-17T12:00:00Z",
+ "modified": "2026-10-17T12:00:00Z",
+ "database_specific": {"severity": "MODERATE"},
+ "affected": [
+ {
+ "package": {"name": "@fixture/parser", "ecosystem": "npm"},
+ "ranges": [{"type": "SEMVER", "events": [{"introduced": "0"}, {"fixed": "1.0.1"}]}]
+ }
+ ]
+}
diff --git a/testdata/recorded/e2e/osv/GHSA-4q9w-7h3c-5vrx.json b/testdata/recorded/e2e/osv/GHSA-4q9w-7h3c-5vrx.json
new file mode 100644
index 0000000..bca419d
--- /dev/null
+++ b/testdata/recorded/e2e/osv/GHSA-4q9w-7h3c-5vrx.json
@@ -0,0 +1,14 @@
+{
+ "id": "GHSA-4q9w-7h3c-5vrx",
+ "summary": "Format string injection in money",
+ "details": "money passes its input to a format string. 1.1.1 changes the output it writes.",
+ "published": "2026-10-17T12:00:00Z",
+ "modified": "2026-10-17T12:00:00Z",
+ "database_specific": {"severity": "LOW"},
+ "affected": [
+ {
+ "package": {"name": "@fixture/format", "ecosystem": "npm"},
+ "ranges": [{"type": "SEMVER", "events": [{"introduced": "0"}, {"fixed": "1.1.1"}]}]
+ }
+ ]
+}