diff --git a/.changeset/README.md b/.changeset/README.md index 4a2fc0fc..ae9827ed 100644 --- a/.changeset/README.md +++ b/.changeset/README.md @@ -1,3 +1,5 @@ # Changesets Run `pnpm changeset` to describe a change for the changelog. + +See [RELEASING.md](../RELEASING.md) for releases and npm setup. diff --git a/.changeset/calibration-history-bindings.md b/.changeset/calibration-history-bindings.md index 98a39d91..7e8f2a20 100644 --- a/.changeset/calibration-history-bindings.md +++ b/.changeset/calibration-history-bindings.md @@ -1,5 +1,5 @@ --- -'@tanstack/oracles': minor +'@tanstack/oracles': patch --- Add direct `history` bindings for calibrations and `probeHistories` for automatic controls, so bound calibrations validate one selected premise instead of searching. Preserve fixed and enumerated history identity, including fixed declarations with unrelated `build` metadata, rebuild constructed histories from stable seeds, and resolve once per driver execution. Apply ordinary verdict ranking and optional difference requirements to bound mutants, validate clean declared reach, and retain selected-history error context. Retain search during migration with one warning per property outside collect-only runs, before search removal ahead of the first npm release. diff --git a/.changeset/constructed-stream-independent.md b/.changeset/constructed-stream-independent.md index 251bf4ae..0b3cb145 100644 --- a/.changeset/constructed-stream-independent.md +++ b/.changeset/constructed-stream-independent.md @@ -1,5 +1,5 @@ --- -'@tanstack/oracles': minor +'@tanstack/oracles': patch --- A campaign's generated histories no longer depend on its constructed histories, and each constructed history runs several bases from a stream of its own. The `generated` unit draws only from the property's arbitrary. Constructed history k builds from each of the first `bases` draws of the arbitrary's sample at the campaign's seed plus k, and every base must enter the states it names. The new `histories.bases` option sets that number. It must be a whole number of at least 1 (default 5), or the property fails to load. So appending a constructed history keeps every fixed seed's generated histories and every other constructed history's bases. Before, half of the generated unit's runs were constructed histories, weighted by how many there were, so appending one moved every run's draw, and each constructed unit ran one history. diff --git a/.changeset/enumerated-declared-states.md b/.changeset/enumerated-declared-states.md index 4c708ca4..ea436442 100644 --- a/.changeset/enumerated-declared-states.md +++ b/.changeset/enumerated-declared-states.md @@ -1,5 +1,5 @@ --- -'@tanstack/oracles': minor +'@tanstack/oracles': patch --- An enumerated source can declare the states its laws depend on: `histories: { enumerated, states, measured }`, where `enumerated` is the list a plain enumerated source passes, and `states` and `measured` are state names. Every enumerated history runs, so a required state needs no constructed history. A `reach` test after the histories fails when no enumerated history entered a state in `states`, and otherwise prints how many entered each declared state, as ` enumerated reach {...}`. A history counts once it is judged, passing or violating its law. The reach test reuses what each history's test recorded. It runs again only a history whose test never started, such as one that a `-t` filter left out. A history whose test failed before a verdict or timed out counts for nothing. A judged history that enters a state outside `states` and `measured` fails its test. An enumerated source fails to load when it holds a key other than `enumerated`, `states`, and `measured`, or a state that is not a name; only a generated source binds a probe to a state. A plain list of histories registers no `reach` test. Any enumerated source now fails to load when its `label` names a history `reach` or `determinism`, because the rerun command for that history would also select the framework test of that name. diff --git a/.changeset/gap-cli-baseline-report.md b/.changeset/gap-cli-baseline-report.md index f408aae0..d0c206f8 100644 --- a/.changeset/gap-cli-baseline-report.md +++ b/.changeset/gap-cli-baseline-report.md @@ -1,5 +1,5 @@ --- -'@tanstack/oracles': minor +'@tanstack/oracles': patch --- The `oracle-gaps` report leads with the baseline, and a failing oracle file no longer stops the run. diff --git a/.changeset/gap-cli-block-per-law.md b/.changeset/gap-cli-block-per-law.md index bafe2efc..eef812f8 100644 --- a/.changeset/gap-cli-block-per-law.md +++ b/.changeset/gap-cli-block-per-law.md @@ -1,5 +1,5 @@ --- -'@tanstack/oracles': minor +'@tanstack/oracles': patch --- A failing law no longer blocks the gap report for its whole file. In `oracle-gaps`, a test of an oracle file that fails with no mutant active judges nothing: it is left out per test, as a nondeterministic test is, and the passing tests of its file still judge the mutants the file owns. A failing law still runs in every copy of its file: its calls count toward the copy's call budget, its I/O and timers toward idle, and it keeps its reach, but its verdicts judge nothing and it is never charged extra work. A count cut that a failing law causes blocks the mutant by that law. A test of a `describe` whose `beforeAll` or `afterAll` throws is a failing law too. An owner file that fails outside its tests (it does not load, or a file-level hook throws) judges nothing, and another owner file's passing tests still judge the mutants they share. A mutant that no deterministic passing owner test reached is `blocked` by its owners' failing laws that reached it, and by owner files that judge nothing; its directive names them. The baseline prints one `oracle-gaps: blocked` line per failing law, named by its file and test names (or one per broken file), `results.json` lists each failing file's `laws`, and the report stays provisional. diff --git a/.changeset/gap-cli-extra-work.md b/.changeset/gap-cli-extra-work.md index a59e4318..da5d43dc 100644 --- a/.changeset/gap-cli-extra-work.md +++ b/.changeset/gap-cli-extra-work.md @@ -1,5 +1,5 @@ --- -'@tanstack/oracles': minor +'@tanstack/oracles': patch --- The `oracle-gaps` report no longer reports a shortcut for speed as `not-observed`. A survivor that changed no observation but made a test do more work is now `extra-work`. Before, its directive said to observe a value or widen the oracle, which cannot work for a branch whose fast and general paths give the same result, and an author who removed the code instead made it slower. Work is the number of site evaluations that the test's instrumented production code makes, a deterministic count, never a time. The `extra-work` directive names the test, its work before and after, and the bound to declare. `oracleProperty` takes a new `work: { ratio }` option. Under the gap report, a mutant whose work in one of the property's tests is more than `ratio` times the unmodified code's work is killed under the law `work bound`. `ratio` must be a finite number of at least 1. A plain Vitest run has no unmodified run to compare with, so there the bound judges nothing. diff --git a/.changeset/gap-cli-greppable-lines.md b/.changeset/gap-cli-greppable-lines.md index e824c182..785ca92b 100644 --- a/.changeset/gap-cli-greppable-lines.md +++ b/.changeset/gap-cli-greppable-lines.md @@ -1,5 +1,5 @@ --- -'@tanstack/oracles': minor +'@tanstack/oracles': patch --- Every line the `oracle-gaps` CLI writes for a check now starts with `oracle-gaps: ` and its kind, on stdout and stderr alike, cold and through `--daemon`, so an agent can act on the results as they stream with `grep '^oracle-gaps: '` and filter one kind by the word after the prefix: diff --git a/.changeset/gap-cli-never-crash.md b/.changeset/gap-cli-never-crash.md index 55c716d1..340f69a1 100644 --- a/.changeset/gap-cli-never-crash.md +++ b/.changeset/gap-cli-never-crash.md @@ -1,5 +1,5 @@ --- -'@tanstack/oracles': minor +'@tanstack/oracles': patch --- The `oracle-gaps` CLI no longer ends a run with a bare stack trace. A problem in the author's own files or arguments (bad arguments, a `--source` that is missing or not a file, a broken `owns` declaration, no oracle file or no owner, a Vitest config that throws when it loads, has no default export, or defines `test.projects`, a Vitest that does not load, a setup file that throws, an oracle file that fails with no mutant active, an authored mutant file that is not JSON or is incomplete) refuses the run: it exits 2 and prints `refused: ` and `fix: `. When the output directory is known (even from `--out` alone, when other arguments are bad), the refusal is also written there as `results.json` (`{ "status": "refused", "cause", "directive" }`) and `summary.md`, replacing an earlier run's ending there, and the CLI's last line names that report (`oracle-gaps: done refused, report `). Any other error is a bug in the CLI: it exits 3, says so, and writes its stack to `error.log` in the output directory (or the system's temporary directory when none is known), with `results.json` status `internal-error`. A check through `--daemon` ends the same way. A daemon serves only a CLI of its own code, so a second install of the CLI starts its own daemon rather than reading another version's reply. diff --git a/.changeset/gap-cli-runtime.md b/.changeset/gap-cli-runtime.md index b0b47ed6..da53f5fd 100644 --- a/.changeset/gap-cli-runtime.md +++ b/.changeset/gap-cli-runtime.md @@ -1,5 +1,5 @@ --- -'@tanstack/oracles': minor +'@tanstack/oracles': patch --- The `oracle-gaps` CLI bounds a mutant's copies by counts, not by wall-clock limits, reports long runs, stops the processes it started, and writes nothing beside the tests. diff --git a/.changeset/gap-cli-temp-state.md b/.changeset/gap-cli-temp-state.md index 60491965..5e979364 100644 --- a/.changeset/gap-cli-temp-state.md +++ b/.changeset/gap-cli-temp-state.md @@ -1,5 +1,5 @@ --- -'@tanstack/oracles': minor +'@tanstack/oracles': patch --- The `oracle-gaps` CLI keeps its working files out of the repository. The daemon's state (its lock, log, and evidence), the one-file bundles of workspace dependencies, and the default output directory now live in the OS temp directory, in a directory keyed by the package (`oracle-gaps-`, never a shared directory), which the OS cleans. A state that the OS removed is a cold start. `--out` is honored as before, and the run still prints its output path. While a run runs, its capture setup and Vitest configs are in `/.oracle-gaps-/`, which it removes when it ends; one that a killed run left is removed by the next run. A run leaves nothing in the package, so there is nothing to add to `.gitignore` or to delete. Before, every run wrote `/.oracle-gaps/` and `/.oracle-gaps/bundle-*.mjs`. diff --git a/.changeset/gap-diff-base-limits-run.md b/.changeset/gap-diff-base-limits-run.md index f446bf4e..deb8fef5 100644 --- a/.changeset/gap-diff-base-limits-run.md +++ b/.changeset/gap-diff-base-limits-run.md @@ -1,5 +1,5 @@ --- -'@tanstack/oracles': minor +'@tanstack/oracles': patch --- `oracle-gaps --diff-base ` now judges only the mutants on lines changed since ``, for fast feedback after a change. Operator and authored mutants both count, and a mutant is on a changed line when any line from its first to its last is changed. Every line of a source file that git does not track is changed. The baseline still runs every test file that the run without the option runs, and each judged mutant gets the outcome it gets in the full run. An authored mutant that does not apply is reported on every run with the option, as it is without it. The run says so on its stream before the baseline, `oracle-gaps: note --diff-base : of mutants are on changed lines; the others are not judged in this run`, and in the same sentence in `summary.md`; `` counts the run without the option, with the same `--only` or `--sample`. Its `results.json` and `summary.md` inputs say `a partial run (--only, --sample, or --diff-base)`, as an `--only` or `--sample` run's do (their text used to read `(--only or --sample)`). Authored mutants are marked `inDiff` too. diff --git a/.changeset/gap-report-directives.md b/.changeset/gap-report-directives.md index 03e2ee47..d9c0544f 100644 --- a/.changeset/gap-report-directives.md +++ b/.changeset/gap-report-directives.md @@ -1,5 +1,5 @@ --- -'@tanstack/oracles': minor +'@tanstack/oracles': patch --- The `oracle-gaps` report gives each gap a class and one directive with a concrete next step. A message never offers an exit such as an equivalent mutant or a maintainer approval. Survivors are `not-judged`, `indeterminate`, `dead-code`, `branch-never-taken`, `not-infected`, or `not-observed`. A `crashed` gap names the error that production threw, and tells the author to record it as an observation and state the law. Standard output is short. It has the totals, one legend line for each class, and gaps grouped by function. It also has the unowned warnings counted for each function, and the paths of `summary.md` and `results.json`. The full report is in `summary.md`. The CLI also streams its progress: the baseline result first, then one line for each gap when the CLI judges it, then the summary. diff --git a/.changeset/initial-release.md b/.changeset/initial-release.md new file mode 100644 index 00000000..1c0f81fa --- /dev/null +++ b/.changeset/initial-release.md @@ -0,0 +1,7 @@ +--- +'@tanstack/oracles': patch +'@tanstack/eslint-plugin-oracles': patch +--- + +Publish the first release of the oracle testing framework, the bundled +`oracle-gaps` CLI and skills, and the ESLint plugin for oracle tests. diff --git a/.changeset/oracle-property-const-inference.md b/.changeset/oracle-property-const-inference.md index 3d3ce461..861c1911 100644 --- a/.changeset/oracle-property-const-inference.md +++ b/.changeset/oracle-property-const-inference.md @@ -1,5 +1,5 @@ --- -'@tanstack/oracles': minor +'@tanstack/oracles': patch --- `oracleProperty` infers a history from a literal with `const`, so a zero-argument `constructed[].build` that returns a literal compiles, and an annotated `model` without `resolve` keeps its annotated type, as on main. `constructed[].build` may return the read-only view of a history, `ReadonlyHistory`, which is a new public type export. diff --git a/.changeset/oracle-property-owns.md b/.changeset/oracle-property-owns.md index 0d96633e..960e476a 100644 --- a/.changeset/oracle-property-owns.md +++ b/.changeset/oracle-property-owns.md @@ -1,5 +1,5 @@ --- -'@tanstack/oracles': minor +'@tanstack/oracles': patch --- `oracleProperty` takes an `owns` list: the production files or functions (`src/x.ts`, `src/x.ts#fn`) whose static call tree the oracle owns. The `oracle-gaps` CLI reads `owns` from an object-literal argument of any call in a test file, so a wrapper that forwards `owns` to `oracleProperty` (`registerX('id', { owns: [...] })`) names it at its call. A test file that calls `oracleProperty`, or passes such a list, is an oracle file, and it owns the union of its lists. Every test file is read, because a file that never calls `oracleProperty` still owns code when it passes `owns` to a wrapper that it imports. An `owns` key inside an assertion's arguments is data, so it is not read: an `expect` chain (including `.not`, `.soft`, a computed matcher, and an aliased `expect`), `assert` and its members, `chai`, `expectTypeOf`, `assertType`, and every binding imported from Node's `assert` (named, default, or namespace). An `owns` key in an object literal passed to any other call is read, so an unrelated domain object with that key makes the file an oracle file. A local function named like an assertion, such as `function assert() {}`, is skipped too. Each list must be a literal array of string or plain template literals. It refuses a run that has no oracle file, or in which no file owns a selected source, with one diagnostic. Before, such a run reported zero gaps without judging anything. `law.owner` is removed. Each run writes its output to a directory of its own by default, not to a shared `/tmp/oracle-gaps`. diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index f331df9e..0ab137d7 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -2,13 +2,12 @@ name: PR on: pull_request: - push: - branches: [main] + workflow_call: concurrency: group: ${{ github.workflow }}-${{ github.event.number || github.ref }} - # Only a newer push to the same pull request cancels a run. Every commit on - # main keeps its run, so every commit gets a preview. + # Cancel superseded PR checks. version.yml calls this on main pushes; + # release.yml calls it after a Changesets version PR is merged. cancel-in-progress: ${{ github.event_name == 'pull_request' }} permissions: @@ -62,6 +61,7 @@ jobs: - run: pnpm run typecheck # The classifier's unit check: sample changes and the sets they must turn on. - run: pnpm run test:ci-paths + - run: pnpm run test:release - run: pnpm --filter @tanstack/oracles run test # Checks the partition of the end-to-end gap oracle into CI shards # (packages/oracles/scripts/e2e-shards.mjs) ahead of the shard jobs, diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..877f1eb3 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,104 @@ +name: Release + +on: + pull_request: + types: [closed] + branches: [main] + +permissions: + contents: read + +jobs: + checks: + name: Validate + if: >- + github.repository == 'TanStack/oracles' && + github.event.pull_request.merged == true && + github.event.pull_request.head.ref == 'changeset-release/main' && + github.event.pull_request.head.repo.full_name == github.repository + # Keep the same-commit syntax supported by actionlint's workflow parser. + uses: ./.github/workflows/pr.yml # zizmor: ignore[self-repository] + + release: + needs: checks + # Skipped PR closures never enter this queue. Retain eligible pending jobs. + concurrency: + group: release-main + cancel-in-progress: false + queue: max + runs-on: ubuntu-latest + permissions: + contents: write + id-token: write + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 0 + ref: ${{ github.event.pull_request.merge_commit_sha }} + persist-credentials: true # Changesets pushes release tags. + - name: Setup Tools + uses: tanstack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 + - name: Build packages + run: pnpm run build + - name: Check packages + run: pnpm run test:publint + - name: Publish packages + run: | + set -euo pipefail + git config user.name 'github-actions[bot]' + git config user.email '41898282+github-actions[bot]@users.noreply.github.com' + if [ -n "$NPM_TOKEN" ]; then + export NPM_CONFIG_USERCONFIG="$RUNNER_TEMP/release.npmrc" + printf '//registry.npmjs.org/:_authToken=%s\n' "$NPM_TOKEN" > "$NPM_CONFIG_USERCONFIG" + fi + + # Invoke only publication, even if future changesets remain at this merge. + pnpm run changeset:publish + + head_commit=$(git rev-parse HEAD) + release_manifests=() + tag_refs=() + for manifest in packages/*/package.json; do + if [ "$(jq -r '.private // false' "$manifest")" = true ]; then + continue + fi + name=$(jq -r '.name' "$manifest") + version=$(jq -r '.version' "$manifest") + tag="$name@$version" + tagged_commit=$(git rev-list -n 1 "$tag" 2>/dev/null) || continue + if [ "$tagged_commit" != "$head_commit" ]; then + continue + fi + + release_manifests+=("$manifest") + tag_refs+=("refs/tags/$tag") + done + + # Push all eligible tags before creating releases so a fresh retry + # can recover after a GitHub API failure. + if [ "${#tag_refs[@]}" -eq 0 ]; then + exit 0 + fi + git push --atomic origin "${tag_refs[@]}" + for manifest in "${release_manifests[@]}"; do + name=$(jq -r '.name' "$manifest") + version=$(jq -r '.version' "$manifest") + tag="$name@$version" + if gh release view "$tag" >/dev/null 2>&1; then + continue + fi + notes=$(mktemp "$RUNNER_TEMP/release-notes.XXXXXX") + awk -v heading="## $version" ' + $0 == heading { found = 1; next } + found && /^## / { exit } + found { print } + END { if (!found) exit 1 } + ' "$(dirname "$manifest")/CHANGELOG.md" > "$notes" + gh release create "$tag" --verify-tag --title "$tag" --notes-file "$notes" + done + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # New npm packages need a token for their first publication. Once + # trusted publishers are configured, remove the secret to use OIDC. + NPM_TOKEN: ${{ secrets.NPM_TOKEN }} # zizmor: ignore[use-trusted-publishing] diff --git a/.github/workflows/version.yml b/.github/workflows/version.yml new file mode 100644 index 00000000..9f30b3be --- /dev/null +++ b/.github/workflows/version.yml @@ -0,0 +1,43 @@ +name: Version Packages + +on: + push: + branches: [main] + +concurrency: + group: version-main + cancel-in-progress: false + +permissions: + contents: read + +jobs: + checks: + name: Validate + # Keep the same-commit syntax supported by actionlint's workflow parser. + uses: ./.github/workflows/pr.yml # zizmor: ignore[self-repository] + + version: + needs: checks + if: github.repository == 'TanStack/oracles' + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 0 + persist-credentials: true # Changesets pushes the version PR branch. + - name: Setup Tools + uses: tanstack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 + - name: Create or update version PR + uses: changesets/action@e0145edc7d9d8679003495b11f87bd8ef63c0cba # v1.5.3 + with: + version: pnpm run changeset:version + branch: main + commit: 'ci: Version Packages' + title: 'ci: Version Packages' + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/README.md b/README.md index ef918068..18507ac0 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,10 @@ Oracle-based testing for TypeScript: state a law, generate the histories where it matters, and check production against an independent model. This package is under construction while it is extracted from TanStack DB's -oracle suite. It is not published to npm yet; previews are published from -every commit with [pkg.pr.new](https://pkg.pr.new). +oracle suite. CI publishes previews for passing pull-request and `main` +commits with [pkg.pr.new](https://pkg.pr.new). + +For npm releases, see [the release instructions](RELEASING.md). ## Packages diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 00000000..2b7c2ca4 --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,78 @@ +# Releasing TanStack Oracles + +The two public npm packages are: + +| Package | Contents | +| --------------------------------- | ----------------------------------------------------------------------------------- | +| `@tanstack/oracles` | Oracle testing framework, `/route` entry point, `oracle-gaps` CLI, skills, and docs | +| `@tanstack/eslint-plugin-oracles` | ESLint rules and configurations for oracle tests | + +The root workspace and `@tanstack/bug-search` are private. + +## First release + +For the first release, the patch changesets advance both public packages +from `0.0.0` to `0.0.1` under npm's default `latest` tag. + +Before the first release: + +1. Enable **Allow GitHub Actions to create and approve pull requests** in + the repository's Actions settings. The Changesets action uses + `GITHUB_TOKEN` to maintain its version pull request. +2. For the first publication, add an Actions secret named `NPM_TOKEN` with + permission to create and publish public packages in the `@tanstack` scope. + Use a granular npm token with bypass 2FA enabled for automation. npm + trusted publishers can be configured after the packages exist. + +After this setup reaches `main`, the Version Packages workflow runs the same +checks and previews as a pull request, then opens **ci: Version Packages** +from `changeset-release/main`. Main pushes only create or update that PR; +they cannot publish packages. + +Merging that version PR into `main` triggers the Release workflow. It accepts +only a merged PR from this repository's `changeset-release/main` branch, +runs validation, and publishes the exact merge commit. Closing the PR without +merging it, merging another PR, or pushing directly to `main` does not +publish packages. Publication runs directly, so remaining changesets cannot +start another version PR. The workflow pushes the package tags and creates +GitHub releases from each version's changelog entry. Reruns retain existing +GitHub releases. + +Before merging the first version PR, confirm that both public package +manifests are set to `0.0.1`. + +If GitHub does not start CI on the bot-created version pull request, a +maintainer can close and reopen it to trigger `pull_request` checks. +`GITHUB_TOKEN` does not trigger workflows on its own pushes. + +Immediately before the first OIDC release, configure each package's trusted +publisher on npm with organization **TanStack**, repository **oracles**, and +workflow filename **release.yml**. Allow direct publishing, then remove +`NPM_TOKEN` from Actions. Complete the first successful OIDC publication within +two days. If the configuration expires, delete it and create a new one before +retrying within two days. The workflow grants +`id-token: write`; the Node version in `.nvmrc` includes a compatible npm +CLI (trusted publishing needs npm 11.5.1 or newer). + +Consumers can then install the packages with their peer dependencies: + +```sh +pnpm add -D @tanstack/oracles fast-check vitest +pnpm add -D @tanstack/eslint-plugin-oracles eslint +``` + +## Subsequent releases + +1. Run `pnpm changeset` with each user-facing change and select the affected + packages and bump types. Commit the generated Markdown file with the change. +2. Merge the change to `main`. Once checks pass, Changesets updates the version + pull request with versions, changelogs, and the lockfile. +3. Review and merge the `changeset-release/main` version pull request. That + merge starts release validation, then publishes the merged package versions + to npm and creates GitHub releases. + +Packages version independently. An unchanged package does not get a new +release. `pnpm changeset status` shows the pending release plan. + +For a manual publish from a built version commit, run +`pnpm run changeset:publish`. diff --git a/package.json b/package.json index 5b2175ef..57c5bb07 100644 --- a/package.json +++ b/package.json @@ -19,9 +19,12 @@ "format": "prettier --ignore-unknown '**/*' --write", "format:check": "prettier --ignore-unknown '**/*' --check", "changeset": "changeset", + "changeset:version": "changeset version && pnpm install --no-frozen-lockfile", + "changeset:publish": "changeset publish", "test:publint": "pnpm --filter \"./packages/**\" exec publint --strict", "test:sherif": "sherif", "test:ci-paths": "node scripts/classify-changes-check.mjs", + "test:release": "node --test scripts/release-workflows.test.mjs", "prepare": "husky" }, "devDependencies": { @@ -40,6 +43,7 @@ "sherif": "^1.10.0", "typescript": "^5.9.2", "vite": "^7.3.7", - "vitest": "^4.1.12" + "vitest": "^4.1.12", + "yaml": "2.9.1" } } diff --git a/packages/eslint-plugin-oracles/package.json b/packages/eslint-plugin-oracles/package.json index bd4bbf1a..fd20450b 100644 --- a/packages/eslint-plugin-oracles/package.json +++ b/packages/eslint-plugin-oracles/package.json @@ -19,6 +19,10 @@ ], "type": "module", "sideEffects": false, + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, "main": "./src/index.js", "exports": { ".": "./src/index.js", diff --git a/packages/oracles/package.json b/packages/oracles/package.json index 2301c07d..c6025f58 100644 --- a/packages/oracles/package.json +++ b/packages/oracles/package.json @@ -20,6 +20,10 @@ ], "type": "module", "sideEffects": false, + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, "main": "dist/esm/index.js", "module": "dist/esm/index.js", "types": "dist/esm/index.d.ts", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 142f160b..d750badf 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -56,6 +56,9 @@ importers: vitest: specifier: ^4.1.12 version: 4.1.12(@types/node@25.9.9)(vite@7.3.7(@types/node@25.9.9)(yaml@2.9.1)) + yaml: + specifier: 2.9.1 + version: 2.9.1 packages/bug-search: devDependencies: diff --git a/scripts/release-workflows.test.mjs b/scripts/release-workflows.test.mjs new file mode 100644 index 00000000..1059c7af --- /dev/null +++ b/scripts/release-workflows.test.mjs @@ -0,0 +1,313 @@ +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { + chmodSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join, resolve } from 'node:path' +import { test } from 'node:test' +import { fileURLToPath } from 'node:url' +import { parse } from 'yaml' + +const root = resolve(dirname(fileURLToPath(import.meta.url)), '..') +const workflow = (name) => + parse(readFileSync(join(root, '.github/workflows', name), 'utf8')) +const release = workflow('release.yml') +const version = workflow('version.yml') + +// GitHub schedules workflow concurrency before job conditions. Only the +// eligible publication job may join the shared queue, which retains up to +// GitHub's documented 100 pending jobs instead of replacing the previous one. +test('only guarded publication jobs enter the release queue', () => { + assert.equal(release.concurrency, undefined) + assert.deepEqual(release.jobs.release.concurrency, { + group: 'release-main', + 'cancel-in-progress': false, + queue: 'max', + }) + assert.equal(release.jobs.release.needs, 'checks') + assert.equal(release.jobs.release.if, undefined) + assert.deepEqual(release.on, { + pull_request: { types: ['closed'], branches: ['main'] }, + }) + const allowed = new Function('github', `return (${release.jobs.checks.if})`) + const event = { + repository: 'TanStack/oracles', + event: { + pull_request: { + merged: true, + head: { + ref: 'changeset-release/main', + repo: { full_name: 'TanStack/oracles' }, + }, + }, + }, + } + assert.equal(allowed(event), true) + for (const change of [ + (value) => { + value.event.pull_request.merged = false + }, + (value) => { + value.event.pull_request.head.ref = 'feature' + }, + (value) => { + value.event.pull_request.head.repo.full_name = 'fork/oracles' + }, + (value) => { + value.repository = 'fork/oracles' + }, + ]) { + const other = structuredClone(event) + change(other) + assert.equal(allowed(other), false) + } +}) + +test('main pushes only maintain the version PR and releases use the merge commit', () => { + const manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) + assert.equal(manifest.scripts['changeset:publish'], 'changeset publish') + assert.deepEqual(version.on, { push: { branches: ['main'] } }) + const action = version.jobs.version.steps.find((step) => + step.uses?.startsWith('changesets/action@'), + ) + assert.equal(action.with.branch, 'main') + assert.equal(action.with.publish, undefined) + assert.equal(JSON.stringify(version).includes('NPM_TOKEN'), false) + const checkout = release.jobs.release.steps.find((step) => + step.uses?.startsWith('actions/checkout@'), + ) + assert.equal( + checkout.with.ref, + '${{ github.event.pull_request.merge_commit_sha }}', + ) +}) + +const fakeCommands = `#!/usr/bin/env node +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { readFileSync, readdirSync, writeFileSync } from 'node:fs' +import { basename, join } from 'node:path' +const file = process.env.RELEASE_FIXTURE_STATE +const state = JSON.parse(readFileSync(file, 'utf8')) +const args = process.argv.slice(2) +if (basename(process.argv[1]) === 'pnpm') { + assert.deepEqual(args, ['run', 'changeset:publish']) + if (process.env.NPM_TOKEN) { + assert.equal(readFileSync(process.env.NPM_CONFIG_USERCONFIG, 'utf8'), '//registry.npmjs.org/:_authToken=fixture-token\\n') + } + state.publishCalls++ + for (const directory of readdirSync('packages')) { + const pkg = JSON.parse(readFileSync(join('packages', directory, 'package.json'), 'utf8')) + const tag = pkg.name + '@' + pkg.version + if (pkg.private || state.registry.includes(tag)) continue + state.registry.push(tag) + state.published.push(tag) + execFileSync('git', ['tag', '-a', tag, '-m', tag]) + } +} else { + assert.equal(args[0], 'release') + const tag = args[2] + if (args[1] === 'view') process.exit(state.releases.some(release => release.tag === tag) ? 0 : 1) + assert.equal(args[1], 'create') + assert.ok(args.includes('--verify-tag')) + assert.ok(!state.releases.some(release => release.tag === tag)) + if (state.failOnce && !state.failed) { + state.failed = true + writeFileSync(file, JSON.stringify(state)) + console.error('fixture GitHub release failure') + process.exit(1) + } + state.releases.push({ tag, notes: readFileSync(args[args.indexOf('--notes-file') + 1], 'utf8').trim() }) +} +writeFileSync(file, JSON.stringify(state)) +` + +// Execute the exact workflow shell against real local Git repositories and +// recording package/GitHub boundaries. No test contacts npm or GitHub. +for (const pending of [false, true]) { + for (const token of ['', 'fixture-token']) { + test(`publish reviewed versions, pending=${pending}, token=${!!token}, then retry`, (t) => { + const publisher = release.jobs.release.steps.find( + (step) => step.name === 'Publish packages', + ) + assert.equal( + typeof publisher.run, + 'string', + 'publication must not use the mixed version/publish action', + ) + const temporary = mkdtempSync(join(tmpdir(), 'release-workflow-')) + t.after(() => rmSync(temporary, { recursive: true, force: true })) + let cwd = join(temporary, 'work') + const remote = join(temporary, 'origin.git') + const bin = join(temporary, 'bin') + const runner = join(temporary, 'runner') + for (const directory of [cwd, bin, runner]) mkdirSync(directory) + const git = (...args) => + execFileSync('git', args, { + cwd, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + }).trim() + git('init', '-q') + git('init', '--bare', '-q', remote) + git('config', 'user.name', 'Release fixture') + git('config', 'user.email', 'fixture@example.invalid') + git('config', 'commit.gpgsign', 'false') + git('config', 'tag.gpgsign', 'false') + git('remote', 'add', 'origin', remote) + writeFileSync(join(cwd, 'package.json'), '{"private":true}') + for (const [directory, name, number, privatePackage] of [ + ['one', '@fixture/one', '0.0.1', false], + ['two', '@fixture/two', '0.0.2', false], + ['internal', '@fixture/internal', '0.0.0', true], + ['unchanged', '@fixture/unchanged', '1.0.0', false], + ]) { + const destination = join(cwd, 'packages', directory) + mkdirSync(destination, { recursive: true }) + writeFileSync( + join(destination, 'package.json'), + JSON.stringify({ name, version: number, private: privatePackage }), + ) + writeFileSync( + join(destination, 'CHANGELOG.md'), + `# ${name}\n\n## ${number}\n\n${directory} current notes\n\n## 0.0.0-old\n\nOld notes\n`, + ) + } + git('add', '.') + git('commit', '-qm', 'Previous release') + git('tag', '@fixture/unchanged@1.0.0') + if (pending) { + mkdirSync(join(cwd, '.changeset')) + writeFileSync( + join(cwd, '.changeset/pending.md'), + '---\n"@fixture/one": patch\n---\n\nFuture work.\n', + ) + } + writeFileSync(join(cwd, 'reviewed.txt'), 'Reviewed version PR merge\n') + git('add', '.') + git('commit', '-qm', 'Reviewed merge') + git('tag', '@fixture/internal@0.0.0') + git('push', 'origin', 'HEAD:refs/heads/main') + git('config', '--unset', 'user.name') + git('config', '--unset', 'user.email') + const stateFile = join(temporary, 'state.json') + writeFileSync( + stateFile, + JSON.stringify({ + registry: ['@fixture/unchanged@1.0.0'], + publishCalls: 0, + published: [], + releases: [], + failOnce: pending && !token, + }), + ) + const command = join(bin, 'command.mjs') + writeFileSync(command, fakeCommands) + chmodSync(command, 0o755) + for (const name of ['pnpm', 'gh']) symlinkSync(command, join(bin, name)) + const before = git('status', '--porcelain') + for (let attempt = 0; attempt < 2; attempt++) { + if (attempt === 1) { + cwd = join(temporary, 'retry') + execFileSync('git', ['clone', '-q', '--branch', 'main', remote, cwd]) + git('config', 'tag.gpgsign', 'false') + } + const execute = () => + execFileSync('bash', ['-euo', 'pipefail', '-c', publisher.run], { + cwd, + env: { + ...process.env, + PATH: `${bin}:${process.env.PATH}`, + RUNNER_TEMP: runner, + NPM_TOKEN: token, + GH_TOKEN: 'fixture-token', + RELEASE_FIXTURE_STATE: stateFile, + GIT_CONFIG_GLOBAL: '/dev/null', + GIT_CONFIG_NOSYSTEM: '1', + }, + stdio: ['ignore', 'pipe', 'pipe'], + timeout: 10000, + }) + if (attempt === 0 && pending && !token) { + assert.throws(execute, (error) => + error.stderr.toString().includes('fixture GitHub release failure'), + ) + } else { + execute() + } + } + const state = JSON.parse(readFileSync(stateFile, 'utf8')) + assert.equal(state.publishCalls, 2) + assert.deepEqual(state.published.sort(), [ + '@fixture/one@0.0.1', + '@fixture/two@0.0.2', + ]) + assert.deepEqual( + state.releases.sort((a, b) => a.tag.localeCompare(b.tag)), + [ + { tag: '@fixture/one@0.0.1', notes: 'one current notes' }, + { tag: '@fixture/two@0.0.2', notes: 'two current notes' }, + ], + ) + const pushed = new Set( + git('ls-remote', '--tags', remote) + .split('\n') + .map((line) => line.split('refs/tags/')[1].replace(/\^\{\}$/, '')), + ) + assert.deepEqual([...pushed].sort(), state.published.sort()) + assert.equal( + git('status', '--porcelain'), + before, + 'pending changesets and reviewed manifests must remain untouched', + ) + }) + } +} + +test('an empty publication leaves GitHub releases untouched', (t) => { + const temporary = mkdtempSync(join(tmpdir(), 'release-workflow-empty-')) + t.after(() => rmSync(temporary, { recursive: true, force: true })) + const cwd = join(temporary, 'work') + const bin = join(temporary, 'bin') + const runner = join(temporary, 'runner') + for (const directory of [cwd, bin, runner]) mkdirSync(directory) + const git = (...args) => execFileSync('git', args, { cwd, stdio: 'pipe' }) + git('init', '-q') + git('config', 'user.name', 'Release fixture') + git('config', 'user.email', 'fixture@example.invalid') + git('config', 'commit.gpgsign', 'false') + const directory = join(cwd, 'packages', 'private') + mkdirSync(directory, { recursive: true }) + writeFileSync(join(directory, 'package.json'), '{"private":true}') + git('add', '.') + git('commit', '-qm', 'No public packages') + for (const [name, status] of [ + ['pnpm', 0], + ['gh', 99], + ]) { + const file = join(bin, name) + writeFileSync(file, `#!/bin/sh\nexit ${status}\n`) + chmodSync(file, 0o755) + } + const publisher = release.jobs.release.steps.find( + (step) => step.name === 'Publish packages', + ) + execFileSync('bash', ['-euo', 'pipefail', '-c', publisher.run], { + cwd, + env: { + ...process.env, + PATH: `${bin}:${process.env.PATH}`, + RUNNER_TEMP: runner, + NPM_TOKEN: '', + }, + stdio: 'pipe', + timeout: 10000, + }) +})