diff --git a/docs/reference.md b/docs/reference.md index 622f6c7..3402411 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -502,6 +502,8 @@ every image by digest; `extension release` runs this. `--registry ` ```bash agentage extension release # in release.yml, on a v* tag push +agentage extension release --changed # in release.yml, on a push to master +agentage extension release --changed --dry-run # what it would release; changes nothing ``` What an extension's `release.yml` runs after `npm ci` and `npm run verify`, one `PASS :` line @@ -529,6 +531,38 @@ stage publish` instead. `GH_TOKEN` (or `GITHUB_TOKEN`) goes only to `gh` and `NP npm; both leave the environment first, so the image build and npm lifecycle scripts never see them. A package with `"private": true` skips npm entirely (no `npm --version`, `view` or `publish`) and prints `PASS npm: private package, not published`. Needs git, `docker` and the `gh` CLI, and npm only for a package that is not private. Needs `docker login` to the registry first. +`--changed` is the release of a repo where a merge to master is the release. Run it from the repo +root: the extensions are each `extensions/` with an `agentage` package, or the root package +when there is none. It reads `GITHUB_REPOSITORY` and `GITHUB_SHA` (default: `HEAD`), refuses a +commit not on `origin/master`, then fetches the tags (a default shallow checkout has none). An +extension is changed when a file in its folder differs from its last `@*` tag (the highest by +number, not the push range, so a run the concurrency group dropped is caught up), when it has no +such tag yet, or when that tag has no `agentage-extension.json` record (a release that failed after +its tag). Only the folder is read: each extension keeps its own `package-lock.json` there, and a +change to a shared root file (a root lock, a workflow, a config) does not release anything. When +the last tag is on this commit (a re-run), that version is resumed. An extension is refused (a +`FAIL history:` line) when the commit of its last tag is not an ancestor of this commit: a re-run +of an older run never gives older code a higher version. It is refused (`FAIL stuck:`, naming the +tags) when its newest 3 tags have no record: a build that always fails stops taking new tags until +a release of the last tag succeeds or a human removes those tags. A shallow checkout is deepened +(`--unshallow`) for the ancestor check. A changed +extension gets the date version `YYYY.MDD.N`: the UTC year, then month times 100 plus day (5 +January is `105`, 22 November `1122`), and `N` one more than the highest `N` tagged for that id +that UTC day. The version and `repository` (the releasing repo, which the +`org.opencontainers.image.source` label and npm provenance read) go into `package.json`, its +`package-lock.json` and the contracts `check --write` writes, in the CI copy only: never committed. +The build allows only those files to differ from `HEAD`. Then the tag `@` is created +on the commit (a tag on another commit is refused), before the build, so a failed build uses up its +`N`. The guard and images are as above; npm is published before the records are attached, so a +version with a record is on npm (a private package skips npm). When npm fails, no record goes up: +a re-run of that commit is refused by the guard (images pushed, no record), and the next commit +takes a new `N`. The release is created with `--target `. Every changed extension is tried: +one that fails or is refused does not stop the others. The run ends with one table (`id`, +`version`, `result`: `released`, `failed`, `refused` or `unchanged`) and exits 1 when any failed +or was refused; the error names each one as `: FAIL ...` and keeps the code of the first. `--dry-run` prints the plan and writes, tags, pushes and publishes nothing (a refused extension +still exits 1); without +`--changed` it is refused with `invalid_argument` (exit 1). + ## extension up, down and token ```bash @@ -915,20 +949,20 @@ from another site, `AGENTAGE_SITE_FQDN= agentage daemon restart`, then ins A usage error (an unknown flag, a missing argument) exits 2 with no object; with `--json` it exits 1 with the error object, code `usage`, and the usage line on stderr. -| Command | `data` | -| ----------------------------------------------------- | --------------------------------------------------------------------------------------------------- | -| `setup` | `{ extensions: [...] }`, the rows as `extension doctor` has them | -| `extension install`, `disable`, `enable`, `configure` | the daemon's row `{ id, version, source, state, enabled, error? }` | -| `extension list` | the daemon's rows; a folder row has `source: "folder"` and `path` | -| `extension list --available` | `[{ id, version }]` from the market; `meta.skipped` is `[{ id, reason }]`; `meta.down` when silent | -| `extension update` | `[{ id, from, to, updated }]` | -| `extension remove` | `{ id, purged }` | -| `update` | `{ installed, status, latest, updated }` | -| `extension create` | `{ id, dir, from, kept, installed, url }` | -| `extension build` | `{ dir, built, contracts, conforms }`; the kit's result for images | -| `extension release` | `{ id, version, tag, built, published }` | -| `extension up`, `down` | `up`: `{ id, version, url, port, stoppedBy }` (`--docker`: `{ lines }`); `down`: `{ local, lines }` | -| `extension token` | `{ token }`; nothing else is printed | +| Command | `data` | +| ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| `setup` | `{ extensions: [...] }`, the rows as `extension doctor` has them | +| `extension install`, `disable`, `enable`, `configure` | the daemon's row `{ id, version, source, state, enabled, error? }` | +| `extension list` | the daemon's rows; a folder row has `source: "folder"` and `path` | +| `extension list --available` | `[{ id, version }]` from the market; `meta.skipped` is `[{ id, reason }]`; `meta.down` when silent | +| `extension update` | `[{ id, from, to, updated }]` | +| `extension remove` | `{ id, purged }` | +| `update` | `{ installed, status, latest, updated }` | +| `extension create` | `{ id, dir, from, kept, installed, url }` | +| `extension build` | `{ dir, built, contracts, conforms }`; the kit's result for images | +| `extension release` | `{ id, version, tag, built, published }`; `--changed`: `{ released, unchanged }`, with `--dry-run` `{ dryRun, changed, unchanged }` | +| `extension up`, `down` | `up`: `{ id, version, url, port, stoppedBy }` (`--docker`: `{ lines }`); `down`: `{ local, lines }` | +| `extension token` | `{ token }`; nothing else is printed | `setup` with `--json` does not open a browser: when it must sign in it needs `--no-browser`, else it fails with `confirmation_required`. `extension remove --purge` with `--json` needs `--yes`, else diff --git a/src/commands/extension/release-changed-safety.test.ts b/src/commands/extension/release-changed-safety.test.ts new file mode 100644 index 0000000..a3fc487 --- /dev/null +++ b/src/commands/extension/release-changed-safety.test.ts @@ -0,0 +1,124 @@ +import { writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { describe, expect } from 'vitest'; +import { test } from '../../test/config-dir.js'; +import { checkoutAt, ciClone, makeRepo, release, writeExtension } from '../../test/release-repo.js'; + +const tagged = (calls: string[]) => calls.filter((c) => c.includes('/git/refs')); + +// probe changed on C1 (its run failed), then changed again and released on C2. +const oldAndNew = () => { + const repo = makeRepo(); + writeExtension(repo, 'extensions/probe', 'probe'); + repo.commit('base'); + repo.tag('probe@2026.1121.1'); + const base = repo.git('rev-parse', 'HEAD'); + repo.write('extensions/probe/index.js', 'c1\n'); + writeExtension(repo, 'extensions/fixture', 'fixture'); + const c1 = repo.commit('c1'); + repo.write('extensions/probe/index.js', 'c2\n'); + const c2 = repo.commit('c2'); + repo.tag('probe@2026.1122.1'); + return { repo, c1, records: { 'probe@2026.1121.1': base, 'probe@2026.1122.1': c2 } }; +}; + +// probe tagged `count` times today with no record, then changed again. +const failedTags = (count: number) => { + const repo = makeRepo(); + writeExtension(repo, 'extensions/probe', 'probe'); + repo.commit('base'); + for (let n = 1; n <= count; n++) { + repo.tag(`probe@2026.1122.${n}`); + repo.write('extensions/probe/index.js', `try ${n}\n`); + repo.commit(`try ${n}`); + } + return repo; +}; + +describe('extension release --changed: an older commit', () => { + test('a re-run of an older commit is refused for an id tagged later; others still go', async () => { + const { repo, c1, records } = oldAndNew(); + const run = await release({ dir: checkoutAt(repo, c1), w: { records } }); + expect(run.code).toBe('release_refused'); + expect(run.error).toMatch( + /^probe: FAIL history: probe@2026\.1122\.1 is on \w{40}, which is not/ + ); + expect(run.error).toContain(`not before ${c1}: an older commit is refused`); + expect(tagged(run.calls)).toEqual([ + `gh api repos/agentage/examples/git/refs -f ref=refs/tags/fixture@2026.1122.1 -f sha=${c1}`, + ]); + expect(run.lines.slice(-3)).toEqual([ + 'id version result', + 'probe - refused', + 'fixture 2026.1122.1 released', + ]); + }); +}); + +describe('extension release --changed: tags with no record', () => { + test('three in a row with no record: refused, the three named, no new tag', async () => { + const run = await release({ dir: ciClone(failedTags(3)), opts: { dryRun: true } }); + expect(run.error).toBe( + 'probe: FAIL stuck: probe@2026.1122.3, probe@2026.1122.2, probe@2026.1122.1 have no record: fix the release, or remove those tags' + ); + expect(run.lines).toContain('probe - refused'); + }); + + test('two with no record: still released with the next N', async () => { + const run = await release({ dir: ciClone(failedTags(2)), opts: { dryRun: true } }); + expect(run.error).toBeNull(); + expect(run.lines).toContain( + 'PASS changed: probe (extensions/probe) differs from probe@2026.1122.2: release probe@2026.1122.3' + ); + }); + + test('a record on the newest tag breaks the row: one record check only', async () => { + const repo = failedTags(3); + const records = { 'probe@2026.1122.3': repo.git('rev-list', '-n', '1', 'probe@2026.1122.3') }; + const run = await release({ dir: ciClone(repo), w: { records }, opts: { dryRun: true } }); + expect(run.error).toBeNull(); + expect(run.calls.filter((c) => c.startsWith('gh release download'))).toHaveLength(1); + }); +}); + +describe('extension release --changed: npm and the record', () => { + test('npm fails: no record goes up, so the next commit releases a new N', async () => { + const repo = makeRepo(); + writeExtension(repo, 'extensions/probe', 'probe'); + repo.commit('one'); + const run = await release({ dir: ciClone(repo), w: { npmFails: 'E403 forbidden' } }); + expect(run.error).toBe('probe: FAIL npm: E403 forbidden'); + expect(run.calls).toContain('build probe@2026.1122.1'); + expect(run.calls.some((c) => c.startsWith('gh release create'))).toBe(false); + repo.tag('probe@2026.1122.1'); + repo.write('README.md', 'outside the folder\n'); + repo.commit('readme'); + const next = await release({ dir: ciClone(repo), opts: { dryRun: true } }); + expect(next.lines).toContain( + 'PASS changed: probe (extensions/probe) equals probe@2026.1122.1, which has no record: release probe@2026.1122.2' + ); + }); +}); + +describe('extension release --changed: one failure', () => { + test('a failed extension does not stop the next; one table, a non-zero exit', async () => { + const repo = makeRepo(); + writeExtension(repo, 'extensions/fixture', 'fixture', { api: true }); + writeExtension(repo, 'extensions/probe', 'probe', { api: true }); + repo.commit('two'); + // A half-done contracts write leaves a file behind: it must not block the next build. + const writeContracts = async (dir: string) => { + writeFileSync(join(dir, 'openapi.json'), '{}\n'); + if (dir.endsWith('fixture')) throw new Error('fixture contracts broke'); + return ['openapi.json']; + }; + const run = await release({ dir: ciClone(repo) }, { writeContracts }); + expect(run.error).toBe('fixture: FAIL contracts: fixture contracts broke'); + expect(run.calls).toContain('build probe@2026.1122.1'); + expect(run.lines.slice(-3)).toEqual([ + 'id version result', + 'fixture 2026.1122.1 failed', + 'probe 2026.1122.1 released', + ]); + }); +}); diff --git a/src/commands/extension/release-changed.test.ts b/src/commands/extension/release-changed.test.ts new file mode 100644 index 0000000..1bb9343 --- /dev/null +++ b/src/commands/extension/release-changed.test.ts @@ -0,0 +1,282 @@ +import { execFileSync } from 'node:child_process'; +import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, expect } from 'vitest'; +import { output, test } from '../../test/config-dir.js'; +import { + changedDeps, + ciClone, + makeRepo, + release, + REPO, + writeExtension, + type Repo, + type Spec, +} from '../../test/release-repo.js'; +import { runRelease } from './release.js'; + +// Two extensions released on 2026-11-21 from the first commit; then only probe changes. +const twoExtensions = (records = true) => { + const repo = makeRepo(); + writeExtension(repo, 'extensions/probe', 'probe'); + writeExtension(repo, 'extensions/fixture', 'fixture'); + const first = repo.commit('two extensions'); + repo.tag('probe@2026.1121.1'); + repo.tag('fixture@2026.1121.1'); + repo.write('extensions/probe/index.js', "export const id = 'probe 2';\n"); + repo.write('README.md', 'outside both folders\n'); + repo.commit('change probe'); + const recorded = { 'probe@2026.1121.1': first, 'fixture@2026.1121.1': first }; + return { repo, first, records: records ? recorded : { 'probe@2026.1121.1': first } }; +}; + +const status = (dir: string) => + execFileSync('git', ['status', '--porcelain'], { cwd: dir, encoding: 'utf8' }).trim(); + +const remoteTags = (repo: Repo) => repo.git('ls-remote', '--tags', 'origin'); + +const oneExtension = (rel: string, id: string, spec?: Spec) => { + const repo = makeRepo(); + writeExtension(repo, rel, id, spec); + repo.commit('one'); + return repo; +}; + +describe('extension release --changed: what it releases', () => { + test('a dry run on two extensions names only the changed one and changes nothing', async () => { + const { repo, records } = twoExtensions(); + const dir = ciClone(repo); + expect(execFileSync('git', ['tag', '-l'], { cwd: dir, encoding: 'utf8' })).toBe(''); + const tagsBefore = remoteTags(repo); + const run = await release({ dir, w: { records }, opts: { dryRun: true } }); + expect(run.error).toBeNull(); + expect(run.lines).toEqual([ + `PASS master: ${run.sha} is on master`, + 'PASS unchanged: fixture (extensions/fixture) is the same as fixture@2026.1121.1', + 'PASS changed: probe (extensions/probe) differs from probe@2026.1121.1: release probe@2026.1122.1', + 'PASS dry run: would release probe@2026.1122.1; nothing was written, tagged, pushed or published', + ]); + expect(run.calls).toEqual([ + `gh release download fixture@2026.1121.1 -R ${REPO} -p agentage-extension.json -O -`, + `gh release download probe@2026.1121.1 -R ${REPO} -p agentage-extension.json -O -`, + ]); + expect(status(dir)).toBe(''); + expect(remoteTags(repo)).toBe(tagsBefore); + expect(run.result).toMatchObject({ dryRun: true, unchanged: ['fixture'] }); + }); + + test('a release: tag on the commit, images, the record with --target, npm; nothing committed', async () => { + const { repo, records } = twoExtensions(); + const dir = ciClone(repo); + const run = await release({ dir, w: { records } }); + expect(run.error).toBeNull(); + const tag = 'probe@2026.1122.1'; + expect(run.calls.filter((c) => !c.includes('2026.1121.1'))).toEqual([ + 'npm --version', + `gh api repos/${REPO}/git/refs -f ref=refs/tags/${tag} -f sha=${run.sha}`, + `gh release download ${tag} -R ${REPO} -p agentage-extension.json -O -`, + 'docker manifest inspect ghcr.io/agentage/probe-pages:2026.1122.1', + 'build probe@2026.1122.1', + 'npm view @agentage/extension-probe@2026.1122.1 version', + 'npm publish --access public --provenance --ignore-scripts', + `gh release view ${tag} -R ${REPO}`, + `gh release create ${tag} dist/agentage-extension.json --title ${tag} --notes Images by digest: agentage-extension.json --target ${run.sha} -R ${REPO}`, + ]); + expect(run.lines).toContain('PASS version: probe is 2026.1122.1 in this CI copy only'); + expect(run.lines).toContain(`PASS tag: ${tag} created on ${run.sha}`); + expect(status(dir)).toBe('M extensions/probe/package.json'); + const pkg = JSON.parse(readFileSync(join(dir, 'extensions/probe/package.json'), 'utf8')); + expect(pkg.repository.url).toBe(`git+https://github.com/${REPO}.git`); + expect(execFileSync('git', ['rev-parse', 'HEAD'], { cwd: dir, encoding: 'utf8' }).trim()).toBe( + run.sha + ); + expect(run.result).toEqual({ + released: [{ id: 'probe', version: '2026.1122.1', tag, built: true, published: true }], + unchanged: ['fixture'], + }); + }); + + test('nothing changed: exit 0, nothing released, no tag, build or npm call', async () => { + const repo = makeRepo(); + writeExtension(repo, 'extensions/probe', 'probe'); + writeExtension(repo, 'extensions/fixture', 'fixture'); + const first = repo.commit('two extensions'); + repo.tag('probe@2026.1121.1'); + repo.tag('fixture@2026.1121.1'); + const records = { 'probe@2026.1121.1': first, 'fixture@2026.1121.1': first }; + repo.write('README.md', 'only the readme\n'); + repo.commit('readme'); + const run = await release({ dir: ciClone(repo), w: { records } }); + expect(run.error).toBeNull(); + expect(run.result).toEqual({ released: [], unchanged: ['fixture', 'probe'] }); + expect(run.calls.every((c) => c.startsWith('gh release download'))).toBe(true); + }); + + test('a dropped run is caught up: a later commit that changes only the README releases probe', async () => { + const { repo, records } = twoExtensions(); + repo.write('README.md', 'a later commit, outside both folders\n'); + repo.commit('readme only'); + const run = await release({ dir: ciClone(repo), w: { records }, opts: { dryRun: true } }); + expect(run.lines).toContain( + 'PASS changed: probe (extensions/probe) differs from probe@2026.1121.1: release probe@2026.1122.1' + ); + }); + + test('an extension with no @* tag yet is changed', async () => { + const dir = ciClone(oneExtension('extensions/probe', 'probe')); + const run = await release({ dir, opts: { dryRun: true } }); + expect(run.lines).toContain( + 'PASS changed: probe (extensions/probe) has no probe@* tag yet: release probe@2026.1122.1' + ); + }); + + test('the root layout: one extension at the root, private, so no npm', async () => { + const repo = oneExtension('.', 'root', { private: true }); + repo.tag('root@2026.1121.1'); + repo.write('index.js', 'changed\n'); + repo.commit('change'); + const dir = ciClone(repo); + const run = await release({ dir }); + expect(run.error).toBeNull(); + expect(run.lines[1]).toBe( + 'PASS changed: root (.) differs from root@2026.1121.1: release root@2026.1122.1' + ); + expect(run.lines).toContain('PASS npm: private package, not published'); + expect(run.calls.some((c) => c.startsWith('npm'))).toBe(false); + expect(status(dir)).toBe('M package.json'); + }); + + test('the second release of a day takes N + 1', async () => { + const repo = oneExtension('extensions/probe', 'probe'); + const first = repo.git('rev-parse', 'HEAD'); + repo.tag('probe@2026.1122.1'); + repo.write('extensions/probe/index.js', 'two\n'); + repo.commit('two'); + const dir = ciClone(repo); + const run = await release({ dir, w: { records: { 'probe@2026.1122.1': first } } }); + expect(run.error).toBeNull(); + expect(run.calls).toContain('build probe@2026.1122.2'); + }); + + test('a last tag with no record (a failed release) is changed: a new N', async () => { + const { repo, records } = twoExtensions(false); + const run = await release({ dir: ciClone(repo), w: { records }, opts: { dryRun: true } }); + expect(run.lines).toContain( + 'PASS changed: fixture (extensions/fixture) equals fixture@2026.1121.1, which has no record: release fixture@2026.1122.1' + ); + }); + + test('a re-run of the commit its last tag is on resumes that version', async () => { + const repo = oneExtension('extensions/probe', 'probe'); + repo.tag('probe@2026.1122.1'); + const dir = ciClone(repo); + const sha = repo.git('rev-parse', 'HEAD'); + const w = { refFails: 'Reference already exists (HTTP 422)', refAt: sha }; + const run = await release({ dir, w }); + expect(run.error).toBeNull(); + expect(run.lines).toContain( + 'PASS changed: probe (extensions/probe) probe@2026.1122.1 is on this commit: resume it: release probe@2026.1122.1' + ); + expect(run.lines).toContain(`PASS tag: probe@2026.1122.1 is on ${sha}`); + }); +}); + +describe('extension release --changed: the guards', () => { + test('a tag on another commit is refused before any build', async () => { + const dir = ciClone(oneExtension('extensions/probe', 'probe')); + const w = { refFails: 'Reference already exists', refAt: 'b'.repeat(40) }; + const run = await release({ dir, w }); + expect(run.error).toContain(`is on ${'b'.repeat(40)}`); + expect(run.error).toContain('a moved tag is refused'); + expect(run.calls.some((c) => c.startsWith('build'))).toBe(false); + }); + + test('a tag call that fails for another reason stops the release', async () => { + const dir = ciClone(oneExtension('extensions/probe', 'probe')); + const run = await release({ dir, w: { refFails: 'HTTP 403' } }); + expect(run.error).toBe('probe: FAIL tag: HTTP 403'); + }); + + test('a record check that cannot answer stops the release', async () => { + const { repo } = twoExtensions(); + const run = await release({ dir: ciClone(repo), w: { downloadFails: 'HTTP 502' } }); + expect(run.error).toContain('FAIL changed: cannot tell whether fixture@2026.1121.1'); + }); + + test('a commit that is not on master is refused', async () => { + const repo = oneExtension('extensions/probe', 'probe'); + const env = { GITHUB_REPOSITORY: REPO, GITHUB_SHA: 'c'.repeat(40) }; + const run = await release({ dir: ciClone(repo), env }); + expect(run.error).toContain(`FAIL master: ${'c'.repeat(40)} is not on master`); + }); + + test('inputs: no repo is refused; no GITHUB_SHA reads HEAD; outside git, it stops', async () => { + const dir = ciClone(oneExtension('extensions/probe', 'probe')); + expect((await release({ dir, env: {} })).error).toContain('GITHUB_REPOSITORY is not set'); + const head = await release({ dir, env: { GITHUB_REPOSITORY: REPO }, opts: { dryRun: true } }); + expect(head.lines[0]).toBe(`PASS master: ${head.sha} is on master`); + const empty = mkdtempSync(join(tmpdir(), 'agentage-nogit-')); + const outside = await output(() => + runRelease({ dir: empty, changed: true }, changedDeps({}, [], { GITHUB_REPOSITORY: REPO })) + ); + expect(outside.error).toContain('FAIL inputs: git rev-parse'); + }); + + test('a repo with no extension package is refused', async () => { + const repo = makeRepo(); + repo.commit('nothing'); + const run = await release({ dir: ciClone(repo) }); + expect(run.error).toBe('FAIL folders: no extension package at the root or in extensions/*'); + }); + + test('a file the run did not write makes the tree dirty: the build is refused', async () => { + const dir = ciClone(oneExtension('extensions/probe', 'probe')); + writeFileSync(join(dir, 'stray.txt'), 'x'); + const run = await release({ dir }); + expect(run.code).toBe('uncommitted_changes'); + expect(run.error).toContain('?? stray.txt'); + expect(run.calls.some((c) => c.startsWith('build'))).toBe(false); + }); + + test('the template id is refused before its tag', async () => { + const dir = ciClone(oneExtension('.', 'template')); + const run = await release({ dir }); + expect(run.error).toContain('FAIL id: this repo is the starting point'); + expect(run.calls.some((c) => c.startsWith('gh api'))).toBe(false); + }); + + test('--dry-run needs --changed; without --changed it is the v* release', async () => { + const dir = ciClone(oneExtension('.', 'probe')); + const deps = changedDeps({}, [], {}); + const dry = await output(() => runRelease({ dir, dryRun: true }, deps)); + expect(dry).toMatchObject({ code: 'invalid_argument', error: '--dry-run goes with --changed' }); + const tagged = await output(() => runRelease({ dir }, deps)); + expect(tagged.error).toContain('FAIL inputs: GITHUB_REF_NAME is not set'); + }); +}); + +describe('extension release --changed: an api part', () => { + test('its contracts carry the version: rewritten in the CI copy; the one image too', async () => { + const dir = ciClone(oneExtension('extensions/probe', 'probe', { api: true })); + const run = await release({ dir }); + expect(run.error).toBeNull(); + expect(run.calls).toContain('writeContracts'); + expect(run.calls).toContain('build probe@2026.1122.1 container'); + expect(run.calls).toContain('docker manifest inspect ghcr.io/agentage/probe:2026.1122.1'); + expect(status(dir).split('\n').sort()).toEqual([ + '?? extensions/probe/openapi.json', + 'M extensions/probe/package.json', + ]); + }); + + test('a contract write that fails stops the release before its tag', async () => { + const dir = ciClone(oneExtension('extensions/probe', 'probe', { api: true })); + const writeContracts = async () => { + throw new Error('dist is not built: run npm run build'); + }; + const run = await release({ dir }, { writeContracts }); + expect(run.error).toBe('probe: FAIL contracts: dist is not built: run npm run build'); + expect(run.calls.some((c) => c.startsWith('gh api'))).toBe(false); + }); +}); diff --git a/src/commands/extension/release-changed.ts b/src/commands/extension/release-changed.ts new file mode 100644 index 0000000..1187c02 --- /dev/null +++ b/src/commands/extension/release-changed.ts @@ -0,0 +1,163 @@ +import { join } from 'node:path'; +import type { ExtensionPackage } from '@agentage/extension/tool'; +import { CliError } from '../../lib/json-output.js'; +import type { ExtensionReleaseOptions, ReleaseDeps } from './release.js'; +import { writeCiCopy } from './release-folders.js'; +import { imagesOf, releaseGuard, type Exec } from './release-guard.js'; +import { fetchTags, git, planRelease, type Plan, type Planned } from './release-plan.js'; +import { rowsOf, summary, type Row } from './release-summary.js'; +import { + attach, + buildImages, + fail, + idChecks, + npmVersion, + onMaster, + publish, + PUBLISH_SECONDS, + scoped, + step, + takeSecrets, +} from './release-steps.js'; + +type Session = { + root: string; + run: Exec; + deps: ReleaseDeps; + secrets: Record; + sha: string; + repo: string; + timeout: number; + written: string[]; +}; + +const inputs = async (run: Exec, env: NodeJS.ProcessEnv) => { + const repo = env['GITHUB_REPOSITORY']; + if (!repo) return fail('inputs: GITHUB_REPOSITORY is not set; run it in CI on a push to master'); + const sha = env['GITHUB_SHA'] || (await git(run, ['rev-parse', 'HEAD'], 'inputs')).trim(); + return { repo, sha }; +}; + +// The build needs a committed tree: only the CI copy files this run wrote may differ. +const committedBut = (s: Session) => async (): Promise => { + const args = ['status', '--porcelain', '--', '.', ...s.written.map((f) => `:(exclude)${f}`)]; + const dirty = (await git(s.run, args, 'build')).trim(); + if (dirty) + throw new CliError('uncommitted_changes', `uncommitted changes: ${dirty}: commit first`); +}; + +// Tag first: a failed build still uses up its N, so the next run takes a new version. +const createTag = async (s: Session, tag: string): Promise => { + const ref = ['-f', `ref=refs/tags/${tag}`, '-f', `sha=${s.sha}`]; + const made = await s.run('gh', ['api', `repos/${s.repo}/git/refs`, ...ref]); + if (made.ok) return step(`tag: ${tag} created on ${s.sha}`); + if (!/Reference already exists/.test(made.err)) fail(`tag: ${made.err}`); + const at = await s.run('gh', [ + 'api', + `repos/${s.repo}/git/ref/tags/${tag}`, + '--jq', + '.object.sha', + ]); + const on = at.out.trim(); + if (on !== s.sha) fail(`tag: ${tag} is on ${on || at.err}, not ${s.sha}: a moved tag is refused`); + step(`tag: ${tag} is on ${s.sha}`); +}; + +// The date version in package.json, the lock and the committed contracts that carry it. +const prepare = async (s: Session, p: Planned): Promise => { + const dir = join(s.root, p.rel); + s.written.push(...(await writeCiCopy(s.root, p, p.version, s.repo))); + const tool = await s.deps.tool(); + const pkg = await tool.readManifest(dir); + idChecks(pkg); + const { parts } = imagesOf(pkg); + if (parts.includes('api') || parts.includes('mcp')) { + const files = await tool + .writeContracts(dir) + .catch((e: Error) => fail(`contracts: ${e.message}`)); + s.written.push(...files.map((f) => join(p.rel, f))); + } + step(`version: ${p.id} is ${p.version} in this CI copy only`); + return pkg; +}; + +const npmStep = async (s: Session, run: Exec, dir: string, pkg: ExtensionPackage) => { + if (pkg['private'] === true) return step('npm: private package, not published'); + const push = scoped(s.deps.exec(dir, PUBLISH_SECONDS), s.secrets); + await publish(run, push, pkg, s.secrets['npm']?.['NPM_TOKEN']); +}; + +// A released version is never rebuilt: the guard reuses its record, else it builds the images. +const imagesStep = async (s: Session, p: Planned, run: Exec, pkg: ExtensionPackage) => { + const { parts, oneImage } = imagesOf(pkg); + const dir = join(s.root, p.rel); + const g = { dir, tag: p.tag, sha: s.sha, repo: s.repo, id: p.id, version: p.version }; + const decision = await releaseGuard({ ...g, parts, oneImage }, run).catch((e: Error) => + fail(`guard: ${e.message}`) + ); + const built = decision === 'build'; + step(`guard: ${p.tag} ${built ? 'has no record and no image: build' : 'is released: npm only'}`); + return built ? buildImages(dir, oneImage, s.deps.tool, committedBut(s)) : []; +}; + +// The record is the "released" marker: it goes up only after npm has the version. +const releaseOne = async (s: Session, p: Planned) => { + const pkg = await prepare(s, p); + const dir = join(s.root, p.rel); + const run = scoped(s.deps.exec(dir, s.timeout), s.secrets); + const isPrivate = pkg['private'] === true; + if (!isPrivate) await npmVersion(run); + await createTag(s, p.tag); + const records = await imagesStep(s, p, run, pkg); + await npmStep(s, run, dir, pkg); + if (records.length > 0) await attach(run, p.tag, s.repo, records, s.sha); + return { + id: p.id, + version: p.version, + tag: p.tag, + built: records.length > 0, + published: !isPrivate, + }; +}; + +// Every changed extension is tried; its folder then no longer counts as a change for the next build. +const releaseAll = async (s: Session, plan: Plan) => { + const released: Awaited>[] = []; + const rows = rowsOf(plan.refused, 'refused'); + for (const p of plan.changed) { + const row: Row = { id: p.id, version: p.version, result: 'released' }; + await releaseOne(s, p).then( + (r) => void released.push(r), + (err: unknown) => Object.assign(row, { result: 'failed', err }) + ); + s.written.push(p.rel); + rows.push(row); + } + rows.push(...rowsOf(plan.unchanged, 'unchanged')); + summary(rows); + return released; +}; + +const dryRun = (plan: Plan) => { + const tags = plan.changed.map((p) => p.tag).join(', ') || 'nothing'; + step(`dry run: would release ${tags}; nothing was written, tagged, pushed or published`); + summary(rowsOf(plan.refused, 'refused')); + return { dryRun: true, changed: plan.changed, unchanged: plan.unchanged.map((f) => f.id) }; +}; + +// Each extension changed since its last @* tag gets a date version, its tag, images and npm. +export const runChangedRelease = async ( + { dir = '.', timeout = 60, dryRun: dry }: ExtensionReleaseOptions, + deps: ReleaseDeps +): Promise => { + const secrets = takeSecrets(deps.env); + const run = scoped(deps.exec(dir, timeout), secrets); + const { repo, sha } = await inputs(run, deps.env); + await onMaster(run, sha); + await fetchTags(run); + const now = deps.now?.() ?? new Date(); + const plan = await planRelease({ root: dir, run, sha, repo, now }); + if (dry) return dryRun(plan); + const s: Session = { root: dir, run, deps, secrets, sha, repo, timeout, written: [] }; + return { released: await releaseAll(s, plan), unchanged: plan.unchanged.map((f) => f.id) }; +}; diff --git a/src/commands/extension/release-date.test.ts b/src/commands/extension/release-date.test.ts new file mode 100644 index 0000000..8628143 --- /dev/null +++ b/src/commands/extension/release-date.test.ts @@ -0,0 +1,68 @@ +import { validateManifest } from '@agentage/extension/tool'; +import { describe, expect, it } from 'vitest'; +import { dateVersion, dayOf, lastTag, tagOf, versionOfTag } from './release-date.js'; + +// The kit's own version check: what readManifest accepts in package.json. +const valid = (version: string): boolean => { + const pkg = { name: '@agentage/extension-probe', version, engines: { agentage: '^0.5' } }; + try { + validateManifest({ ...pkg, agentage: { id: 'probe', parts: { pages: true } } }); + return true; + } catch { + return false; + } +}; + +describe('the date version YYYY.MDD.N', () => { + it.each([ + ['2027-01-05T00:00:00Z', '2027.105.1'], + ['2026-03-09T12:00:00Z', '2026.309.1'], + ['2026-11-22T10:00:00Z', '2026.1122.1'], + ['2026-12-31T23:59:59Z', '2026.1231.1'], + ['2026-01-01T00:00:00Z', '2026.101.1'], + ])('%s is %s, valid semver with no leading zero', (at, version) => { + expect(dateVersion('probe', [], new Date(at))).toBe(version); + expect(valid(version)).toBe(true); + }); + + it('the day is the UTC day, not the local one', () => { + expect(dayOf(new Date('2026-11-22T23:30:00-05:00'))).toBe('2026.1123'); + }); + + it('the second release of a day is N + 1 over the highest N of that id that day', () => { + const tags = [ + 'probe@2026.1122.1', + 'probe@2026.1122.2', + 'probe@2026.1121.7', + 'fixture@2026.1122.5', + ]; + expect(dateVersion('probe', tags, new Date('2026-11-22T10:00:00Z'))).toBe('2026.1122.3'); + expect(dateVersion('probe', ['probe@2026.1122.9'], new Date('2026-11-22'))).toBe( + '2026.1122.10' + ); + }); + + it('a day prefix of another day is not that day: 2026.112 is not 2026.1122', () => { + expect(dateVersion('probe', ['probe@2026.112.4'], new Date('2026-11-22'))).toBe('2026.1122.1'); + }); + + it('the tag form is @', () => { + expect(tagOf('probe', '2027.105.1')).toBe('probe@2027.105.1'); + }); +}); + +describe('the last @* tag', () => { + it('compares numbers, not text: N=10 after 9, January after December', () => { + expect(lastTag('probe', ['probe@2026.1122.9', 'probe@2026.1122.10'])).toBe( + 'probe@2026.1122.10' + ); + expect(lastTag('probe', ['probe@2027.105.1', 'probe@2026.1231.4'])).toBe('probe@2027.105.1'); + }); + + it('skips another id, a leading zero and a prerelease; none is undefined', () => { + const tags = ['probe-api@2030.101.1', 'probe@2027.0105.1', 'probe@2028.101.1-rc.1', 'v1.0.0']; + expect(lastTag('probe', [...tags, 'probe@0.3.0'])).toBe('probe@0.3.0'); + expect(lastTag('probe', tags)).toBeUndefined(); + expect(versionOfTag('probe', 'fixture@2026.1122.1')).toBeUndefined(); + }); +}); diff --git a/src/commands/extension/release-date.ts b/src/commands/extension/release-date.ts new file mode 100644 index 0000000..d955bfd --- /dev/null +++ b/src/commands/extension/release-date.ts @@ -0,0 +1,41 @@ +// The three numbers of a plain version: no prerelease, no leading zero. +const PLAIN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/; + +type Numbers = [number, number, number]; + +export const tagOf = (id: string, version: string): string => `${id}@${version}`; + +// The version of `@`; undefined for another id or another form. +export const versionOfTag = (id: string, tag: string): string | undefined => { + const version = tag.startsWith(`${id}@`) ? tag.slice(id.length + 1) : ''; + return PLAIN.test(version) ? version : undefined; +}; + +const numbersOf = (version: string): Numbers => version.split('.').map(Number) as Numbers; + +const compare = (a: Numbers, b: Numbers): number => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]; + +// The `@*` tags newest first by number, never by text: 2027.105.1 is after 2026.1231.9. +export const newestTags = (id: string, tags: string[]): string[] => { + const plain = tags.flatMap((tag) => { + const version = versionOfTag(id, tag); + return version ? [{ tag, n: numbersOf(version) }] : []; + }); + return plain.sort((a, b) => compare(b.n, a.n)).map((p) => p.tag); +}; + +export const lastTag = (id: string, tags: string[]): string | undefined => newestTags(id, tags)[0]; + +// YYYY.MDD of a UTC day: month times 100 plus day, so it never has a leading zero. +export const dayOf = (now: Date): string => + `${now.getUTCFullYear()}.${(now.getUTCMonth() + 1) * 100 + now.getUTCDate()}`; + +// YYYY.MDD.N: N is one more than the highest N tagged for this id on this UTC day. +export const dateVersion = (id: string, tags: string[], now: Date): string => { + const day = dayOf(now); + const taken = tags + .map((tag) => versionOfTag(id, tag)) + .filter((v): v is string => v?.startsWith(`${day}.`) === true) + .map((v) => numbersOf(v)[2]); + return `${day}.${Math.max(0, ...taken) + 1}`; +}; diff --git a/src/commands/extension/release-folders.test.ts b/src/commands/extension/release-folders.test.ts new file mode 100644 index 0000000..7b9c6a5 --- /dev/null +++ b/src/commands/extension/release-folders.test.ts @@ -0,0 +1,96 @@ +import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { extensionFolders, writeCiCopy } from './release-folders.js'; + +const tree = (files: Record): string => { + const root = mkdtempSync(join(tmpdir(), 'agentage-folders-')); + for (const [rel, value] of Object.entries(files)) { + mkdirSync(join(root, rel, '..'), { recursive: true }); + writeFileSync(join(root, rel), typeof value === 'string' ? value : JSON.stringify(value)); + } + return root; +}; + +const ext = (id: string) => ({ + name: `@agentage/extension-${id}`, + version: '0.0.0', + agentage: { id }, +}); + +const json = (root: string, rel: string): Record => + JSON.parse(readFileSync(join(root, rel), 'utf8')) as Record; + +describe('extension folders', () => { + it('each extensions/ with an agentage package, sorted; others are skipped', async () => { + const root = tree({ + 'package.json': { name: 'examples', private: true }, + 'extensions/probe/package.json': ext('probe'), + 'extensions/fixture/package.json': ext('fixture'), + 'extensions/notes/README.md': 'not an extension', + 'extensions/lib/package.json': { name: 'lib' }, + 'extensions/file.txt': 'x', + }); + expect(await extensionFolders(root)).toEqual([ + { rel: 'extensions/fixture', id: 'fixture' }, + { rel: 'extensions/probe', id: 'probe' }, + ]); + }); + + it('one extension at the root when there is no extensions/*', async () => { + expect(await extensionFolders(tree({ 'package.json': ext('root') }))).toEqual([ + { rel: '.', id: 'root' }, + ]); + }); + + it('none: no extension package anywhere', async () => { + expect(await extensionFolders(tree({ 'package.json': { name: 'x' } }))).toEqual([]); + expect(await extensionFolders(tree({ 'README.md': 'x' }))).toEqual([]); + }); + + it('a package.json that is not JSON stops the release', async () => { + await expect(extensionFolders(tree({ 'package.json': '{' }))).rejects.toThrow(/JSON/); + }); +}); + +describe('the CI copy', () => { + it('writes the version and the releasing repo into package.json and the lock', async () => { + const lock = { name: 'x', version: '0.0.0', packages: { '': { version: '0.0.0' } } }; + const root = tree({ + 'extensions/probe/package.json': { ...ext('probe'), repository: 'github:agentage/old' }, + 'extensions/probe/package-lock.json': lock, + }); + const folder = { rel: 'extensions/probe', id: 'probe' }; + const written = await writeCiCopy(root, folder, '2026.1122.1', 'agentage/examples'); + expect(written).toEqual([ + 'extensions/probe/package.json', + 'extensions/probe/package-lock.json', + ]); + const pkg = json(root, 'extensions/probe/package.json'); + expect(pkg['version']).toBe('2026.1122.1'); + expect(pkg['repository']).toEqual({ + type: 'git', + url: 'git+https://github.com/agentage/examples.git', + directory: 'extensions/probe', + }); + const after = json(root, 'extensions/probe/package-lock.json'); + expect(after['version']).toBe('2026.1122.1'); + expect(after['packages']).toEqual({ '': { version: '2026.1122.1' } }); + }); + + it('the root layout: no directory, a lock with no packages map, or no lock', async () => { + const root = tree({ 'package.json': ext('root'), 'package-lock.json': { version: '0' } }); + const folder = { rel: '.', id: 'root' }; + expect(await writeCiCopy(root, folder, '2027.105.1', 'agentage/agentage.io')).toEqual([ + 'package.json', + 'package-lock.json', + ]); + expect(json(root, 'package.json')['repository']).toEqual({ + type: 'git', + url: 'git+https://github.com/agentage/agentage.io.git', + }); + const bare = tree({ 'package.json': ext('root') }); + expect(await writeCiCopy(bare, folder, '2027.105.1', 'agentage/x')).toEqual(['package.json']); + }); +}); diff --git a/src/commands/extension/release-folders.ts b/src/commands/extension/release-folders.ts new file mode 100644 index 0000000..5059a28 --- /dev/null +++ b/src/commands/extension/release-folders.ts @@ -0,0 +1,70 @@ +import { readdir, readFile, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; + +export type Folder = { rel: string; id: string }; + +type Json = Record; + +// A missing file reads as undefined; a file that is not JSON stops the release. +const readJson = (file: string): Promise => + readFile(file, 'utf8').then( + (text) => JSON.parse(text) as Json, + () => undefined + ); + +const idAt = async (root: string, rel: string): Promise => { + const pkg = await readJson(join(root, rel, 'package.json')); + const id = (pkg?.['agentage'] as Json | undefined)?.['id']; + return typeof id === 'string' ? id : undefined; +}; + +// Each extensions/ with an agentage package; with none, the root package is the one extension. +export const extensionFolders = async (root: string): Promise => { + const entries = await readdir(join(root, 'extensions'), { withFileTypes: true }).catch(() => []); + const names = entries.filter((e) => e.isDirectory()).map((e) => e.name); + const folders: Folder[] = []; + for (const name of names.sort()) { + const id = await idAt(root, join('extensions', name)); + if (id) folders.push({ rel: join('extensions', name), id }); + } + if (folders.length > 0) return folders; + const id = await idAt(root, '.'); + return id ? [{ rel: '.', id }] : []; +}; + +const writeJson = async (file: string, value: unknown): Promise => + writeFile(file, `${JSON.stringify(value, null, 2)}\n`); + +// The image source label and npm provenance both read `repository`: it names the releasing repo. +const repositoryOf = (repo: string, rel: string): Json => ({ + type: 'git', + url: `git+https://github.com/${repo}.git`, + ...(rel === '.' ? {} : { directory: rel }), +}); + +// The lock's root version too, so npm ci in the image reads the same package. +const writeLock = async (root: string, rel: string, version: string): Promise => { + const file = join(rel, 'package-lock.json'); + const lock = await readJson(join(root, file)); + if (!lock) return []; + lock['version'] = version; + const own = (lock['packages'] as Record | undefined)?.['']; + if (own) own['version'] = version; + await writeJson(join(root, file), lock); + return [file]; +}; + +// The CI copy only: never committed. Returns the files it wrote, relative to the root. +export const writeCiCopy = async ( + root: string, + { rel }: Folder, + version: string, + repo: string +): Promise => { + const file = join(rel, 'package.json'); + const pkg = JSON.parse(await readFile(join(root, file), 'utf8')) as Json; + pkg['version'] = version; + pkg['repository'] = repositoryOf(repo, rel); + await writeJson(join(root, file), pkg); + return [file, ...(await writeLock(root, rel, version))]; +}; diff --git a/src/commands/extension/release-plan.ts b/src/commands/extension/release-plan.ts new file mode 100644 index 0000000..9645caf --- /dev/null +++ b/src/commands/extension/release-plan.ts @@ -0,0 +1,108 @@ +import { dateVersion, lastTag, newestTags, tagOf } from './release-date.js'; +import { extensionFolders, type Folder } from './release-folders.js'; +import { RECORD, type Exec } from './release-guard.js'; +import { fail, step } from './release-steps.js'; + +export type Planned = Folder & { version: string; tag: string; why: string }; + +export type Refused = Folder & { err: unknown }; + +export type Plan = { changed: Planned[]; unchanged: Folder[]; refused: Refused[] }; + +export type PlanInput = { root: string; run: Exec; sha: string; repo: string; now: Date }; + +// A build that always fails stops here: no new tag after this many tags in a row with no record. +export const UNRECORDED_LIMIT = 3; + +// Fail closed: a git call that cannot answer stops the release, never reads as "no change". +export const git = async (run: Exec, args: string[], what: string): Promise => { + const ran = await run('git', args); + if (!ran.ok) fail(`${what}: git ${args[0] ?? ''}: ${ran.err}`); + return ran.out; +}; + +// A default CI checkout has no tags and one commit: the ancestor check needs both. +export const fetchTags = async (run: Exec): Promise => { + const shallow = (await git(run, ['rev-parse', '--is-shallow-repository'], 'tags')).trim(); + const deepen = shallow === 'true' ? ['--unshallow'] : []; + await git(run, ['fetch', '-q', '--tags', ...deepen, 'origin'], 'tags'); +}; + +// Only "not found" means "no record"; any other answer stops the release. +const hasRecord = async (c: PlanInput, tag: string): Promise => { + const args = ['release', 'download', tag, '-R', c.repo, '-p', RECORD, '-O', '-']; + const got = await c.run('gh', args); + if (got.ok) return true; + if (!/release not found|no assets match|no assets to download/.test(got.err)) + fail(`changed: cannot tell whether ${tag} has its record: ${got.err}`); + return false; +}; + +// The newest tags with no record, up to the first that has one. +const unrecorded = async (c: PlanInput, f: Folder, tags: string[]): Promise => { + const missing: string[] = []; + for (const tag of newestTags(f.id, tags).slice(0, UNRECORDED_LIMIT)) { + if (await hasRecord(c, tag)) break; + missing.push(tag); + } + if (missing.length === UNRECORDED_LIMIT) + fail(`stuck: ${missing.join(', ')} have no record: fix the release, or remove those tags`); + return missing; +}; + +// From the last tag, not the push range: a run the concurrency group dropped is caught up here. +const whyOf = async (c: PlanInput, f: Folder, tags: string[], last?: string) => { + if (!last) return `has no ${f.id}@* tag yet`; + const missing = await unrecorded(c, f, tags); + const diff = await git(c.run, ['diff', '--name-only', last, c.sha, '--', f.rel], 'changed'); + if (diff.trim()) return `differs from ${last}`; + // A release that failed after its tag: the next commit releases it with a new N. + if (missing[0] === last) return `equals ${last}, which has no record`; + return undefined; +}; + +// A re-run of an old commit must not give older code a higher version than its last tag. +const inHistory = async (c: PlanInput, last: string, at: string): Promise => { + const ahead = await git(c.run, ['rev-list', '--count', `${c.sha}..${at}`], 'history'); + if (ahead.trim() !== '0') + fail(`history: ${last} is on ${at}, which is not before ${c.sha}: an older commit is refused`); +}; + +const planned = (f: Folder, version: string, why: string): Planned => { + const tag = tagOf(f.id, version); + step(`changed: ${f.id} (${f.rel}) ${why}: release ${tag}`); + return { ...f, version, tag, why }; +}; + +const planOne = async (c: PlanInput, f: Folder): Promise => { + const tags = (await git(c.run, ['tag', '-l', `${f.id}@*`], 'tags')).split('\n').filter(Boolean); + const last = lastTag(f.id, tags); + // A re-run of the commit its last tag is on: resume that version (the guard reuses or builds). + const at = last ? (await git(c.run, ['rev-list', '-n', '1', last], 'tags')).trim() : ''; + if (last && at === c.sha) + return planned(f, last.slice(f.id.length + 1), `${last} is on this commit: resume it`); + if (last) await inHistory(c, last, at); + const why = await whyOf(c, f, tags, last); + if (why) return planned(f, dateVersion(f.id, tags, c.now), why); + step(`unchanged: ${f.id} (${f.rel}) is the same as ${String(last)}`); + return undefined; +}; + +// One refused extension never stops the plan of the others. +const sort = async (c: PlanInput, f: Folder, plan: Plan): Promise => { + try { + const p = await planOne(c, f); + if (p) plan.changed.push(p); + else plan.unchanged.push(f); + } catch (e) { + plan.refused.push({ ...f, err: e }); + } +}; + +export const planRelease = async (c: PlanInput): Promise => { + const folders = await extensionFolders(c.root); + if (folders.length === 0) fail('folders: no extension package at the root or in extensions/*'); + const plan: Plan = { changed: [], unchanged: [], refused: [] }; + for (const f of folders) await sort(c, f, plan); + return plan; +}; diff --git a/src/commands/extension/release-steps.ts b/src/commands/extension/release-steps.ts new file mode 100644 index 0000000..3834676 --- /dev/null +++ b/src/commands/extension/release-steps.ts @@ -0,0 +1,139 @@ +import { mkdtemp, readFile, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { ExtensionPackage } from '@agentage/extension/tool'; +import { CliError } from '../../lib/json-output.js'; +import { runImageBuild, type Committed } from './build.js'; +import { type LoadKitTool } from './kit-tool.js'; +import { CONTAINER_RECORD, imagesOf, PART_SUFFIX, RECORD, type Exec } from './release-guard.js'; + +export const step = (line: string): void => console.log(`PASS ${line}`); + +export const fail = (line: string): never => { + throw new CliError('release_refused', `FAIL ${line}`); +}; + +// Tokens leave the environment, so docker build and npm lifecycle scripts never see them. +export const takeSecrets = (env: NodeJS.ProcessEnv): Record => { + const { GH_TOKEN, GITHUB_TOKEN, NPM_TOKEN } = env; + for (const name of ['GH_TOKEN', 'GITHUB_TOKEN', 'NPM_TOKEN']) delete env[name]; + const gh = GH_TOKEN ?? GITHUB_TOKEN; + return { gh: gh ? { GH_TOKEN: gh } : {}, npm: NPM_TOKEN ? { NPM_TOKEN } : {} }; +}; + +export const scoped = + (exec: Exec, secrets: Record): Exec => + (cmd, args) => + exec(cmd, args, secrets[cmd]); + +// Every image is pushed first. The records go up one call each, RECORD last: it is the "done" marker. +export const attach = async ( + run: Exec, + tag: string, + repo: string, + names: string[], + target?: string +): Promise => { + const notes = ['--title', tag, '--notes', `Images by digest: ${names.join(', ')}`]; + if (target) notes.push('--target', target); + let exists = (await run('gh', ['release', 'view', tag, '-R', repo])).ok; + for (const name of names) { + const file = join('dist', name); + const args = exists ? ['upload', tag, file] : ['create', tag, file, ...notes]; + const ran = await run('gh', ['release', ...args, '-R', repo]); + if (!ran.ok) fail(`record: ${ran.err}`); + exists = true; + } + step(`record: ${names.join(', ')} attached to release ${tag}`); +}; + +// The part images (v13 rows, the estate) and the one image (app hosts), all pushed by digest. +export const buildImages = async ( + dir: string, + oneImage: boolean, + tool: LoadKitTool, + committed?: Committed +) => { + await runImageBuild({ push: true, dir }, tool, committed); + if (!oneImage) return [RECORD]; + // The second compile may clean dist/: the part record is kept and written back. + const record = await readFile(join(dir, 'dist', RECORD)); + // The first build checked this HEAD; its own dist/ output must not read as a change. + await runImageBuild({ push: true, container: true, dir }, tool, async () => undefined); + await writeFile(join(dir, 'dist', RECORD), record); + return [CONTAINER_RECORD, RECORD]; +}; + +// Single quotes on purpose: npm expands ${NPM_TOKEN} itself, the token never lands on disk. +const tokenConfig = async (token?: string): Promise => { + if (!token) return []; + const file = join(await mkdtemp(join(tmpdir(), 'agentage-npm-')), '.npmrc'); + await writeFile(file, '//registry.npmjs.org/:_authToken=${NPM_TOKEN}\n'); + return ['--userconfig', file]; +}; + +// Only E404 means "not on npm"; a registry that cannot answer stops the release, never publishes. +const onNpm = async (run: Exec, args: string[], what: string): Promise => { + const viewed = await run('npm', ['view', ...args]); + if (viewed.ok) return viewed.out.trim() !== ''; + if (!/E404/.test(viewed.err)) fail(`npm: cannot tell whether ${what} is on npm: ${viewed.err}`); + return false; +}; + +// The upload with provenance signs first: its own bound, longer than the checks. +export const PUBLISH_SECONDS = 300; + +// A killed publish may have landed: stop, never stage it again; a re-run reads "already on npm". +const direct = async (push: Exec, spec: string, flags: string[]): Promise => { + const published = await push('npm', ['publish', ...flags]); + if (/timed out after/.test(published.err)) + fail( + `npm: publish of ${spec} ${published.err}; re-run the release: it reads "already on npm" if the upload landed` + ); + return published.ok; +}; + +// OIDC trusted publishing; a new name (NPM_TOKEN set) or an unauthorized direct publish is staged. +export const publish = async ( + run: Exec, + push: Exec, + { name, version }: ExtensionPackage, + token?: string +) => { + const cfg = await tokenConfig(token); + const spec = `${name}@${version}`; + if (await onNpm(run, [spec, 'version', ...cfg], spec)) + return step(`npm: ${spec} is already on npm`); + const flags = ['--access', 'public', '--provenance', '--ignore-scripts', ...cfg]; + const fresh = token !== undefined && !(await onNpm(run, [name, 'name', ...cfg], name)); + if (!fresh && (await direct(push, spec, flags))) return step(`npm: ${spec} published`); + const staged = await push('npm', ['stage', 'publish', ...flags]); + if (!staged.ok) fail(`npm: ${staged.err}`); + const why = fresh + ? 'a new name has no trusted publisher' + : 'direct publish not authorized: no validated trusted publisher'; + step(`npm: ${spec} staged for approval (${why})`); +}; + +export const npmVersion = async (run: Exec): Promise => { + const v = (await run('npm', ['--version'])).out.trim(); + const [major = 0, minor = 0, patch = 0] = v.split('.').map(Number); + if (major * 1e6 + minor * 1e3 + patch < 11_005_001) + fail(`npm: npm ${v} cannot publish with OIDC: needs npm >= 11.5.1`); + step(`npm: npm ${v}`); +}; + +export const idChecks = (pkg: ExtensionPackage): void => { + if (pkg.agentage.id === 'template') + fail('id: this repo is the starting point for extensions: create one, release that'); + step(`id: ${pkg.agentage.id} is not the template`); + if (imagesOf(pkg).oneImage && PART_SUFFIX.test(pkg.agentage.id)) + fail(`id: ${pkg.agentage.id} ends in a part name: it would name another extension's image`); +}; + +export const onMaster = async (run: Exec, sha: string): Promise => { + const fetched = await run('git', ['fetch', '-q', 'origin', 'master']); + if (!fetched.ok || !(await run('git', ['merge-base', '--is-ancestor', sha, 'origin/master'])).ok) + fail(`master: ${sha} is not on master${fetched.err ? `: ${fetched.err}` : ''}`); + step(`master: ${sha} is on master`); +}; diff --git a/src/commands/extension/release-summary.ts b/src/commands/extension/release-summary.ts new file mode 100644 index 0000000..12c73d9 --- /dev/null +++ b/src/commands/extension/release-summary.ts @@ -0,0 +1,27 @@ +export type Row = { id: string; version: string; result: string; err?: unknown }; + +const messageOf = (r: Row): string => `${r.id}: ${(r.err as Error).message}`; + +const table = (rows: Row[]): string[] => { + const idWidth = Math.max(2, ...rows.map((r) => r.id.length)); + const versionWidth = Math.max(7, ...rows.map((r) => r.version.length)); + const line = (id: string, version: string, result: string) => + `${id.padEnd(idWidth)} ${version.padEnd(versionWidth)} ${result}`; + return [line('id', 'version', 'result'), ...rows.map((r) => line(r.id, r.version, r.result))]; +}; + +// One table of every extension; any failure makes one non-zero exit after all were tried. +export const summary = (rows: Row[]): void => { + if (rows.length === 0) return; + for (const line of table(rows)) console.log(line); + const failed = rows.filter((r) => r.err !== undefined); + const first = failed[0]?.err as Error | undefined; + if (!first) return; + // The first error keeps its code; its message names every failed extension. + first.message = failed.map(messageOf).join('\n'); + throw first; +}; + +// Rows of extensions that get no version this run: refused (with its error) or unchanged. +export const rowsOf = (folders: { id: string; err?: unknown }[], result: string): Row[] => + folders.map((f) => ({ id: f.id, version: '-', result, err: f.err })); diff --git a/src/commands/extension/release.ts b/src/commands/extension/release.ts index 642d566..572eeca 100644 --- a/src/commands/extension/release.ts +++ b/src/commands/extension/release.ts @@ -1,135 +1,40 @@ -import { mkdtemp, readFile, writeFile } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; import { type Command } from 'commander'; import type { ExtensionPackage } from '@agentage/extension/tool'; import { addJson, CliError } from '../../lib/json-output.js'; -import { runImageBuild } from './build.js'; import { loadKitTool, type LoadKitTool } from './kit-tool.js'; +import { runChangedRelease } from './release-changed.js'; +import { execIn, imagesOf, releaseGuard, type Exec } from './release-guard.js'; import { - CONTAINER_RECORD, - execIn, - imagesOf, - PART_SUFFIX, - RECORD, - releaseGuard, -} from './release-guard.js'; -import { type Exec } from './release-guard.js'; - -export type ExtensionReleaseOptions = { dir?: string; timeout?: number; json?: boolean }; + attach, + buildImages, + fail, + idChecks, + npmVersion, + onMaster, + publish, + PUBLISH_SECONDS, + scoped, + step, + takeSecrets, +} from './release-steps.js'; + +export type ExtensionReleaseOptions = { + dir?: string; + timeout?: number; + json?: boolean; + changed?: boolean; + dryRun?: boolean; +}; export interface ReleaseDeps { exec: (cwd: string, seconds?: number) => Exec; tool: LoadKitTool; env: NodeJS.ProcessEnv; + now?: () => Date; } const defaultDeps: ReleaseDeps = { exec: execIn, tool: loadKitTool, env: process.env }; -const step = (line: string): void => console.log(`PASS ${line}`); - -const fail = (line: string): never => { - throw new CliError('release_refused', `FAIL ${line}`); -}; - -// Tokens leave the environment, so docker build and npm lifecycle scripts never see them. -const takeSecrets = (env: NodeJS.ProcessEnv): Record => { - const { GH_TOKEN, GITHUB_TOKEN, NPM_TOKEN } = env; - for (const name of ['GH_TOKEN', 'GITHUB_TOKEN', 'NPM_TOKEN']) delete env[name]; - const gh = GH_TOKEN ?? GITHUB_TOKEN; - return { gh: gh ? { GH_TOKEN: gh } : {}, npm: NPM_TOKEN ? { NPM_TOKEN } : {} }; -}; - -const scoped = - (exec: Exec, secrets: Record): Exec => - (cmd, args) => - exec(cmd, args, secrets[cmd]); - -// Every image is pushed first. The records go up one call each, RECORD last: it is the "done" marker. -const attach = async (run: Exec, tag: string, repo: string, names: string[]): Promise => { - const notes = ['--title', tag, '--notes', `Images by digest: ${names.join(', ')}`]; - let exists = (await run('gh', ['release', 'view', tag, '-R', repo])).ok; - for (const name of names) { - const file = join('dist', name); - const args = exists ? ['upload', tag, file] : ['create', tag, file, ...notes]; - const ran = await run('gh', ['release', ...args, '-R', repo]); - if (!ran.ok) fail(`record: ${ran.err}`); - exists = true; - } - step(`record: ${names.join(', ')} attached to release ${tag}`); -}; - -// The part images (v13 rows, the estate) and the one image (app hosts), all pushed by digest. -const buildImages = async (dir: string, oneImage: boolean, tool: LoadKitTool) => { - await runImageBuild({ push: true, dir }, tool); - if (!oneImage) return [RECORD]; - // The second compile may clean dist/: the part record is kept and written back. - const record = await readFile(join(dir, 'dist', RECORD)); - // The first build checked this HEAD; its own dist/ output must not read as a change. - await runImageBuild({ push: true, container: true, dir }, tool, async () => undefined); - await writeFile(join(dir, 'dist', RECORD), record); - return [CONTAINER_RECORD, RECORD]; -}; - -// Single quotes on purpose: npm expands ${NPM_TOKEN} itself, the token never lands on disk. -const tokenConfig = async (token?: string): Promise => { - if (!token) return []; - const file = join(await mkdtemp(join(tmpdir(), 'agentage-npm-')), '.npmrc'); - await writeFile(file, '//registry.npmjs.org/:_authToken=${NPM_TOKEN}\n'); - return ['--userconfig', file]; -}; - -// Only E404 means "not on npm"; a registry that cannot answer stops the release, never publishes. -const onNpm = async (run: Exec, args: string[], what: string): Promise => { - const viewed = await run('npm', ['view', ...args]); - if (viewed.ok) return viewed.out.trim() !== ''; - if (!/E404/.test(viewed.err)) fail(`npm: cannot tell whether ${what} is on npm: ${viewed.err}`); - return false; -}; - -// The upload with provenance signs first: its own bound, longer than the checks. -const PUBLISH_SECONDS = 300; - -// A killed publish may have landed: stop, never stage it again; a re-run reads "already on npm". -const direct = async (push: Exec, spec: string, flags: string[]): Promise => { - const published = await push('npm', ['publish', ...flags]); - if (/timed out after/.test(published.err)) - fail( - `npm: publish of ${spec} ${published.err}; re-run the release: it reads "already on npm" if the upload landed` - ); - return published.ok; -}; - -// OIDC trusted publishing; a new name (NPM_TOKEN set) or an unauthorized direct publish is staged. -const publish = async ( - run: Exec, - push: Exec, - { name, version }: ExtensionPackage, - token?: string -) => { - const cfg = await tokenConfig(token); - const spec = `${name}@${version}`; - if (await onNpm(run, [spec, 'version', ...cfg], spec)) - return step(`npm: ${spec} is already on npm`); - const flags = ['--access', 'public', '--provenance', '--ignore-scripts', ...cfg]; - const fresh = token !== undefined && !(await onNpm(run, [name, 'name', ...cfg], name)); - if (!fresh && (await direct(push, spec, flags))) return step(`npm: ${spec} published`); - const staged = await push('npm', ['stage', 'publish', ...flags]); - if (!staged.ok) fail(`npm: ${staged.err}`); - const why = fresh - ? 'a new name has no trusted publisher' - : 'direct publish not authorized: no validated trusted publisher'; - step(`npm: ${spec} staged for approval (${why})`); -}; - -const npmVersion = async (run: Exec): Promise => { - const v = (await run('npm', ['--version'])).out.trim(); - const [major = 0, minor = 0, patch = 0] = v.split('.').map(Number); - if (major * 1e6 + minor * 1e3 + patch < 11_005_001) - fail(`npm: npm ${v} cannot publish with OIDC: needs npm >= 11.5.1`); - step(`npm: npm ${v}`); -}; - const preflight = async ( run: Exec, pkg: ExtensionPackage, @@ -137,15 +42,8 @@ const preflight = async ( sha: string, isPrivate: boolean ) => { - if (pkg.agentage.id === 'template') - fail('id: this repo is the starting point for extensions: create one, release that'); - step(`id: ${pkg.agentage.id} is not the template`); - if (imagesOf(pkg).oneImage && PART_SUFFIX.test(pkg.agentage.id)) - fail(`id: ${pkg.agentage.id} ends in a part name: it would name another extension's image`); - const fetched = await run('git', ['fetch', '-q', 'origin', 'master']); - if (!fetched.ok || !(await run('git', ['merge-base', '--is-ancestor', sha, 'origin/master'])).ok) - fail(`master: ${sha} is not on master${fetched.err ? `: ${fetched.err}` : ''}`); - step(`master: ${sha} is on master`); + idChecks(pkg); + await onMaster(run, sha); const v = `v${pkg.version}`; if (tag !== v) fail(`tag: ${tag} is not ${v}, the package.json version; tag the commit that sets it`); @@ -185,6 +83,16 @@ export const runExtensionRelease = async ( return { id, version: pkg.version, tag, built: build, published: !isPrivate }; }; +// --changed: each changed extension of the repo; with no flag: the one package of a v* tag. +export const runRelease = async ( + opts: ExtensionReleaseOptions = {}, + deps: ReleaseDeps = defaultDeps +): Promise => { + if (opts.changed) return runChangedRelease(opts, deps); + if (opts.dryRun) throw new CliError('invalid_argument', '--dry-run goes with --changed'); + return runExtensionRelease(opts, deps); +}; + export const addRelease = ( group: Command, release: (opts: ExtensionReleaseOptions) => Promise @@ -201,5 +109,10 @@ export const addRelease = ( 'bound on each git, GitHub and npm check (default: 60; npm publish: 300)', Number ) + .option( + '--changed', + 'each extension (root or extensions/*) whose folder changed since its last @* tag; each keeps its own package-lock.json, shared root files never trigger a release' + ) + .option('--dry-run', 'with --changed: print what it would release, change nothing') ).action(release); }; diff --git a/src/program-deps.ts b/src/program-deps.ts index 7a2ec33..6e0bfe3 100644 --- a/src/program-deps.ts +++ b/src/program-deps.ts @@ -13,7 +13,7 @@ import { readHidden, runConfigure, stdinInput } from './commands/extension/confi import { runEnabled, runInstall, runRemove, terminalIo } from './commands/extension/lifecycle.js'; import { runList, runUpdate as runExtensionUpdate } from './commands/extension/lifecycle-list.js'; import { loadKitTool } from './commands/extension/kit-tool.js'; -import { runExtensionRelease } from './commands/extension/release.js'; +import { runRelease } from './commands/extension/release.js'; import { runExtensionSetup } from './commands/extension/setup.js'; import { runExtensionDown, runExtensionToken, runExtensionUp } from './commands/extension/up.js'; import { runStatus, statusDeps } from './commands/status/status.js'; @@ -91,7 +91,7 @@ export const defaultDeps: ProgramDeps = { extensionCreate: (opts) => runExtensionCreate(opts), extensionCheck: (opts) => runExtensionCheck(opts), extensionBuild: (opts) => runExtensionBuild(opts), - extensionRelease: (opts) => runExtensionRelease(opts), + extensionRelease: (opts) => runRelease(opts), extensionUp: (opts) => runExtensionUp(opts), extensionDown: (opts) => runExtensionDown(opts), extensionToken: (opts) => runExtensionToken(opts), diff --git a/src/program.test.ts b/src/program.test.ts index 7c3fea2..9aec1c9 100644 --- a/src/program.test.ts +++ b/src/program.test.ts @@ -336,6 +336,12 @@ describe('createProgram', () => { expect(failing.stderr()).toContain('boom'); }); + test('extension release --changed --dry-run passes both flags', async () => { + const h = makeDeps(); + expect(await h.exec('extension', 'release', '--changed', '--dry-run')).toBe(0); + expect(h.deps.extensionRelease).toHaveBeenLastCalledWith({ changed: true, dryRun: true }); + }); + test.for(['--profile=x', '--dry-run', '--check', '--disconnect'])( 'setup --latest with %s is a usage error', async (other) => { diff --git a/src/test/release-repo.ts b/src/test/release-repo.ts new file mode 100644 index 0000000..ef3689a --- /dev/null +++ b/src/test/release-repo.ts @@ -0,0 +1,179 @@ +/** + * A scratch git repo for `extension release --changed`: a bare origin, a clone that plays the CI + * checkout (real git), and gh, docker and npm played by `world`; every non-git call is logged. + */ +import { execFileSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { readManifest } from '@agentage/extension/tool'; +import type { KitTool } from '../commands/extension/kit-tool.js'; +import { execIn, type Exec, type Ran } from '../commands/extension/release-guard.js'; +import { + runRelease, + type ExtensionReleaseOptions, + type ReleaseDeps, +} from '../commands/extension/release.js'; +import { output } from './config-dir.js'; + +export type Spec = { private?: boolean; api?: boolean }; + +export const NOW = new Date('2026-11-22T10:00:00Z'); + +const git = (cwd: string, ...args: string[]): string => + execFileSync('git', ['-c', 'user.email=t@t', '-c', 'user.name=t', ...args], { + cwd, + encoding: 'utf8', + }).trim(); + +export const pkgOf = (id: string, spec: Spec = {}) => ({ + name: `@agentage/extension-${id}`, + version: '0.0.0', + engines: { agentage: '^0.5' }, + agentage: { + id, + parts: spec.api ? { pages: true, api: true, store: 'postgres' } : { pages: true }, + }, + ...(spec.private ? { private: true } : {}), +}); + +export interface Repo { + root: string; + work: string; + origin: string; + git: (...args: string[]) => string; + write: (rel: string, text: string) => void; + commit: (message: string) => string; + tag: (name: string) => void; +} + +// The source repo: a .gitignore for dist/, as an extension repo has; tags reach origin on push. +export const makeRepo = (): Repo => { + const root = mkdtempSync(join(tmpdir(), 'agentage-changed-')); + const work = join(root, 'work'); + const origin = join(root, 'origin.git'); + mkdirSync(work); + git(work, 'init', '-q', '-b', 'master'); + git(root, 'init', '-q', '--bare', '-b', 'master', origin); + git(work, 'remote', 'add', 'origin', origin); + const write = (rel: string, text: string) => { + mkdirSync(join(work, rel, '..'), { recursive: true }); + writeFileSync(join(work, rel), text); + }; + write('.gitignore', 'dist/\n'); + const commit = (message: string) => { + git(work, 'add', '-A'); + git(work, 'commit', '-q', '-m', message); + git(work, 'push', '-q', 'origin', 'master', '--tags'); + return git(work, 'rev-parse', 'HEAD'); + }; + const tag = (name: string) => { + git(work, 'tag', name); + git(work, 'push', '-q', 'origin', '--tags'); + }; + return { root, work, origin, git: (...a) => git(work, ...a), write, commit, tag }; +}; + +export const writeExtension = (repo: Repo, rel: string, id: string, spec: Spec = {}) => { + repo.write(join(rel, 'package.json'), `${JSON.stringify(pkgOf(id, spec), null, 2)}\n`); + repo.write(join(rel, 'index.js'), `export const id = '${id}';\n`); +}; + +// A full checkout of an older commit, as a re-run of that commit's workflow run has. +export const checkoutAt = (repo: Repo, sha: string): string => { + const dir = join(repo.root, `at-${sha.slice(0, 7)}`); + execFileSync('git', ['clone', '-q', `file://${repo.origin}`, dir]); + execFileSync('git', ['checkout', '-q', sha], { cwd: dir }); + return dir; +}; + +// The CI checkout: a depth-1 clone with no tags, as actions/checkout makes by default. +export const ciClone = (repo: Repo): string => { + const dir = join(repo.root, `ci-${Math.random().toString(36).slice(2)}`); + execFileSync('git', ['clone', '-q', '--depth', '1', `file://${repo.origin}`, dir]); + return dir; +}; + +export interface World { + records?: Record; + refAt?: string; + refFails?: string; + downloadFails?: string; + npmFails?: string; +} + +const ran = (ok: boolean, text = ''): Ran => + ok ? { ok, out: text, err: '' } : { ok, out: '', err: text }; + +const gh = (w: World, args: string[]): Ran => { + const call = args.join(' '); + if (call.startsWith('release download') && w.downloadFails) return ran(false, w.downloadFails); + if (call.startsWith('release download')) { + const commit = w.records?.[args[2] ?? '']; + return commit ? ran(true, JSON.stringify({ commit })) : ran(false, 'release not found'); + } + if (call.startsWith('release view')) return ran(false, 'release not found'); + if (args[0] === 'api' && args.includes('--jq')) return ran(true, `${w.refAt ?? ''}\n`); + if (args[0] === 'api' && w.refFails) return ran(false, w.refFails); + return ran(true); +}; + +const npm = (w: World, args: string[]): Ran => { + if (args[0] === '--version') return ran(true, '11.7.0\n'); + if (args[0] === 'view') return ran(false, 'E404'); + return w.npmFails ? ran(false, w.npmFails) : ran(true); +}; + +// Real git in the folder it runs in; gh, docker and npm from the world. +export const changedDeps = (w: World, calls: string[], env: NodeJS.ProcessEnv) => { + const exec = + (cwd: string): Exec => + async (cmd, args, extra) => { + if (cmd === 'git') return execIn(cwd)(cmd, args, extra); + calls.push([cmd, ...args].join(' ')); + if (cmd === 'gh') return gh(w, args); + if (cmd === 'npm') return npm(w, args); + return ran(false, 'manifest unknown'); + }; + return { exec, tool: async () => kitStub(calls), env, now: () => NOW } satisfies ReleaseDeps; +}; + +const kitStub = (calls: string[]): KitTool => { + const tool: Partial = { + readManifest, + build: async (opts) => { + const dir = opts?.dir ?? '.'; + rmSync(join(dir, 'dist'), { recursive: true, force: true }); + mkdirSync(join(dir, 'dist'), { recursive: true }); + const name = opts?.container ? 'agentage-container.json' : 'agentage-extension.json'; + writeFileSync(join(dir, 'dist', name), '{}'); + const pkg = await readManifest(dir); + calls.push(`build ${pkg.agentage.id}@${pkg.version}${opts?.container ? ' container' : ''}`); + return { id: pkg.agentage.id, version: pkg.version, commit: '', buildTime: '', images: [] }; + }, + buildLines: () => [], + writeContracts: async (dir) => { + writeFileSync(join(dir, 'openapi.json'), '{"info":{"version":"new"}}\n'); + calls.push('writeContracts'); + return ['openapi.json']; + }, + }; + return tool as KitTool; +}; + +export const REPO = 'agentage/examples'; + +type Run = { dir: string; w?: World; opts?: ExtensionReleaseOptions; env?: NodeJS.ProcessEnv }; + +// One --changed run in `dir`: its printed lines, error, result and every non-git call. +export const release = async ({ dir, w = {}, opts = {}, env }: Run, tool?: Partial) => { + const calls: string[] = []; + const sha = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: dir, encoding: 'utf8' }).trim(); + const deps = changedDeps(w, calls, env ?? { GITHUB_REPOSITORY: REPO, GITHUB_SHA: sha }); + const kit = tool ? { tool: async () => ({ ...(await deps.tool()), ...tool }) as KitTool } : {}; + let result: unknown; + const printed = await output(async () => { + result = await runRelease({ dir, changed: true, ...opts }, { ...deps, ...kit }); + }); + return { ...printed, result, calls, sha }; +};