Computer use for the Pi coding agent — Windows apps, browsers and desktops through native UI trees, screenshots and real input.
TypeScript accessibilityagent-toolsai-agentbrowser-automationcomputer-usecuadesktop-automationelectronpipi-coding-agentpi-extensionpi-packageplaywrighttypescriptui-automationvisionwebview2windowswindows-automationwsl
feat: release through verified candidates and npm Trusted Publishing (LPT-1032)
alexshpunt-clanker[bot]b9faa7873267
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 78d422e..28e0185 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1,10 +1,11 @@+# yamllint disable rule:line-length rule:document-start rule:truthyname: CIon:push:branches: [main, develop]pull_request:- branches: [main, develop]+ branches: [main, develop, "release/*"]workflow_dispatch:permissions:@@ -14,27 +15,46 @@ concurrency:group: ci-${{ github.ref }}cancel-in-progress: true+env:+ NODE_VERSION: "24.19.0"+ NPM_VERSION: "11.19.0"+ PI_VERSION: "1.4.0"+jobs:- test:- name: Typecheck and tests+ validate:+ # Branch protection on main requires this check by name.+ name: Validateruns-on: ubuntu-latesttimeout-minutes: 45steps:- name: Checkout- uses: actions/checkout@v6+ uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6+ with:+ # A release candidate records the PR merge commit's first parent as its tested base.+ fetch-depth: 0- name: Setup Node- uses: actions/setup-node@v6+ uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6with:- node-version: "24"- cache: npm+ node-version: ${{ env.NODE_VERSION }}+ package-manager-cache: false++ - name: Setup npm+ run: npm install --global "npm@${NPM_VERSION}"++ - name: Enforce main release freeze+ if: github.event_name == 'pull_request' && github.base_ref == 'main'+ env:+ PR_HEAD: ${{ github.head_ref }}+ PR_LABELS: ${{ toJSON(github.event.pull_request.labels.*.name) }}+ run: node --experimental-strip-types scripts/release/merge-policy.ts- name: Install dependenciesrun: npm ci --legacy-peer-deps- name: Install Pi# Integration tests start the real Pi CLI from PATH.- run: npm install --global @earendil-works/[email protected]+ run: npm install --global "@earendil-works/pi-coding-agent@${PI_VERSION}"- name: Typecheckrun: npm run typecheck@@ -45,3 +65,17 @@ jobs:- name: Integration tests# Fake MCP drivers stand in for Windows; no desktop or native runtime is used.run: npm run test:integration++ - name: Build and install reproducible release candidate+ if: success() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && startsWith(github.head_ref, 'release/') && github.base_ref == 'main'+ run: node --experimental-strip-types scripts/release/build-candidate.ts++ - name: Retain release candidate+ if: success() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && startsWith(github.head_ref, 'release/') && github.base_ref == 'main'+ uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0+ with:+ name: release-candidate+ path: .tmp/release/candidate/*+ if-no-files-found: error+ compression-level: 0+ retention-days: 30diff --git a/.github/workflows/release-cancel.yml b/.github/workflows/release-cancel.ymlnew file mode 100644index 0000000..3dbf2c1--- /dev/null+++ b/.github/workflows/release-cancel.yml@@ -0,0 +1,54 @@+# yamllint disable rule:line-length rule:document-start rule:truthy+name: Cancel release++on:+ workflow_dispatch:+ inputs:+ version:+ description: Release version X.Y.Z+ required: true+ type: string+ confirmation:+ description: Type cancel to close an unpublished release PR and remove its branch+ required: true+ type: string++permissions:+ contents: read++concurrency:+ group: npm-release+ cancel-in-progress: false++jobs:+ cancel:+ if: github.ref == 'refs/heads/main'+ runs-on: ubuntu-latest+ steps:+ - name: Get short-lived repository credentials+ id: app+ uses: actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349 # v2+ with:+ app-id: ${{ secrets.RELEASE_APP_ID }}+ private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}+ owner: alexshpunt+ repositories: pi-agent-computer-use+ permission-contents: write+ permission-pull-requests: write+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6+ with:+ fetch-depth: 0+ token: ${{ steps.app.outputs.token }}+ - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6+ with:+ node-version: "24.19.0"+ package-manager-cache: false+ - name: Cancel only an unpublished, unmerged release+ env:+ GH_TOKEN: ${{ steps.app.outputs.token }}+ RELEASE_VERSION: ${{ inputs.version }}+ CONFIRM_CANCEL: ${{ inputs.confirmation }}+ run: |+ git config user.name pi-agent-computer-use-release[bot]+ git config user.email 41898282+github-actions[bot]@users.noreply.github.com+ node --experimental-strip-types scripts/release/cancel.tsdiff --git a/.github/workflows/release-start.yml b/.github/workflows/release-start.ymlnew file mode 100644index 0000000..a410456--- /dev/null+++ b/.github/workflows/release-start.yml@@ -0,0 +1,54 @@+# yamllint disable rule:line-length rule:document-start rule:truthy+name: Start release++on:+ workflow_dispatch:+ inputs:+ version:+ description: Stable version X.Y.Z+ required: true+ type: string+ notes:+ description: Release notes for the changelog+ required: true+ type: string++permissions:+ contents: read++concurrency:+ group: npm-release+ cancel-in-progress: false++jobs:+ start:+ if: github.ref == 'refs/heads/main'+ runs-on: ubuntu-latest+ steps:+ - name: Get short-lived repository credentials+ id: app+ uses: actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349 # v2+ with:+ app-id: ${{ secrets.RELEASE_APP_ID }}+ private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}+ owner: alexshpunt+ repositories: pi-agent-computer-use+ permission-contents: write+ permission-pull-requests: write+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6+ with:+ fetch-depth: 0+ token: ${{ steps.app.outputs.token }}+ - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6+ with:+ node-version: "24.19.0"+ package-manager-cache: false+ - name: Prepare release branch and candidate PR+ env:+ GH_TOKEN: ${{ steps.app.outputs.token }}+ RELEASE_VERSION: ${{ inputs.version }}+ RELEASE_NOTES: ${{ inputs.notes }}+ run: |+ git config user.name pi-agent-computer-use-release[bot]+ git config user.email 41898282+github-actions[bot]@users.noreply.github.com+ node --experimental-strip-types scripts/release/start.tsdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlnew file mode 100644index 0000000..9cd2b56--- /dev/null+++ b/.github/workflows/release.yml@@ -0,0 +1,142 @@+# yamllint disable rule:line-length rule:comments rule:document-start rule:truthy+name: Publish to npm++on:+ workflow_dispatch:+ inputs:+ pull_request:+ description: Merged release PR number+ required: true+ type: string+ candidate_run:+ description: Successful CI run for the release PR+ required: true+ type: string+ publish:+ description: Publish after verifying the candidate (requires npm approval)+ default: false+ type: boolean++concurrency:+ group: npm-release+ cancel-in-progress: false++permissions:+ contents: read+ actions: read++env:+ NODE_VERSION: "24.19.0"+ NPM_VERSION: "11.19.0"++jobs:+ validate:+ name: Verify candidate+ if: github.ref == 'refs/heads/main'+ runs-on: ubuntu-latest+ timeout-minutes: 10+ outputs:+ version: ${{ steps.candidate.outputs.version }}+ commit: ${{ steps.candidate.outputs.commit }}+ steps:+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6+ - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6+ with:+ node-version: ${{ env.NODE_VERSION }}+ package-manager-cache: false+ - name: Verify candidate identity and archive+ id: candidate+ env:+ GH_TOKEN: ${{ github.token }}+ RELEASE_PR: ${{ inputs.pull_request }}+ CANDIDATE_RUN: ${{ inputs.candidate_run }}+ run: node --experimental-strip-types scripts/release/promote.ts+ - name: Retain verified artifact+ uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0+ with:+ name: release-${{ steps.candidate.outputs.version }}+ path: .tmp/release/promoted/*+ if-no-files-found: error+ compression-level: 0++ publish:+ name: Publish package+ needs: validate+ if: inputs.publish+ runs-on: ubuntu-latest+ timeout-minutes: 15+ environment: npm+ permissions:+ contents: write+ actions: read+ id-token: write+ steps:+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6+ - name: Setup Node and npm registry+ uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6+ with:+ node-version: ${{ env.NODE_VERSION }}+ registry-url: "https://registry.npmjs.org"+ package-manager-cache: false+ - name: Install pinned npm+ # Trusted Publishing needs npm 11.5.1 or newer.+ run: npm install --global "npm@${NPM_VERSION}"+ - name: Download verified artifact+ uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0+ with:+ name: release-${{ needs.validate.outputs.version }}+ path: .tmp/release/promoted+ - name: Publish exact archive without replacing tags or versions+ env:+ GH_TOKEN: ${{ github.token }}+ RELEASE_VERSION: ${{ needs.validate.outputs.version }}+ RELEASE_COMMIT: ${{ needs.validate.outputs.commit }}+ run: node --experimental-strip-types scripts/release/publish.ts+ - name: Create matching GitHub release+ env:+ GH_TOKEN: ${{ github.token }}+ RELEASE_VERSION: ${{ needs.validate.outputs.version }}+ run: |+ tag="v${RELEASE_VERSION}"+ archive=".tmp/release/promoted/pi-agent-computer-use-${RELEASE_VERSION}.tgz"+ gh release view "$tag" >/dev/null 2>&1 ||+ gh release create "$tag" "$archive" --verify-tag --generate-notes --title "Pi Agent Computer Use ${RELEASE_VERSION}"++ finish:+ name: Synchronize develop and lift release freeze+ needs: [validate, publish]+ if: inputs.publish && needs.publish.result == 'success'+ runs-on: ubuntu-latest+ permissions:+ contents: read+ actions: read+ steps:+ - name: Get short-lived repository credentials+ id: app+ uses: actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349 # v2+ with:+ app-id: ${{ secrets.RELEASE_APP_ID }}+ private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}+ owner: alexshpunt+ repositories: pi-agent-computer-use+ permission-contents: write+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6+ with:+ fetch-depth: 0+ token: ${{ steps.app.outputs.token }}+ - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6+ with:+ node-version: ${{ env.NODE_VERSION }}+ package-manager-cache: false+ - name: Download verified archive and evidence+ uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0+ with:+ name: release-${{ needs.validate.outputs.version }}+ path: .tmp/release/promoted+ - name: Merge main into develop and end freeze+ env:+ RELEASE_VERSION: ${{ needs.validate.outputs.version }}+ run: |+ git config user.name pi-agent-computer-use-release[bot]+ git config user.email 41898282+github-actions[bot]@users.noreply.github.com+ node --experimental-strip-types scripts/release/finish.tsdiff --git a/.github/workflows/sync-develop.yml b/.github/workflows/sync-develop.ymlnew file mode 100644index 0000000..cdc2261--- /dev/null+++ b/.github/workflows/sync-develop.yml@@ -0,0 +1,44 @@+# yamllint disable rule:line-length rule:document-start rule:truthy+name: Synchronize main into develop++on:+ push:+ branches: [main]+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: npm-release+ cancel-in-progress: false++jobs:+ sync:+ if: github.ref == 'refs/heads/main'+ runs-on: ubuntu-latest+ steps:+ - name: Get short-lived repository credentials+ id: app+ uses: actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349 # v2+ with:+ app-id: ${{ secrets.RELEASE_APP_ID }}+ private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}+ owner: alexshpunt+ repositories: pi-agent-computer-use+ permission-contents: write+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6+ with:+ fetch-depth: 0+ token: ${{ steps.app.outputs.token }}+ - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6+ with:+ node-version: "24.19.0"+ package-manager-cache: false+ - name: Merge main into develop unless a release is active+ env:+ SKIP_ACTIVE_RELEASE: "true"+ run: |+ git config user.name pi-agent-computer-use-release[bot]+ git config user.email 41898282+github-actions[bot]@users.noreply.github.com+ node --experimental-strip-types scripts/release/sync-develop.tsdiff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 0000000..825c32f--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1 @@+# Changelogdiff --git a/README.md b/README.mdindex dc5ca14..21442fd 100644--- a/README.md+++ b/README.md@@ -194,6 +194,7 @@ I use this every day on real tasks, but I can only test the machines, apps and w| [Native visuals](docs/native-observability.md) | Human controls, previews and presentation safety || [Bundled runtime](docs/bundled-runtime.md) | Native runtime packages and platform boundaries || [Setup and modes](docs/setup.md) | Install, Safe and YOLO, runtime overrides and window lifetime |+| [Releases](docs/releases.md) | Promotion, release candidates, publication and first-time setup |## Licensediff --git a/docs/releases.md b/docs/releases.mdnew file mode 100644index 0000000..1c34e86--- /dev/null+++ b/docs/releases.md@@ -0,0 +1,69 @@+# Develop and release Pi Agent Computer Use++Feature branches merge into `develop`. Ready changes merge into `main` through a pinned promotion PR. A versioned release starts from `main` and freezes it until the package is published and `main` has been merged back into `develop`, or the unpublished release is canceled. `develop` stays open throughout. The flow follows [Pi Agent IDE](https://github.com/alexshpunt/pi-agent-ide/blob/main/docs/releases.md), adapted to npm and one package.++## Workflows++| Workflow | Trigger | What it does |+| --- | --- | --- |+| CI (`ci.yml`) | Push and PR | The `Validate` job runs typecheck, unit and integration tests. On a PR to `main` it enforces the release freeze. On a release PR it also builds the candidate archive. |+| Start release (`release-start.yml`) | Manual, on `main` | Creates `release/X.Y.Z` with the version and changelog section, then opens its PR to `main`. |+| Publish to npm (`release.yml`) | Manual, on `main` | Verifies the merged release PR and its candidate run, publishes that exact archive after approval, tags it and creates the GitHub release, then synchronizes `develop`. |+| Cancel release (`release-cancel.yml`) | Manual, on `main` | Closes an unpublished release PR and deletes its branch. |+| Synchronize main into develop (`sync-develop.yml`) | Push to `main` | Merges `main` into `develop` unless a release is active. |++The scripts behind them live in `scripts/release/`.++## Promote to main++Choose the release cut by its full `develop` commit SHA. Create a branch such as `chore/promote-X.Y.Z` from that commit and open its PR to `main`. Keep the branch unchanged while CI runs, then squash-merge it. Check that **Synchronize main into develop** succeeds before starting the release. Squash merges make the histories of `main` and `develop` diverge, so a failed synchronization must be fixed before the next promotion.++## Start a release++Run **Start release** on `main` with an unused `X.Y.Z` and finished release notes. It refuses a version that npm already has, an existing tag and a second active release. It sets the version in `package.json` and `package-lock.json`, adds `## X.Y.Z — date` with the notes to `CHANGELOG.md` and opens the release PR.++A branch named exactly `release/X.Y.Z` is the freeze marker. While it exists, the `Validate` check rejects every PR to `main` except the release PR and `fix/release-*` PRs labeled `release-fix`. Review the fix itself: the label is not proof that a change is a fix. After a fix merges into `main`, rebase the release branch onto it with `--force-with-lease` and wait for a new candidate run.++## Release candidate++CI on the release PR runs the normal checks, then `scripts/release/build-candidate.ts`:++1. Packs the package twice with `npm pack` (prepack fetches and hash-checks the pinned native runtime) and fails if the archives differ.+2. Installs the archive the way `pi install` does: `npm install <archive> --prefix <root> --legacy-peer-deps`.+3. Checks the installed manifest: every `pi.extensions` entry exists and every `pi.skills` root holds a skill.+4. Runs `test/installed-package.integration.test.ts` against that install in real Pi, standalone and with the installed Pi Agent IDE.+5. Records the PR, head, tested base, tree, run and archive hashes in `candidate.json` and keeps both files as the `release-candidate` artifact.++To rehearse packing and installation locally, run `node scripts/release/build-candidate.ts --local`. A local candidate is never published.++Squash-merge only a release PR whose candidate passed. Keep the release branch until publication and synchronization finish.++## Publish++Run **Publish to npm** on `main` with the merged release PR number and the ID of its successful CI run. With `publish: false` it only verifies: the PR merged from `release/X.Y.Z`, the run is CI for that PR head, the squash commit has the tested tree on the tested base, `main` has not moved except for release infrastructure, and the downloaded archive matches the recorded hashes. With `publish: true` it then waits for approval of the protected `npm` environment and publishes the downloaded bytes with `npm publish --provenance` through npm Trusted Publishing. It never rebuilds the archive. A retry cannot replace a tag or publish different bytes under an existing version.++After publication the finish job waits until the registry serves the version, compares its integrity with the candidate, merges `main` into `develop` and deletes the unchanged release branch. If `develop` moved during the push or the merge conflicts, the branch stays and `main` stays frozen. Resolve the conflict and rerun the same publication.++To abandon an unpublished release, run **Cancel release** with the version and the confirmation `cancel`. If its PR already merged, revert it on `main` first. A published or tagged version cannot be canceled.++## One-time setup++The repository owner configures these before the first release:++- Make the repository public and create `main` from the commit chosen for 0.1.0.+- Protect `main`: no direct pushes, PRs require the `Validate` check.+- Install a GitHub App on this repository with Contents and Pull requests write access. Store its ID and private key as the Actions secrets `RELEASE_APP_ID` and `RELEASE_APP_PRIVATE_KEY`. The App pushes release branches, `develop` merges and branch deletions.+- Create the `npm` Actions environment with required reviewers.+- Create the `release-fix` label.++### Publish the first version++npm cannot attach a Trusted Publisher to a package that does not exist yet, so 0.1.0 goes through the normal candidate flow and is then published by hand from the verified archive:++1. Run **Start release** with `0.1.0` and its notes, wait for the candidate run and squash-merge the release PR.+2. Run **Publish to npm** with `publish: false`. It keeps the verified archive as the `release-0.1.0` artifact.+3. Download that artifact (`gh run download <run> --name release-0.1.0`), check that `sha512` in `candidate.json` matches the archive, and publish it: `npm publish pi-agent-computer-use-0.1.0.tgz --access public`.+4. Attach the Trusted Publisher: `npm trust github pi-agent-computer-use --repo alexshpunt/pi-agent-computer-use --file release.yml --env npm` (npm 11.10 or newer). A new relationship expires if no trusted publish succeeds within two days, so later versions should follow soon or the relationship is recreated.+5. Run **Publish to npm** again with `publish: true` and the same PR and run. It finds 0.1.0 in the registry with the candidate's integrity, creates the `v0.1.0` tag and GitHub release, and synchronizes `develop`.++Every later version publishes through the workflow.diff --git a/package.json b/package.jsonindex 53aeb0c..d196622 100644--- a/package.json+++ b/package.json@@ -93,6 +93,7 @@"files": ["src/","scripts/",+ "!scripts/release/","native/","native-runtime/win32-x64/runtime/","native-runtime/win32-x64/runtime.source",@@ -100,6 +101,7 @@"skills/","docs/","assets/banner.png",+ "CHANGELOG.md","LICENSE","README.md"]diff --git a/scripts/release/build-candidate.ts b/scripts/release/build-candidate.tsnew file mode 100644index 0000000..01edaff--- /dev/null+++ b/scripts/release/build-candidate.ts@@ -0,0 +1,64 @@+import { execFileSync } from "node:child_process";+import { createHash } from "node:crypto";+import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import path from "node:path";+import { archiveName, installTestPackage, verifyInstalledPackage, type CandidateEvidence } from "./candidate.ts";+import { CANDIDATE_DIRECTORY } from "./package.ts";++/** Packs the package with npm, which runs prepack and fetches the pinned native runtime. */+function pack(destination: string, filename: string): Buffer {+ rmSync(destination, { recursive: true, force: true });+ mkdirSync(destination, { recursive: true });+ // prepack logs to stdout, so the archive is found by its name rather than by parsing npm's output.+ execFileSync("npm", ["pack", "--pack-destination", destination], { stdio: "inherit" });+ return readFileSync(path.join(destination, filename));+}++const git = (...args: string[]) => execFileSync("git", args, { encoding: "utf8" }).trim();+const { version } = JSON.parse(readFileSync("package.json", "utf8")) as { version: string };+const local = process.argv.includes("--local");+let identity: Omit<CandidateEvidence, "version" | "sha256" | "sha512" | "baseCommit" | "tree">;+if (local) {+ // A local rehearsal checks packing and installation; its evidence never reaches Publish.+ identity = { repository: "local", pullRequest: 0, headCommit: git("rev-parse", "HEAD"), runId: 0 };+} else {+ const eventPath = process.env.GITHUB_EVENT_PATH;+ if (!eventPath) throw new Error("Missing GitHub event");+ const pr = (JSON.parse(readFileSync(eventPath, "utf8")) as {+ pull_request?: { number: number; base: { ref: string }; head: { sha: string; ref: string; repo: { full_name: string } } };+ }).pull_request;+ if (!pr || pr.head.repo.full_name !== process.env.GITHUB_REPOSITORY) throw new Error("Expected a same-repository PR");+ if (pr.base.ref !== "main") throw new Error("Release candidate must target main");+ if (pr.head.ref !== `release/${version}`) throw new Error("Release branch and package version differ");+ identity = { repository: pr.head.repo.full_name, pullRequest: pr.number, headCommit: pr.head.sha, runId: Number(process.env.GITHUB_RUN_ID) };+}++mkdirSync(".tmp", { recursive: true });+const work = mkdtempSync(path.resolve(".tmp/release-build-"));+try {+ const filename = archiveName(version);+ const first = pack(path.join(work, "first"), filename);+ const second = pack(path.join(work, "second"), filename);+ if (!first.equals(second)) throw new Error("Release archive is not reproducible");+ rmSync(CANDIDATE_DIRECTORY, { recursive: true, force: true });+ mkdirSync(CANDIDATE_DIRECTORY, { recursive: true });+ copyFileSync(path.join(work, "second", filename), path.join(CANDIDATE_DIRECTORY, filename));+ const installation = path.resolve(".tmp/release-install");+ rmSync(installation, { recursive: true, force: true });+ installTestPackage(installation, path.join(CANDIDATE_DIRECTORY, filename));+ verifyInstalledPackage(installation, version);+ execFileSync("npx", ["pi-test", "run", "--", "vitest", "run", "--config", "vitest.integration.config.ts",+ "test/installed-package.integration.test.ts"], {+ stdio: "inherit", env: { ...process.env, PI_COMPUTER_USE_TEST_INSTALLATION: installation },+ });+ const evidence: CandidateEvidence = {+ version, ...identity,+ // CI checks out the PR merge commit: its first parent is the tested main base.+ baseCommit: local ? git("rev-parse", "HEAD") : git("rev-parse", "HEAD^1"),+ tree: git("rev-parse", "HEAD^{tree}"),+ sha256: createHash("sha256").update(second).digest("hex"),+ sha512: createHash("sha512").update(second).digest("hex"),+ };+ writeFileSync(path.join(CANDIDATE_DIRECTORY, "candidate.json"), JSON.stringify(evidence, null, 2) + "\n");+ console.log(`Candidate ${filename} ${evidence.sha256}`);+} finally { rmSync(work, { recursive: true, force: true }); }diff --git a/scripts/release/cancel.ts b/scripts/release/cancel.tsnew file mode 100644index 0000000..a93bb42--- /dev/null+++ b/scripts/release/cancel.ts@@ -0,0 +1,28 @@+import { execFileSync } from "node:child_process";+import { readFileSync } from "node:fs";+import { registryUrl, REPOSITORY, REPOSITORY_OWNER, VERSION_PATTERN } from "./package.ts";+import { synchronizeDevelop } from "./sync-develop.ts";++const version = process.env.RELEASE_VERSION;+if (!version || !VERSION_PATTERN.test(version) || process.env.CONFIRM_CANCEL !== "cancel")+ throw new Error("Explicit release version and cancel confirmation required");+if (process.env.GITHUB_REF !== "refs/heads/main") throw new Error("Cancel releases from main only");+const registry = await fetch(registryUrl(version));+if (registry.status !== 404) throw new Error("Published or registry unavailable; cannot cancel");+const git = (...args: string[]) => execFileSync("git", args, { encoding: "utf8" }).trim();+if (git("tag", "--list", `v${version}`)) throw new Error("Tagged releases cannot be canceled");+const branch = `refs/heads/release/${version}`;+const head = git("ls-remote", "origin", branch).split("\t")[0] ?? "";+if (!/^[0-9a-f]{40}$/.test(head)) throw new Error("No active release branch");+const prs = JSON.parse(execFileSync("gh", ["api", `repos/${REPOSITORY}/pulls?state=all&head=${REPOSITORY_OWNER}:release/${version}`],+ { encoding: "utf8" })) as { number: number; merged_at: string | null; state: string }[];+if (prs.some(pr => pr.merged_at)) {+ const main = JSON.parse(readFileSync("package.json", "utf8")) as { version: string };+ const changelog = readFileSync("CHANGELOG.md", "utf8");+ if (main.version === version && changelog.includes(`## ${version} —`))+ throw new Error("Revert the merged release PR on main and review the rollback before canceling");+}+// Keep the freeze in place if main has not made it back into develop.+synchronizeDevelop();+for (const pr of prs.filter(pr => pr.state === "open")) execFileSync("gh", ["pr", "close", String(pr.number)], { stdio: "inherit" });+execFileSync("git", ["push", `--force-with-lease=${branch}:${head}`, "origin", `:${branch}`], { stdio: "inherit" });diff --git a/scripts/release/candidate.ts b/scripts/release/candidate.tsnew file mode 100644index 0000000..646c630--- /dev/null+++ b/scripts/release/candidate.ts@@ -0,0 +1,84 @@+import { execFileSync } from "node:child_process";+import { createHash } from "node:crypto";+import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";+import path from "node:path";+import { PACKAGE_NAME } from "./package.ts";++/** Evidence recorded by the successful release PR validation job. */+export interface CandidateEvidence {+ version: string;+ repository: string;+ pullRequest: number;+ headCommit: string;+ baseCommit: string;+ tree: string;+ runId: number;+ sha256: string;+ sha512: string;+}++export function archiveName(version: string): string {+ return `${PACKAGE_NAME}-${version}.tgz`;+}++export function integrity(evidence: Pick<CandidateEvidence, "sha512">): string {+ return `sha512-${Buffer.from(evidence.sha512, "hex").toString("base64")}`;+}++/** Installs an archive the way `pi install` does: npm, an install prefix and no peer resolution. */+export function installTestPackage(directory: string, archive: string): void {+ mkdirSync(directory, { recursive: true });+ writeFileSync(path.join(directory, "package.json"), JSON.stringify({ private: true }) + "\n");+ execFileSync("npm", ["install", path.resolve(archive), "--prefix", directory, "--legacy-peer-deps",+ "--registry=https://registry.npmjs.org/"], { stdio: "inherit" });+}++/**+ * Checks the installed package against its Pi manifest: every extension entry exists and every skill root holds+ * at least one SKILL.md. Pi loads the TypeScript entries itself; the installed-package integration test runs them.+ */+export function verifyInstalledPackage(directory: string, version: string): void {+ const root = path.join(directory, "node_modules", PACKAGE_NAME);+ const manifest = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")) as {+ name?: string; version?: string; pi?: { extensions?: string[]; skills?: string[] };+ };+ if (manifest.name !== PACKAGE_NAME || manifest.version !== version) throw new Error("Installed package identity does not match");+ const extensions = manifest.pi?.extensions ?? [], skills = manifest.pi?.skills ?? [];+ if (!extensions.length) throw new Error("No Pi extension entries");+ for (const entry of extensions) if (!existsSync(path.resolve(root, entry))) throw new Error(`Missing Pi extension entry ${entry}`);+ if (!skills.length) throw new Error("No Pi skill roots");+ for (const skillRoot of skills) {+ const directoryPath = path.resolve(root, skillRoot);+ const found = readdirSync(directoryPath, { withFileTypes: true })+ .filter(entry => entry.isDirectory() && existsSync(path.join(directoryPath, entry.name, "SKILL.md")));+ if (!found.length) throw new Error(`Skill root ${skillRoot} holds no SKILL.md`);+ }+}++/** Rejects promotion unless the tested tree became one squash commit on main. */+export function verifyCandidate(evidence: CandidateEvidence, expected: {+ repository: string; pullRequest: number; runId: number; headCommit: string; version: string; tree: string; parents: string[];+}): void {+ for (const key of ["repository", "pullRequest", "runId", "headCommit", "version", "tree"] as const)+ if (evidence[key] !== expected[key]) throw new Error(`Candidate ${key} does not match`);+ if (expected.parents.length !== 1 || expected.parents[0] !== evidence.baseCommit)+ throw new Error("Candidate was not squash merged onto its tested base");+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(evidence.version)) throw new Error("Invalid release version");+}++/** Checks the exact archive bytes and package identity before they can be published. */+export function verifyCandidateArchive(directory: string, evidence: CandidateEvidence): string {+ const filename = archiveName(evidence.version);+ const archives = readdirSync(directory).filter(name => name.endsWith(".tgz"));+ if (archives.length !== 1 || archives[0] !== filename) throw new Error("Unexpected release archive");+ const file = path.join(directory, filename);+ const bytes = readFileSync(file);+ for (const algorithm of ["sha256", "sha512"] as const)+ if (createHash(algorithm).update(bytes).digest("hex") !== evidence[algorithm]) throw new Error(`Archive ${algorithm} does not match`);+ const manifest = JSON.parse(execFileSync("tar", ["-xOzf", file, "package/package.json"], { encoding: "utf8" })) as {+ name?: string; version?: string; private?: boolean;+ };+ if (manifest.name !== PACKAGE_NAME || manifest.version !== evidence.version || manifest.private === true)+ throw new Error("Archive package identity does not match");+ return file;+}diff --git a/scripts/release/changelog.ts b/scripts/release/changelog.tsnew file mode 100644index 0000000..34e6196--- /dev/null+++ b/scripts/release/changelog.ts@@ -0,0 +1,6 @@+/** Insert a release section below the changelog title, keeping the notes byte for byte. */+export function insertReleaseNotes(changelog: string, heading: string, notes: string): string {+ if (!changelog.startsWith("# Changelog\n")) throw new Error("CHANGELOG.md must start with '# Changelog'");+ // A replacement function keeps `$` sequences such as `$$$ARGS` literal.+ return changelog.replace("# Changelog\n", () => `# Changelog\n\n${heading}\n\n${notes}\n`);+}diff --git a/scripts/release/finish.ts b/scripts/release/finish.tsnew file mode 100644index 0000000..e76cf19--- /dev/null+++ b/scripts/release/finish.ts@@ -0,0 +1,31 @@+import { execFileSync } from "node:child_process";+import { readFileSync } from "node:fs";+import { setTimeout as sleep } from "node:timers/promises";+import { integrity, verifyCandidateArchive, type CandidateEvidence } from "./candidate.ts";+import { PROMOTED_DIRECTORY, registryUrl } from "./package.ts";+import { synchronizeDevelop } from "./sync-develop.ts";++const evidence = JSON.parse(readFileSync(`${PROMOTED_DIRECTORY}/candidate.json`, "utf8")) as CandidateEvidence;+const version = process.env.RELEASE_VERSION;+if (version !== evidence.version || process.env.GITHUB_REF !== "refs/heads/main") throw new Error("Finish requires the verified release version on main");+verifyCandidateArchive(PROMOTED_DIRECTORY, evidence);++/** npm accepts a publish minutes before the registry serves the version; wait, but keep main frozen if it never appears. */+async function publishedVersion(): Promise<Response> {+ const deadline = Date.now() + 15 * 60_000;+ for (;;) {+ const response = await fetch(registryUrl(version!));+ if (response.status !== 404 || Date.now() > deadline) return response;+ await sleep(20_000);+ }+}+const registry = await publishedVersion();+if (!registry.ok) throw new Error("Package has not been published; main remains frozen");+const published = await registry.json() as { dist?: { integrity?: string } };+if (published.dist?.integrity !== integrity(evidence)) throw new Error("Registry archive differs from the verified release candidate");+const git = (...args: string[]) => execFileSync("git", args, { encoding: "utf8" }).trim();+const branch = `refs/heads/release/${version}`;+const branchHead = git("ls-remote", "origin", branch).split("\t")[0];+if (branchHead !== evidence.headCommit) throw new Error("Release branch changed after candidate validation; do not lift the freeze");+synchronizeDevelop();+execFileSync("git", ["push", `--force-with-lease=${branch}:${branchHead}`, "origin", `:${branch}`], { stdio: "inherit" });diff --git a/scripts/release/merge-policy.ts b/scripts/release/merge-policy.tsnew file mode 100644index 0000000..7617bab--- /dev/null+++ b/scripts/release/merge-policy.ts@@ -0,0 +1,27 @@+import { execFileSync } from "node:child_process";+import { pathToFileURL } from "node:url";++/** Ignore other release-like refs when finding active versioned releases. */+export function activeReleaseBranches(refs: string): string[] {+ return refs+ .split("\n")+ .map(line => line.split("refs/heads/")[1])+ .filter((name): name is string => name !== undefined && /^release\/\d+\.\d+\.\d+$/.test(name));+}++/** Check which pull requests may enter main while a release branch exists. */+export function canMergeIntoMain(releaseBranches: readonly string[], head: string, labels: readonly string[]): boolean {+ if (releaseBranches.length === 0) return true;+ if (releaseBranches.length !== 1) return false;+ return head === releaseBranches[0] || (head.startsWith("fix/release-") && labels.includes("release-fix"));+}++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {+ const head = process.env.PR_HEAD;+ if (!head) throw new Error("Missing PR head");+ const refs = execFileSync("git", ["ls-remote", "origin", "refs/heads/release/*"], { encoding: "utf8" });+ const labels = JSON.parse(process.env.PR_LABELS ?? "[]") as string[];+ const active = activeReleaseBranches(refs);+ if (!canMergeIntoMain(active, head, labels))+ throw new Error(`main is frozen by ${active.join(", ")}; only its release PR or labeled release fixes may merge`);+}diff --git a/scripts/release/package.ts b/scripts/release/package.tsnew file mode 100644index 0000000..f2d6c93--- /dev/null+++ b/scripts/release/package.ts@@ -0,0 +1,12 @@+/** Identity of the only package this repository releases. */+export const PACKAGE_NAME = "pi-agent-computer-use";+export const REPOSITORY = "alexshpunt/pi-agent-computer-use";+export const REPOSITORY_OWNER = "alexshpunt";+/** Where CI keeps the candidate and Publish keeps the downloaded, verified candidate. */+export const CANDIDATE_DIRECTORY = ".tmp/release/candidate";+export const PROMOTED_DIRECTORY = ".tmp/release/promoted";+export const VERSION_PATTERN = /^\d+\.\d+\.\d+$/;++export function registryUrl(version: string): string {+ return `https://registry.npmjs.org/${PACKAGE_NAME}/${version}`;+}diff --git a/scripts/release/promote-paths.ts b/scripts/release/promote-paths.tsnew file mode 100644index 0000000..959018e--- /dev/null+++ b/scripts/release/promote-paths.ts@@ -0,0 +1,7 @@+/** Files that may change on main after the candidate merged without invalidating it. */+export const RELEASE_INFRASTRUCTURE_PATHS: ReadonlySet<string> = new Set([+ ".github/workflows/release.yml",+ "scripts/release/promote.ts",+ "scripts/release/promote-paths.ts",+ "scripts/release/publish.ts",+]);diff --git a/scripts/release/promote.ts b/scripts/release/promote.tsnew file mode 100644index 0000000..5faefbc--- /dev/null+++ b/scripts/release/promote.ts@@ -0,0 +1,37 @@+import { execFileSync } from "node:child_process";+import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { verifyCandidate, verifyCandidateArchive, type CandidateEvidence } from "./candidate.ts";+import { PROMOTED_DIRECTORY, REPOSITORY } from "./package.ts";+import { RELEASE_INFRASTRUCTURE_PATHS } from "./promote-paths.ts";++const pr = Number(process.env.RELEASE_PR);+const runId = Number(process.env.CANDIDATE_RUN);+if (!Number.isSafeInteger(pr) || pr <= 0 || !Number.isSafeInteger(runId) || runId <= 0)+ throw new Error("A merged PR and successful candidate run are required");+const api = (route: string): unknown => JSON.parse(execFileSync("gh", ["api", `repos/${REPOSITORY}/${route}`], { encoding: "utf8" }));+const pull = api(`pulls/${pr}`) as { merged: boolean; base: { ref: string }; head: { sha: string; ref: string; repo: { full_name: string } | null }; merge_commit_sha: string };+const run = api(`actions/runs/${runId}`) as { conclusion: string; event: string; workflow_id: number; head_sha: string; head_repository: { full_name: string } | null };+const workflow = api("actions/workflows/ci.yml") as { id: number };+if (!pull.merged || pull.base.ref !== "main" || pull.head.repo?.full_name !== REPOSITORY || !/^release\/\d+\.\d+\.\d+$/.test(pull.head.ref))+ throw new Error("Only a merged same-repository release PR into main can be promoted");+if (run.conclusion !== "success" || run.event !== "pull_request" || run.workflow_id !== workflow.id ||+ run.head_sha !== pull.head.sha || run.head_repository?.full_name !== REPOSITORY)+ throw new Error("Candidate run is not successful CI for this PR head");+const commit = api(`git/commits/${pull.merge_commit_sha}`) as { tree: { sha: string }; parents: { sha: string }[] };+const main = api("git/ref/heads/main") as { object: { sha: string } };+if (main.object.sha !== pull.merge_commit_sha) {+ const comparison = api(`compare/${pull.merge_commit_sha}...${main.object.sha}`) as { status: string; files?: { filename: string }[] };+ if (comparison.status !== "ahead" || !comparison.files?.length || comparison.files.some(({ filename }) => !RELEASE_INFRASTRUCTURE_PATHS.has(filename)))+ throw new Error("Release candidate is no longer the current publishable main tree");+}+const manifestFile = api(`contents/package.json?ref=${pull.merge_commit_sha}`) as { content: string };+const manifest = JSON.parse(Buffer.from(manifestFile.content, "base64").toString("utf8")) as { version: string };+if (pull.head.ref !== `release/${manifest.version}`) throw new Error("Merged release branch and package version differ");+mkdirSync(PROMOTED_DIRECTORY, { recursive: true });+execFileSync("gh", ["run", "download", String(runId), "--repo", REPOSITORY, "--name", "release-candidate", "--dir", PROMOTED_DIRECTORY], { stdio: "inherit" });+const evidence = JSON.parse(readFileSync(`${PROMOTED_DIRECTORY}/candidate.json`, "utf8")) as CandidateEvidence;+verifyCandidate(evidence, { repository: REPOSITORY, pullRequest: pr, runId, headCommit: pull.head.sha, version: manifest.version,+ tree: commit.tree.sha, parents: commit.parents.map(parent => parent.sha) });+verifyCandidateArchive(PROMOTED_DIRECTORY, evidence);+writeFileSync(`${PROMOTED_DIRECTORY}/promotion.json`, JSON.stringify({ commit: pull.merge_commit_sha, runId, pr, version: evidence.version }) + "\n");+if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `version=${evidence.version}\ncommit=${pull.merge_commit_sha}\n`);diff --git a/scripts/release/publish.ts b/scripts/release/publish.tsnew file mode 100644index 0000000..d937da5--- /dev/null+++ b/scripts/release/publish.ts@@ -0,0 +1,55 @@+import { execFileSync } from "node:child_process";+import { readFileSync } from "node:fs";+import { integrity, verifyCandidateArchive, type CandidateEvidence } from "./candidate.ts";+import { PACKAGE_NAME, PROMOTED_DIRECTORY, registryUrl, REPOSITORY } from "./package.ts";+import { RELEASE_INFRASTRUCTURE_PATHS } from "./promote-paths.ts";++const evidence = JSON.parse(readFileSync(`${PROMOTED_DIRECTORY}/candidate.json`, "utf8")) as CandidateEvidence;+const promotion = JSON.parse(readFileSync(`${PROMOTED_DIRECTORY}/promotion.json`, "utf8")) as { version: string; commit: string };+const version = process.env.RELEASE_VERSION;+const commit = process.env.RELEASE_COMMIT;+if (!version || !commit || version !== evidence.version || version !== promotion.version || commit !== promotion.commit || evidence.repository !== REPOSITORY)+ throw new Error("Promotion identity changed");+const archive = verifyCandidateArchive(PROMOTED_DIRECTORY, evidence);++type TagRequest = { tag: string; message: string; object: string; type: "commit" } | { ref: string; sha: string };+async function github(route: string, body?: TagRequest, allowMissing = false) {+ const response = await fetch(`https://api.github.com/repos/${REPOSITORY}/${route}`, {+ method: body ? "POST" : "GET",+ headers: { Authorization: `Bearer ${process.env.GH_TOKEN}`, Accept: "application/vnd.github+json" },+ ...(body ? { body: JSON.stringify(body) } : {}),+ });+ if (allowMissing && response.status === 404) return null;+ if (!response.ok) throw new Error(`GitHub ${route}: ${response.status}`);+ return await response.json() as { object: { sha: string; type: string }; sha: string; status?: string; files?: { filename: string }[] };+}+const main = await github("git/ref/heads/main");+if (main?.object.sha !== commit) {+ const comparison = await github(`compare/${commit}...${main?.object.sha}`);+ if (comparison?.status !== "ahead" || !comparison.files?.length || comparison.files.some(({ filename }) => !RELEASE_INFRASTRUCTURE_PATHS.has(filename)))+ throw new Error("Main changed while waiting for approval");+}+const tag = `v${version}`;+const existing = await github(`git/ref/tags/${tag}`, undefined, true);+if (existing) {+ if (existing.object.type !== "tag") throw new Error("Release tag must be annotated");+ const annotation = await github(`git/tags/${existing.object.sha}`);+ if (annotation?.object.type !== "commit" || annotation.object.sha !== commit) throw new Error("Existing tag points elsewhere");+}+async function createTag(): Promise<void> {+ const annotation = await github("git/tags", { tag, message: `${PACKAGE_NAME} ${tag}`, object: commit!, type: "commit" });+ if (!annotation) throw new Error("Tag creation returned no object");+ await github("git/refs", { ref: `refs/tags/${tag}`, sha: annotation.sha });+}+const registry = await fetch(registryUrl(version));+if (registry.ok) {+ const published = await registry.json() as { dist?: { integrity?: string } };+ if (published.dist?.integrity !== integrity(evidence)) throw new Error("Version already exists with different release evidence");+ // The first version is published by hand from this verified archive before Trusted Publishing exists.+ if (!existing) await createTag();+ console.log(`${PACKAGE_NAME}@${version} is already published with this exact archive`);+} else {+ if (registry.status !== 404) throw new Error(`Registry check failed: ${registry.status}`);+ if (!existing) await createTag();+ execFileSync("npm", ["publish", archive, "--access", "public", "--provenance"], { stdio: "inherit" });+}diff --git a/scripts/release/start.ts b/scripts/release/start.tsnew file mode 100644index 0000000..6fb91ce--- /dev/null+++ b/scripts/release/start.ts@@ -0,0 +1,35 @@+import { execFileSync } from "node:child_process";+import { readFileSync, writeFileSync } from "node:fs";+import { insertReleaseNotes } from "./changelog.ts";+import { activeReleaseBranches } from "./merge-policy.ts";+import { PACKAGE_NAME, registryUrl, VERSION_PATTERN } from "./package.ts";++const version = process.env.RELEASE_VERSION;+const notes = process.env.RELEASE_NOTES?.trim();+if (!version || !VERSION_PATTERN.test(version) || !notes) throw new Error("A stable X.Y.Z version and release notes are required");+if (process.env.GITHUB_REF !== "refs/heads/main") throw new Error("Start releases from main only");+const git = (...args: string[]) => execFileSync("git", args, { encoding: "utf8" }).trim();+if (activeReleaseBranches(git("ls-remote", "origin", "refs/heads/release/*")).length)+ throw new Error("Finish or explicitly cancel the existing release before starting another");+if (git("tag", "--list", `v${version}`)) throw new Error("Version tag already exists");+const registry = await fetch(registryUrl(version));+if (registry.status !== 404) throw new Error(`Version already exists or registry unavailable: ${registry.status}`);++const branch = `release/${version}`;+execFileSync("git", ["switch", "--create", branch], { stdio: "inherit" });+const manifest = JSON.parse(readFileSync("package.json", "utf8")) as { version: string };+manifest.version = version;+writeFileSync("package.json", JSON.stringify(manifest, null, 2) + "\n");+// The lockfile records the root version twice; dependencies stay exactly as reviewed.+const lock = JSON.parse(readFileSync("package-lock.json", "utf8")) as { version: string; packages: Record<string, { version?: string }> };+lock.version = version;+lock.packages[""]!.version = version;+writeFileSync("package-lock.json", JSON.stringify(lock, null, 2) + "\n");+const changelog = readFileSync("CHANGELOG.md", "utf8");+if (changelog.includes(`## ${version} —`)) throw new Error("Changelog already has this version");+writeFileSync("CHANGELOG.md", insertReleaseNotes(changelog, `## ${version} — ${new Date().toISOString().slice(0, 10)}`, notes));+execFileSync("git", ["add", "package.json", "package-lock.json", "CHANGELOG.md"], { stdio: "inherit" });+execFileSync("git", ["commit", "--message", `chore: prepare ${version} release`], { stdio: "inherit" });+execFileSync("git", ["push", "origin", branch], { stdio: "inherit" });+execFileSync("gh", ["pr", "create", "--base", "main", "--head", branch, "--title", `Release ${version}`,+ "--body", `Validate ${PACKAGE_NAME}@${version} before publication.`], { stdio: "inherit" });diff --git a/scripts/release/sync-develop.ts b/scripts/release/sync-develop.tsnew file mode 100644index 0000000..317ff2e--- /dev/null+++ b/scripts/release/sync-develop.ts@@ -0,0 +1,20 @@+import { execFileSync } from "node:child_process";+import { pathToFileURL } from "node:url";+import { activeReleaseBranches } from "./merge-policy.ts";++/** Merge main back into develop without rewriting either branch. */+export function synchronizeDevelop(cwd = process.cwd()): void {+ const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] }).trim();+ git("fetch", "--no-tags", "origin", "main", "develop");+ if (git("rev-list", "--count", "origin/develop..origin/main") === "0") return;+ git("switch", "--detach", "origin/develop");+ git("merge", "--no-ff", "--no-edit", "origin/main");+ git("push", "origin", "HEAD:develop");+}++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {+ const refs = execFileSync("git", ["ls-remote", "origin", "refs/heads/release/*"], { encoding: "utf8" });+ if (process.env.SKIP_ACTIVE_RELEASE === "true" && activeReleaseBranches(refs).length > 0)+ console.log("A release is active; develop will be synchronized after publication or cancellation");+ else synchronizeDevelop();+}diff --git a/test/installed-package.integration.test.ts b/test/installed-package.integration.test.tsnew file mode 100644index 0000000..e99e216--- /dev/null+++ b/test/installed-package.integration.test.ts@@ -0,0 +1,50 @@+import { readFileSync } from "node:fs";+import { mkdtemp, rm } from "node:fs/promises";+import path from "node:path";+import { assistantMessage, getToolExecution, getToolResultText, PiIntegrationTest, testArtifactsDir, text, toolCall } from "pi-coding-agent-test";+import { expect, test } from "vitest";+import { PI_COMMAND } from "./fixtures/pi-agent-ide.ts";++// The release candidate installs its archive the way `pi install` does and points this test at that install root.+const installation = process.env.PI_COMPUTER_USE_TEST_INSTALLATION;+const root = path.resolve(import.meta.dirname, "..");++function entry(name: string): { version: string; extension: string; root: string } {+ const packageRoot = path.join(installation!, "node_modules", name);+ const manifest = JSON.parse(readFileSync(path.join(packageRoot, "package.json"), "utf8")) as { version: string; pi: { extensions: string[] } };+ return { version: manifest.version, extension: path.join(packageRoot, manifest.pi.extensions[0]!), root: packageRoot };+}++async function run(testName: string, extensions: string[], tools: string[], calls: { id: string; name: string; arguments: Record<string, unknown> }[]) {+ const cwd = await mkdtemp(path.join(root, ".tmp/installed-package-"));+ try {+ return await new PiIntegrationTest({+ testName, artifactsDir: testArtifactsDir(import.meta.filename), cwd, isolateUserResources: true, piCommand: PI_COMMAND,+ extensions, tools, timeoutMs: 90_000,+ conversation: [...calls.map(call => assistantMessage([toolCall(call)], { stopReason: "toolUse" })), assistantMessage([text("Done.")])],+ }).run("Inspect computer use only; operate no desktop window.");+ } finally { await rm(cwd, { recursive: true, force: true }); }+}++test.skipIf(!installation)("the installed package loads standalone in real Pi and ships its skill", async () => {+ const computer = entry("pi-agent-computer-use");+ const skill = readFileSync(path.join(computer.root, "skills/computer-use/SKILL.md"), "utf8");+ expect(skill).toMatch(/^---\nname: computer-use\n/);+ const result = await run("installed-standalone", [computer.extension, "builtin:tool-search"], ["tool_search"], [+ { id: "open", name: "tool_search", arguments: { query: "computer open window" } },+ ]);+ expect(result.tuiRenderedOutput).not.toContain("Failed to load extension");+ expect(getToolExecution(result, "open").isError).toBe(false);+ expect(getToolResultText(result, "open")).toContain("computer_open");+}, 120_000);++test.skipIf(!installation)("the installed package works with its installed Pi Agent IDE", async () => {+ const computer = entry("pi-agent-computer-use"), ide = entry("pi-agent-ide");+ const result = await run("installed-with-ide", [ide.extension, computer.extension, "builtin:tool-search"], ["read", "tool_search"], [+ { id: "open", name: "tool_search", arguments: { query: "computer open window" } },+ { id: "session", name: "read", arguments: { path: "computer:session" } },+ ]);+ expect(result.tuiRenderedOutput).not.toContain("Failed to load extension");+ expect(getToolResultText(result, "open")).toContain("computer_open");+ expect(getToolExecution(result, "session").isError, getToolResultText(result, "session")).toBe(false);+}, 120_000);diff --git a/test/release-scripts.test.ts b/test/release-scripts.test.tsnew file mode 100644index 0000000..6683452--- /dev/null+++ b/test/release-scripts.test.ts@@ -0,0 +1,125 @@+import { execFileSync } from "node:child_process";+import { createHash } from "node:crypto";+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { integrity, verifyCandidate, verifyCandidateArchive, verifyInstalledPackage, type CandidateEvidence } from "../scripts/release/candidate.ts";+import { insertReleaseNotes } from "../scripts/release/changelog.ts";+import { activeReleaseBranches, canMergeIntoMain } from "../scripts/release/merge-policy.ts";++const temporary: string[] = [];+afterEach(async () => { await Promise.all(temporary.splice(0).map(dir => rm(dir, { recursive: true, force: true }))); });+async function directory(): Promise<string> {+ const dir = await mkdtemp(path.join(tmpdir(), "release-"));+ temporary.push(dir);+ return dir;+}++describe("changelog", () => {+ it("keeps dollar sequences in release notes literal", () => {+ const notes = "- Pass `$NAME`, `$$$ARGS`, `$&` and `$1` captures.";+ expect(insertReleaseNotes("# Changelog\n\n## 0.1.0 — 2026-11-01\n", "## 0.2.0 — 2026-12-01", notes))+ .toBe(`# Changelog\n\n## 0.2.0 — 2026-12-01\n\n${notes}\n\n## 0.1.0 — 2026-11-01\n`);+ });++ it("adds the first release below the title", () => {+ expect(insertReleaseNotes("# Changelog\n", "## 0.1.0 — 2026-11-01", "- First release.")).toBe("# Changelog\n\n## 0.1.0 — 2026-11-01\n\n- First release.\n");+ });++ it("refuses a changelog without its title", () => {+ expect(() => insertReleaseNotes("# Notes\n", "## 0.1.0", "- x")).toThrow("# Changelog");+ });+});++describe("release freeze", () => {+ it("treats only exact version branches as active releases", () => {+ const refs = ["abc\trefs/heads/release/v0.6.3", "def\trefs/heads/release/notes"].join("\n");+ expect(activeReleaseBranches(refs)).toEqual([]);+ expect(activeReleaseBranches(`${refs}\n012\trefs/heads/release/0.6.4`)).toEqual(["release/0.6.4"]);+ });++ it("allows normal merges outside a release", () => {+ expect(canMergeIntoMain([], "develop", [])).toBe(true);+ });++ it("blocks develop and unlabeled changes while a release is active", () => {+ expect(canMergeIntoMain(["release/0.2.0"], "develop", [])).toBe(false);+ expect(canMergeIntoMain(["release/0.2.0"], "fix/release-crash", [])).toBe(false);+ expect(canMergeIntoMain(["release/0.2.0"], "feature/abc", ["release-fix"])).toBe(false);+ });++ it("allows only the release PR or labeled release fixes", () => {+ expect(canMergeIntoMain(["release/0.2.0"], "release/0.2.0", [])).toBe(true);+ expect(canMergeIntoMain(["release/0.2.0"], "fix/release-crash", ["release-fix"])).toBe(true);+ });++ it("fails closed for concurrent releases", () => {+ expect(canMergeIntoMain(["release/0.2.0", "release/0.3.0"], "release/0.2.0", [])).toBe(false);+ });+});++describe("candidate verification", () => {+ const evidence: CandidateEvidence = { version: "0.2.0", repository: "alexshpunt/pi-agent-computer-use", pullRequest: 7, headCommit: "head",+ baseCommit: "base", tree: "tree", runId: 42, sha256: "", sha512: "" };+ const expected = { repository: evidence.repository, pullRequest: 7, runId: 42, headCommit: "head", version: "0.2.0", tree: "tree", parents: ["base"] };++ it("accepts the tested tree squash-merged onto its tested base", () => {+ expect(() => verifyCandidate(evidence, expected)).not.toThrow();+ });++ it("rejects another tree, run or merge shape", () => {+ expect(() => verifyCandidate(evidence, { ...expected, tree: "other" })).toThrow("tree");+ expect(() => verifyCandidate(evidence, { ...expected, runId: 43 })).toThrow("runId");+ expect(() => verifyCandidate(evidence, { ...expected, parents: ["base", "head"] })).toThrow("squash");+ expect(() => verifyCandidate(evidence, { ...expected, parents: ["main"] })).toThrow("squash");+ });++ async function archive(manifest: Record<string, unknown>, name = "pi-agent-computer-use-0.2.0.tgz") {+ const root = await directory(), out = await directory();+ await mkdir(path.join(root, "package"));+ await writeFile(path.join(root, "package/package.json"), JSON.stringify(manifest));+ execFileSync("tar", ["-czf", path.join(out, name), "-C", root, "package"]);+ const bytes = execFileSync("cat", [path.join(out, name)]);+ return { out, sha256: createHash("sha256").update(bytes).digest("hex"), sha512: createHash("sha512").update(bytes).digest("hex") };+ }++ it("accepts the exact archive and its package identity", async () => {+ const { out, sha256, sha512 } = await archive({ name: "pi-agent-computer-use", version: "0.2.0" });+ expect(verifyCandidateArchive(out, { ...evidence, sha256, sha512 })).toBe(path.join(out, "pi-agent-computer-use-0.2.0.tgz"));+ expect(integrity({ sha512 })).toBe(`sha512-${Buffer.from(sha512, "hex").toString("base64")}`);+ });++ it("rejects changed bytes, another package or a private manifest", async () => {+ const good = await archive({ name: "pi-agent-computer-use", version: "0.2.0" });+ expect(() => verifyCandidateArchive(good.out, { ...evidence, sha256: "0".repeat(64), sha512: good.sha512 })).toThrow("sha256");+ const other = await archive({ name: "pi-agent-ide", version: "0.2.0" });+ expect(() => verifyCandidateArchive(other.out, { ...evidence, sha256: other.sha256, sha512: other.sha512 })).toThrow("identity");+ const hidden = await archive({ name: "pi-agent-computer-use", version: "0.2.0", private: true });+ expect(() => verifyCandidateArchive(hidden.out, { ...evidence, sha256: hidden.sha256, sha512: hidden.sha512 })).toThrow("identity");+ const renamed = await archive({ name: "pi-agent-computer-use", version: "0.2.0" }, "pi-agent-computer-use-0.3.0.tgz");+ expect(() => verifyCandidateArchive(renamed.out, { ...evidence, sha256: renamed.sha256, sha512: renamed.sha512 })).toThrow("Unexpected");+ });++ async function installed(manifest: Record<string, unknown>, files: string[]) {+ const dir = await directory(), root = path.join(dir, "node_modules/pi-agent-computer-use");+ for (const file of files) { await mkdir(path.dirname(path.join(root, file)), { recursive: true }); await writeFile(path.join(root, file), ""); }+ await writeFile(path.join(root, "package.json"), JSON.stringify(manifest));+ return dir;+ }+ const manifest = { name: "pi-agent-computer-use", version: "0.2.0", pi: { extensions: ["./src/index.ts"], skills: ["./skills"] } };++ it("accepts installed Pi entries and skills", async () => {+ const dir = await installed(manifest, ["src/index.ts", "skills/computer-use/SKILL.md"]);+ expect(() => verifyInstalledPackage(dir, "0.2.0")).not.toThrow();+ });++ it("rejects a missing extension entry or an empty skill root", async () => {+ const noEntry = await installed(manifest, ["skills/computer-use/SKILL.md"]);+ const noSkill = await installed(manifest, ["src/index.ts", "skills/README.md"]);+ const complete = await installed(manifest, ["src/index.ts", "skills/computer-use/SKILL.md"]);+ expect(() => verifyInstalledPackage(noEntry, "0.2.0")).toThrow("extension entry");+ expect(() => verifyInstalledPackage(noSkill, "0.2.0")).toThrow("SKILL.md");+ expect(() => verifyInstalledPackage(complete, "0.3.0")).toThrow("identity");+ });+});diff --git a/tsconfig.json b/tsconfig.jsonindex 4ec8557..8cc2270 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -9,5 +9,5 @@"skipLibCheck": true,"types": ["node"]},- "include": ["src/**/*.ts", "test/**/*.ts", "vitest*.ts"]+ "include": ["src/**/*.ts", "scripts/**/*.ts", "test/**/*.ts", "vitest*.ts"]}