diff --git a/docs/reference.md b/docs/reference.md index 1e60547..856ae61 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -558,7 +558,21 @@ extension is changed when a file in its folder differs from its last `@*` ta 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 +change to a shared root file (a root lock, a workflow, a config) does not release anything. + +Some files at the folder root never release an extension on their own: `/*.md`, `/docs/**`, +`/.github/**`, `/.repo-doctor.yml`, `/.gitignore`, `/.prettierrc*`, `/.editorconfig` and `/LICENSE`. +Each is anchored at the root: a deeper `.md` or `docs/` (a blog post a site serves) counts. A +`.release-ignore` file in the extension folder adds patterns (gitignore style, one per line, `#` +starts a comment, a pattern with no `/` matches at any depth, the last matching line wins) and a +`!pattern` line re-includes one. What goes into the image always counts, whatever a pattern says: +`package.json`, `package-lock.json`, `src/**` and `Dockerfile*` at the folder root (so a +Dependabot bump of the lock releases). A rename counts as two paths. An extension is changed only +when at least one changed file counts; the `changed:` line names the first 5 of them (`in a.js, +b.js`), and the `unchanged:` line names the ignored files when only those changed (`only ignored +files changed: README.md`). `--dry-run` prints the same lines. + +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 @@ -573,11 +587,26 @@ that UTC day. The version and `repository` (the releasing repo, which the 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: +version with a record is on npm, unless npm was skipped (a private package, or a private repo, see +below). 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 +one that fails or is refused does not stop the others. + +A private repo never puts its source on public npm by accident. Before the tag, a package that is +not `"private": true` reads `gh api repos// --jq .private`: only `false` publishes. +When the repo is private, npm is skipped unless `package.json` opts in with both +`publishConfig.access` set to `"public"` and the top-level `"agentagePublishFromPrivateRepo": true` +(top level: the kit refuses unknown keys under `agentage`); an answer that is not `true` or +`false`, or a call that fails, fails that extension before its tag (`FAIL npm: cannot read whether + is private`, exit 1); the next run retries with the same `N`. A skip prints one `AMBER npm: ...` +line, the images and records still go out, the row reads `released, AMBER: npm skipped`, +`published` is `false` and it alone does not make the exit code non-zero. A re-run of that commit +resumes the version and reads the visibility again. The release without `--changed` (a `v*` tag) +has no such check. + +The run ends with one table (`id`, +`version`, `result`: `released`, `released, AMBER: npm skipped`, `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). diff --git a/src/commands/extension/release-changed-ignore.test.ts b/src/commands/extension/release-changed-ignore.test.ts new file mode 100644 index 0000000..d2385be --- /dev/null +++ b/src/commands/extension/release-changed-ignore.test.ts @@ -0,0 +1,129 @@ +import { describe, expect } from 'vitest'; +import { test } from '../../test/config-dir.js'; +import { ciClone, makeRepo, release, writeExtension, type Repo } from '../../test/release-repo.js'; + +// One extension at `rel`, released from the first commit; `files` then change on a second. +const changedAfterTag = (rel: string, files: string[], ignoreFile?: string) => { + const repo = makeRepo(); + writeExtension(repo, rel, 'probe'); + const at = (f: string) => (rel === '.' ? f : `${rel}/${f}`); + if (ignoreFile !== undefined) repo.write(at('.release-ignore'), ignoreFile); + const first = repo.commit('base'); + repo.tag('probe@2026.1121.1'); + for (const f of files) repo.write(at(f), `changed ${f}\n`); + repo.commit('change'); + return { repo, records: { 'probe@2026.1121.1': first } }; +}; + +const plan = async (repo: Repo, records: Record) => + release({ dir: ciClone(repo), w: { records }, opts: { dryRun: true } }); + +const CHANGED = 'PASS changed: probe (.) differs from probe@2026.1121.1 in'; + +describe('extension release --changed: files that do not release', () => { + test('root layout: only the workflow, docs and markdown changed: nothing is released', async () => { + const files = ['.github/workflows/release.yml', 'README.md', 'docs/guide.txt']; + const { repo, records } = changedAfterTag('.', files); + const run = await release({ dir: ciClone(repo), w: { records } }); + expect(run.error).toBeNull(); + expect(run.lines).toContain( + 'PASS unchanged: probe (.) is the same as probe@2026.1121.1; only ignored files changed: .github/workflows/release.yml, README.md, docs/guide.txt' + ); + expect(run.result).toEqual({ released: [], unchanged: ['probe'] }); + expect(run.calls.some((c) => c.includes('/git/refs'))).toBe(false); + }); + + test('the defaults hold at the folder root only: deeper markdown and docs count', async () => { + const deeper = ['site/public/README.md', 'site/src/content/x.md', 'sub/docs/a.md']; + const { repo, records } = changedAfterTag('.', ['README.md', 'docs/a.md', ...deeper]); + const run = await plan(repo, records); + expect(run.lines).toContain(`${CHANGED} ${deeper.join(', ')}: release probe@2026.1122.1`); + }); + + test('a name with a space and a non-ASCII letter is read exactly', async () => { + const quiet = changedAfterTag('.', ['naïve notes.md']); + expect((await plan(quiet.repo, quiet.records)).lines).toContain( + 'PASS unchanged: probe (.) is the same as probe@2026.1121.1; only ignored files changed: naïve notes.md' + ); + const { repo, records } = changedAfterTag('.', ['site/naïve page.md']); + const run = await plan(repo, records); + expect(run.lines).toContain(`${CHANGED} site/naïve page.md: release probe@2026.1122.1`); + }); + + test('a Dependabot bump of the lock releases: package files always count', async () => { + const { repo, records } = changedAfterTag('.', ['package-lock.json', '.github/dependabot.yml']); + const run = await plan(repo, records); + expect(run.lines).toContain(`${CHANGED} package-lock.json: release probe@2026.1122.1`); + }); + + test('.release-ignore adds patterns, but never over src/** or Dockerfile*', async () => { + const ignore = '# local notes\n\nnotes.txt\nsrc/**\nDockerfile*\n'; + const files = ['notes.txt', 'src/a.ts', 'Dockerfile']; + const { repo, records } = changedAfterTag('.', files, ignore); + const run = await plan(repo, records); + expect(run.lines).toContain(`${CHANGED} Dockerfile, src/a.ts: release probe@2026.1122.1`); + const only = changedAfterTag('.', ['notes.txt'], ignore); + const quiet = await plan(only.repo, only.records); + expect(quiet.lines).toContain( + 'PASS unchanged: probe (.) is the same as probe@2026.1121.1; only ignored files changed: notes.txt' + ); + }); + + test('a !pattern line re-includes a default', async () => { + const { repo, records } = changedAfterTag('.', ['README.md'], '!README.md\n'); + const run = await plan(repo, records); + expect(run.lines).toContain(`${CHANGED} README.md: release probe@2026.1122.1`); + }); + + test('more than five files: the first five, then how many more', async () => { + const files = ['a.js', 'b.js', 'c.js', 'd.js', 'e.js', 'f.js', 'g.js', 'h.md']; + const { repo, records } = changedAfterTag('.', files); + const run = await plan(repo, records); + expect(run.lines).toContain( + `${CHANGED} a.js, b.js, c.js, d.js, e.js and 2 more: release probe@2026.1122.1` + ); + }); + + test('extensions/: patterns read the folder; a markdown-only change stays', async () => { + const repo = makeRepo(); + writeExtension(repo, 'extensions/probe', 'probe'); + writeExtension(repo, 'extensions/fixture', 'fixture'); + const first = repo.commit('two'); + repo.tag('probe@2026.1121.1'); + repo.tag('fixture@2026.1121.1'); + repo.write('extensions/probe/docs/guide.md', 'docs\n'); + repo.write('extensions/probe/index.js', 'code\n'); + repo.write('extensions/fixture/CHANGELOG.md', 'notes\n'); + repo.commit('change'); + const run = await plan(repo, { 'probe@2026.1121.1': first, 'fixture@2026.1121.1': first }); + expect(run.lines).toContain( + 'PASS changed: probe (extensions/probe) differs from probe@2026.1121.1 in index.js: release probe@2026.1122.1' + ); + expect(run.lines).toContain( + 'PASS unchanged: fixture (extensions/fixture) is the same as fixture@2026.1121.1; only ignored files changed: CHANGELOG.md' + ); + }); + + test('a move from src/ to docs/ still releases: renames are two paths', async () => { + const repo = makeRepo(); + writeExtension(repo, '.', 'probe'); + repo.write('src/long-enough.ts', 'export const a = 1;\n'.repeat(20)); + const first = repo.commit('base'); + repo.tag('probe@2026.1121.1'); + repo.write('docs/keep.txt', 'a folder to move into\n'); + repo.commit('docs'); + repo.git('mv', 'src/long-enough.ts', 'docs/long-enough.md'); + repo.commit('move'); + expect(repo.git('diff', '-M', '--name-status', 'HEAD~1', 'HEAD')).toMatch(/^R/); + const run = await plan(repo, { 'probe@2026.1121.1': first }); + expect(run.lines).toContain(`${CHANGED} src/long-enough.ts: release probe@2026.1122.1`); + }); + + test('only ignored files, but the last tag has no record: released with a new N', async () => { + const { repo } = changedAfterTag('.', ['README.md']); + const run = await plan(repo, {}); + expect(run.lines).toContain( + 'PASS changed: probe (.) equals probe@2026.1121.1, which has no record: release probe@2026.1122.1' + ); + }); +}); diff --git a/src/commands/extension/release-changed-npm.test.ts b/src/commands/extension/release-changed-npm.test.ts new file mode 100644 index 0000000..fb6d6b6 --- /dev/null +++ b/src/commands/extension/release-changed-npm.test.ts @@ -0,0 +1,94 @@ +import { describe, expect } from 'vitest'; +import { test } from '../../test/config-dir.js'; +import { + ciClone, + makeRepo, + pkgOf, + release, + REPO, + writeExtension, + type World, +} from '../../test/release-repo.js'; + +const VISIBILITY = `gh api repos/${REPO} --jq .private`; + +// One public-npm extension (no "private": true) at the root, with extra package.json fields. +const publicPackage = (extra: Record = {}) => { + const repo = makeRepo(); + repo.write('package.json', `${JSON.stringify({ ...pkgOf('probe'), ...extra }, null, 2)}\n`); + repo.write('index.js', 'export {};\n'); + repo.commit('one'); + return ciClone(repo); +}; + +const npmCalls = (calls: string[]) => calls.filter((c) => c.startsWith('npm')); + +const skipped = async (w: World, extra?: Record) => { + const run = await release({ dir: publicPackage(extra), w }); + expect(run.error).toBeNull(); + expect(npmCalls(run.calls)).toEqual([]); + expect(run.calls.filter((c) => c.startsWith('gh release create'))).toHaveLength(1); + expect(run.lines.slice(-2)).toEqual([ + 'id version result', + 'probe 2026.1122.1 released, AMBER: npm skipped', + ]); + expect(run.result).toMatchObject({ released: [{ published: false, built: true }] }); + return run.lines.filter((l) => l.startsWith('AMBER')); +}; + +describe('extension release --changed: npm from a private repo', () => { + test('a public repo publishes as before', async () => { + const run = await release({ dir: publicPackage() }); + expect(run.calls).toContain(VISIBILITY); + expect(run.calls).toContain('npm publish --access public --provenance --ignore-scripts'); + }); + + test('a private repo: npm is skipped with one AMBER line; images and record go out', async () => { + expect(await skipped({ visibility: 'true' })).toEqual([ + `AMBER npm: ${REPO} is a private repo: npm skipped; set publishConfig.access to "public" and agentagePublishFromPrivateRepo to true to publish it`, + ]); + }); + + test('half an opt-in is no opt-in', async () => { + const only = { publishConfig: { access: 'public' } }; + expect(await skipped({ visibility: 'true' }, only)).toHaveLength(1); + expect( + await skipped({ visibility: 'true' }, { agentagePublishFromPrivateRepo: true }) + ).toHaveLength(1); + }); + + test('both opt-in fields publish from a private repo', async () => { + const extra = { publishConfig: { access: 'public' }, agentagePublishFromPrivateRepo: true }; + const run = await release({ dir: publicPackage(extra), w: { visibility: 'true' } }); + expect(run.error).toBeNull(); + expect(run.lines).toContain( + `PASS npm: ${REPO} is private, @agentage/extension-probe opts in to public npm` + ); + expect(run.calls).toContain('npm publish --access public --provenance --ignore-scripts'); + }); + + test('a visibility that cannot be read fails that extension before its tag: exit 1', async () => { + const cases: [World['visibility'], string][] = [ + [{ ok: false, out: '', err: 'HTTP 502' }, 'HTTP 502'], + ['', 'no answer'], + ['null', 'null'], + ]; + for (const [visibility, why] of cases) { + const run = await release({ dir: publicPackage(), w: { visibility } }); + expect(run.code).toBe('release_refused'); + expect(run.error).toBe(`probe: FAIL npm: cannot read whether ${REPO} is private (${why})`); + expect(run.calls.filter((c) => c.includes('/git/refs') || c.startsWith('npm'))).toEqual([]); + expect(run.lines.at(-1)).toBe('probe 2026.1122.1 failed'); + } + }); + + test('a "private": true package never reads the visibility', async () => { + const repo = makeRepo(); + writeExtension(repo, '.', 'probe', { private: true }); + repo.commit('one'); + const run = await release({ dir: ciClone(repo), w: { visibility: 'true' } }); + expect(run.error).toBeNull(); + expect(run.calls).not.toContain(VISIBILITY); + expect(run.lines).not.toContain(expect.stringMatching(/^AMBER/)); + }); +}); diff --git a/src/commands/extension/release-changed-safety.test.ts b/src/commands/extension/release-changed-safety.test.ts index a3fc487..b064a45 100644 --- a/src/commands/extension/release-changed-safety.test.ts +++ b/src/commands/extension/release-changed-safety.test.ts @@ -68,7 +68,7 @@ describe('extension release --changed: tags with no record', () => { 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' + 'PASS changed: probe (extensions/probe) differs from probe@2026.1122.2 in index.js: release probe@2026.1122.3' ); }); diff --git a/src/commands/extension/release-changed.test.ts b/src/commands/extension/release-changed.test.ts index 1bb9343..256020c 100644 --- a/src/commands/extension/release-changed.test.ts +++ b/src/commands/extension/release-changed.test.ts @@ -54,7 +54,7 @@ describe('extension release --changed: what it releases', () => { 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 changed: probe (extensions/probe) differs from probe@2026.1121.1 in index.js: 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([ @@ -73,6 +73,7 @@ describe('extension release --changed: what it releases', () => { expect(run.error).toBeNull(); const tag = 'probe@2026.1122.1'; expect(run.calls.filter((c) => !c.includes('2026.1121.1'))).toEqual([ + `gh api repos/${REPO} --jq .private`, '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 -`, @@ -119,7 +120,7 @@ describe('extension release --changed: what it releases', () => { 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' + 'PASS changed: probe (extensions/probe) differs from probe@2026.1121.1 in index.js: release probe@2026.1122.1' ); }); @@ -140,7 +141,7 @@ describe('extension release --changed: what it releases', () => { 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' + 'PASS changed: root (.) differs from root@2026.1121.1 in index.js: 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); diff --git a/src/commands/extension/release-changed.ts b/src/commands/extension/release-changed.ts index 1187c02..a73992c 100644 --- a/src/commands/extension/release-changed.ts +++ b/src/commands/extension/release-changed.ts @@ -4,6 +4,7 @@ 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 { amber, npmRefusal } from './release-npm.js'; import { fetchTags, git, planRelease, type Plan, type Planned } from './release-plan.js'; import { rowsOf, summary, type Row } from './release-summary.js'; import { @@ -81,8 +82,11 @@ const prepare = async (s: Session, p: Planned): Promise => { return pkg; }; -const npmStep = async (s: Session, run: Exec, dir: string, pkg: ExtensionPackage) => { +type Npm = { dir: string; pkg: ExtensionPackage; refusal?: string }; + +const npmStep = async (s: Session, run: Exec, { dir, pkg, refusal }: Npm) => { if (pkg['private'] === true) return step('npm: private package, not published'); + if (refusal) return amber(`npm: ${refusal}`); const push = scoped(s.deps.exec(dir, PUBLISH_SECONDS), s.secrets); await publish(run, push, pkg, s.secrets['npm']?.['NPM_TOKEN']); }; @@ -101,22 +105,24 @@ const imagesStep = async (s: Session, p: Planned, run: Exec, pkg: ExtensionPacka }; // The record is the "released" marker: it goes up only after npm has the version. -const releaseOne = async (s: Session, p: Planned) => { +const releaseOne = async (s: Session, p: Planned, row: Row) => { 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); + const refusal = isPrivate ? undefined : await npmRefusal(run, s.repo, pkg); + if (refusal) row.result = 'released, AMBER: npm skipped'; + if (!isPrivate && !refusal) await npmVersion(run); await createTag(s, p.tag); const records = await imagesStep(s, p, run, pkg); - await npmStep(s, run, dir, pkg); + await npmStep(s, run, { dir, pkg, refusal }); 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, + published: !isPrivate && !refusal, }; }; @@ -126,7 +132,7 @@ const releaseAll = async (s: Session, plan: Plan) => { 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( + await releaseOne(s, p, row).then( (r) => void released.push(r), (err: unknown) => Object.assign(row, { result: 'failed', err }) ); diff --git a/src/commands/extension/release-ignore.test.ts b/src/commands/extension/release-ignore.test.ts new file mode 100644 index 0000000..bf79c74 --- /dev/null +++ b/src/commands/extension/release-ignore.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from 'vitest'; +import { + DEFAULT_IGNORE, + firstFive, + globToRegex, + isIgnored, + parseIgnore, +} from './release-ignore.js'; + +const defaults = parseIgnore(DEFAULT_IGNORE.join('\n')); + +describe('release ignore patterns', () => { + it('a pattern with no slash matches at any depth; one with a slash is anchored', () => { + expect(globToRegex('*.md').test('docs/deep/a.md')).toBe(true); + expect(globToRegex('docs/**').test('docs/a/b.txt')).toBe(true); + expect(globToRegex('docs/**').test('src/docs/a.txt')).toBe(false); + expect(globToRegex('/notes.txt').test('notes.txt')).toBe(true); + expect(globToRegex('a/**/b.txt').test('a/x/y/b.txt')).toBe(true); + expect(globToRegex('file?.txt').test('file1.txt')).toBe(true); + expect(globToRegex('a+b.txt').test('aab.txt')).toBe(false); + }); + + it('the defaults ignore root docs, markdown, CI and repo config, nothing deeper', () => { + for (const path of [ + 'docs/guide.txt', + 'README.md', + '.github/workflows/release.yml', + '.repo-doctor.yml', + '.gitignore', + '.prettierrc.json', + '.editorconfig', + 'LICENSE', + ]) + expect(isIgnored(defaults, path), path).toBe(true); + const deeper = ['site/src/content/x.md', 'site/public/README.md', 'sub/docs/a.md', 'a/LICENSE']; + for (const path of ['index.js', 'dist-config.yml', 'scripts/x.sh', ...deeper]) + expect(isIgnored(defaults, path), path).toBe(false); + }); + + it('a folder name with no slash ignores what is under it; ! re-includes; the last rule wins', () => { + const rules = parseIgnore(['# a comment', '', 'fixtures', '!fixtures/keep.json'].join('\n')); + expect(isIgnored(rules, 'fixtures/a.json')).toBe(true); + expect(isIgnored(rules, 'fixtures/keep.json')).toBe(false); + expect(isIgnored(parseIgnore('*.md\n!README.md'), 'README.md')).toBe(false); + }); + + it('what goes into the image always counts, whatever a pattern says', () => { + const all = parseIgnore('*\n**\nsrc/**\npackage*.json\nDockerfile*'); + for (const path of ['package.json', 'package-lock.json', 'src/a.ts', 'src/docs/a.md']) + expect(isIgnored(all, path), path).toBe(false); + expect(isIgnored(all, 'Dockerfile.container')).toBe(false); + expect(isIgnored(all, 'docs/package.json')).toBe(true); + }); + + it('names the first five files, then how many more', () => { + expect(firstFive(['a', 'b'])).toBe('a, b'); + expect(firstFive(['a', 'b', 'c', 'd', 'e', 'f', 'g'])).toBe('a, b, c, d, e and 2 more'); + }); +}); diff --git a/src/commands/extension/release-ignore.ts b/src/commands/extension/release-ignore.ts new file mode 100644 index 0000000..b4ef10a --- /dev/null +++ b/src/commands/extension/release-ignore.ts @@ -0,0 +1,89 @@ +import { readFile } from 'node:fs/promises'; +import { join } from 'node:path'; + +type Rule = { re: RegExp; keep: boolean }; + +// Anchored at the folder root: a deeper .md or docs/ may be served by the site or the image. +export const DEFAULT_IGNORE = [ + '/*.md', + '/docs/**', + '/.github/**', + '/.repo-doctor.yml', + '/.gitignore', + '/.prettierrc*', + '/.editorconfig', + '/LICENSE', +]; + +// What goes into the image always counts, whatever an ignore pattern says. +export const ALWAYS_COUNTS = ['/package.json', '/package-lock.json', '/src/**', '/Dockerfile*']; + +export const IGNORE_FILE = '.release-ignore'; + +const TOKENS: Record = { + '**/': '(?:.*/)?', + '/**': '(?:/.*)?', + '**': '.*', + '*': '[^/]*', + '?': '[^/]', +}; + +// Gitignore-style: a pattern with a slash is anchored to the folder, one without matches any depth. +export const globToRegex = (glob: string): RegExp => { + const bare = glob.replace(/\/$/, ''); + const anchored = bare.includes('/'); + const body = bare + .replace(/^\//, '') + .replace(/\*\*\/|\/\*\*|\*\*|\*|\?|[.+^${}()|[\]\\]/g, (t) => TOKENS[t] ?? `\\${t}`); + return new RegExp(`^${anchored ? '' : '(?:.*/)?'}${body}$`); +}; + +const ruleOf = (line: string): Rule => { + const keep = line.startsWith('!'); + return { re: globToRegex(keep ? line.slice(1) : line), keep }; +}; + +export const parseIgnore = (text: string): Rule[] => + text + .split('\n') + .map((l) => l.trim()) + .filter((l) => l !== '' && !l.startsWith('#')) + .map(ruleOf); + +// The path and each folder above it: `docs` also matches `docs/a.md`. +const candidates = (path: string): string[] => + path.split('/').map((_, i, parts) => parts.slice(0, i + 1).join('/')); + +const hits = (re: RegExp, path: string): boolean => candidates(path).some((p) => re.test(p)); + +// The last matching rule wins, as in .gitignore. +export const isIgnored = (rules: Rule[], path: string): boolean => { + if (ALWAYS_COUNTS.some((g) => hits(globToRegex(g), path))) return false; + let ignored = false; + for (const rule of rules) if (hits(rule.re, path)) ignored = !rule.keep; + return ignored; +}; + +const rulesAt = async (dir: string): Promise => { + const text = await readFile(join(dir, IGNORE_FILE), 'utf8').catch(() => ''); + return parseIgnore([...DEFAULT_IGNORE, text].join('\n')); +}; + +export type Sorted = { counted: string[]; ignored: string[] }; + +// `diff` names files from the repo root; the patterns read them from the extension folder. +export const sortChanged = async (root: string, rel: string, diff: string): Promise => { + const rules = await rulesAt(join(root, rel)); + const prefix = rel === '.' ? '' : `${rel}/`; + const files = diff.split('\0').filter(Boolean); + const local = files.map((f) => f.slice(prefix.length)); + return { + counted: local.filter((f) => !isIgnored(rules, f)), + ignored: local.filter((f) => isIgnored(rules, f)), + }; +}; + +export const firstFive = (files: string[]): string => { + const more = files.length > 5 ? ` and ${files.length - 5} more` : ''; + return `${files.slice(0, 5).join(', ')}${more}`; +}; diff --git a/src/commands/extension/release-npm.ts b/src/commands/extension/release-npm.ts new file mode 100644 index 0000000..d469f89 --- /dev/null +++ b/src/commands/extension/release-npm.ts @@ -0,0 +1,31 @@ +import type { ExtensionPackage } from '@agentage/extension/tool'; +import type { Exec } from './release-guard.js'; +import { fail, step } from './release-steps.js'; + +// The kit refuses unknown keys under `agentage`: the opt-in is a top-level package.json key. +export const OPT_IN = 'agentagePublishFromPrivateRepo'; + +export const amber = (line: string): void => console.log(`AMBER ${line}`); + +const optedIn = (pkg: ExtensionPackage): boolean => { + const config = pkg['publishConfig'] as { access?: unknown } | undefined; + return config?.access === 'public' && pkg[OPT_IN] === true; +}; + +const howTo = `set publishConfig.access to "public" and ${OPT_IN} to true to publish it`; + +// Only a repo GitHub names public, or an opt-in, goes to npm; no clear answer stops the release. +export const npmRefusal = async ( + run: Exec, + repo: string, + pkg: ExtensionPackage +): Promise => { + const read = await run('gh', ['api', `repos/${repo}`, '--jq', '.private']); + const answer = read.out.trim(); + if (read.ok && answer === 'false') return undefined; + if (!read.ok || answer !== 'true') + fail(`npm: cannot read whether ${repo} is private (${read.err || answer || 'no answer'})`); + if (!optedIn(pkg)) return `${repo} is a private repo: npm skipped; ${howTo}`; + step(`npm: ${repo} is private, ${pkg.name} opts in to public npm`); + return undefined; +}; diff --git a/src/commands/extension/release-plan.ts b/src/commands/extension/release-plan.ts index 9645caf..edd07a1 100644 --- a/src/commands/extension/release-plan.ts +++ b/src/commands/extension/release-plan.ts @@ -1,5 +1,6 @@ import { dateVersion, lastTag, newestTags, tagOf } from './release-date.js'; import { extensionFolders, type Folder } from './release-folders.js'; +import { firstFive, sortChanged } from './release-ignore.js'; import { RECORD, type Exec } from './release-guard.js'; import { fail, step } from './release-steps.js'; @@ -50,15 +51,24 @@ const unrecorded = async (c: PlanInput, f: Folder, tags: string[]): Promise { - if (!last) return `has no ${f.id}@* tag yet`; +const whyOf = async (c: PlanInput, f: Folder, tags: string[], last?: string): Promise => { + if (!last) return { why: `has no ${f.id}@* tag yet`, ignored: [] }; 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}`; + // No renames: a move from src/ to docs/ names the src/ path; -z keeps odd names exact. + const args = ['diff', '--name-only', '-z', '--no-renames', last, c.sha, '--', f.rel]; + const { counted, ignored } = await sortChanged(c.root, f.rel, await git(c.run, args, 'changed')); + if (counted.length > 0) return { why: `differs from ${last} in ${firstFive(counted)}`, ignored }; // 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; + if (missing[0] === last) return { why: `equals ${last}, which has no record`, ignored }; + return { ignored }; +}; + +const sameAs = (f: Folder, last: string | undefined, ignored: string[]): void => { + const only = ignored.length > 0 ? `; only ignored files changed: ${firstFive(ignored)}` : ''; + step(`unchanged: ${f.id} (${f.rel}) is the same as ${String(last)}${only}`); }; // A re-run of an old commit must not give older code a higher version than its last tag. @@ -82,9 +92,9 @@ const planOne = async (c: PlanInput, f: Folder): Promise => 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); + const { why, ignored } = 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)}`); + sameAs(f, last, ignored); return undefined; }; diff --git a/src/commands/extension/release.ts b/src/commands/extension/release.ts index 572eeca..7493cca 100644 --- a/src/commands/extension/release.ts +++ b/src/commands/extension/release.ts @@ -111,7 +111,7 @@ export const addRelease = ( ) .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' + 'each extension (root or extensions/*) whose folder changed since its last @* tag; root docs/**, root *.md, .github/** and repo config (plus .release-ignore patterns) never trigger a release, package.json, the lock, src/** and Dockerfile* always do; a private repo skips npm unless the package opts in' ) .option('--dry-run', 'with --changed: print what it would release, change nothing') ).action(release); diff --git a/src/test/release-repo.ts b/src/test/release-repo.ts index ef3689a..698c7c1 100644 --- a/src/test/release-repo.ts +++ b/src/test/release-repo.ts @@ -100,11 +100,16 @@ export interface World { refFails?: string; downloadFails?: string; npmFails?: string; + /** What `gh api repos/ --jq .private` answers (default: false); a Ran to fail it. */ + visibility?: string | Ran; } const ran = (ok: boolean, text = ''): Ran => ok ? { ok, out: text, err: '' } : { ok, out: '', err: text }; +const visibilityOf = ({ visibility = 'false' }: World): Ran => + typeof visibility === 'string' ? ran(true, `${visibility}\n`) : visibility; + const gh = (w: World, args: string[]): Ran => { const call = args.join(' '); if (call.startsWith('release download') && w.downloadFails) return ran(false, w.downloadFails); @@ -113,6 +118,7 @@ const gh = (w: World, args: string[]): Ran => { return commit ? ran(true, JSON.stringify({ commit })) : ran(false, 'release not found'); } if (call.startsWith('release view')) return ran(false, 'release not found'); + if (call === `api repos/${REPO} --jq .private`) return visibilityOf(w); 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);