Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
ci(release): share manual and opt-in daily candidate preparation
Xubin Ren65b6fd03ce60
diff --git a/.github/workflows/release-candidate.yml b/.github/workflows/release-candidate.ymlindex c1fae169f..e1bd4b148 100644--- a/.github/workflows/release-candidate.yml+++ b/.github/workflows/release-candidate.yml@@ -1,7 +1,14 @@name: Verify Release Candidate+run-name: >-+ ${{ github.event_name == 'schedule' && vars.NANOBOT_DAILY_CANDIDATES_ENABLED != 'true' &&+ 'Disabled daily candidate' || format('Candidate {0} {1} from {2}',+ inputs.channel || 'preview', inputs.next_stable || vars.NANOBOT_PREVIEW_BASE, github.sha) }}-# Preparation only: no cron, tags, GitHub Releases, PyPI or channel-feed writes.+# Preparation only: no tags, GitHub Releases, PyPI or channel-feed writes.+# Daily preparation is opt-in and remains disabled until maintainers enable the variable.on:+ schedule:+ - cron: '17 0 * * *'workflow_dispatch:inputs:next_stable:@@ -26,11 +33,67 @@ permissions:contents: readconcurrency:- group: release-candidate+ # A daily tick must not replace a maintainer's pending manual run.+ group: release-candidate-${{ github.event_name }}cancel-in-progress: falsejobs:+ plan:+ if: >-+ github.event_name == 'workflow_dispatch' ||+ (github.repository == 'HKUDS/nanobot' && github.ref == 'refs/heads/main' &&+ vars.NANOBOT_DAILY_CANDIDATES_ENABLED == 'true')+ runs-on: ubuntu-latest+ timeout-minutes: 5+ permissions:+ contents: read+ actions: read+ outputs:+ prepare: ${{ steps.plan.outputs.prepare }}+ base: ${{ steps.plan.outputs.base }}+ channel: ${{ steps.plan.outputs.channel }}+ notes_artifact_id: ${{ steps.notes.outputs.artifact-id }}+ steps:+ - uses: actions/checkout@v4+ with:+ fetch-depth: 0+ persist-credentials: false+ - uses: actions/setup-python@v5+ with:+ python-version: '3.11'+ - name: Install planning tools+ run: python -m pip install 'pydantic>=2,<3' packaging+ - name: Select an exact candidate and generate draft notes+ id: plan+ env:+ GH_TOKEN: ${{ github.token }}+ SOURCE_COMMIT: ${{ github.sha }}+ NEXT_STABLE: ${{ inputs.next_stable || vars.NANOBOT_PREVIEW_BASE }}+ CANDIDATE_CHANNEL: ${{ inputs.channel || 'preview' }}+ PREVIEW_SEQUENCE: ${{ github.run_number }}+ run: |+ args=()+ if [ "$GITHUB_EVENT_NAME" = schedule ]; then args+=(--scheduled); fi+ python -m scripts.release_plan --source-commit "$SOURCE_COMMIT" \+ --base "$NEXT_STABLE" --channel "$CANDIDATE_CHANNEL" \+ --sequence "$PREVIEW_SEQUENCE" --output "$RUNNER_TEMP/release-plan" \+ --github-output "$GITHUB_OUTPUT" "${args[@]}"+ - name: Retain draft notes for the same candidate+ id: notes+ if: steps.plan.outputs.prepare == 'true'+ uses: actions/upload-artifact@v4+ with:+ name: candidate-notes-${{ github.run_number }}-${{ github.run_attempt }}+ path: ${{ runner.temp }}/release-plan+ if-no-files-found: error+ retention-days: 3+ - name: Report unchanged source+ if: steps.plan.outputs.prepare == 'false'+ run: echo 'This source and Preview base already passed candidate acceptance. No new build or publication.' >> "$GITHUB_STEP_SUMMARY"+candidate:+ needs: plan+ if: needs.plan.outputs.prepare == 'true'runs-on: ubuntu-latesttimeout-minutes: 45outputs:@@ -40,9 +103,9 @@ jobs:prepared_artifact_id: ${{ steps.prepared.outputs.artifact-id }}env:SOURCE_COMMIT: ${{ github.sha }}- NEXT_STABLE: ${{ inputs.next_stable }}+ NEXT_STABLE: ${{ needs.plan.outputs.base }}PREVIEW_SEQUENCE: ${{ github.run_number }}- CANDIDATE_CHANNEL: ${{ inputs.channel }}+ CANDIDATE_CHANNEL: ${{ needs.plan.outputs.channel }}steps:- name: Set candidate directory@@ -63,6 +126,13 @@ jobs:with:bun-version: 1.3.13+ - name: Restore the planned notes by producer ID+ uses: actions/download-artifact@v4+ with:+ artifact-ids: ${{ needs.plan.outputs.notes_artifact_id }}+ merge-multiple: true+ path: ${{ runner.temp }}/release-plan+- name: Install isolated build and verification toolsrun: |uv venv "$RUNNER_TEMP/release-tools"@@ -191,11 +261,12 @@ jobs:${{ runner.temp }}/candidate.json${{ runner.temp }}/release-artifacts/release-manifest.json${{ runner.temp }}/install-candidate.md+ ${{ runner.temp }}/release-plan/release-notes.mdif-no-files-found: errorretention-days: 3# Explicit, short-lived release handoff only. This is the documented- # exception to report-only preflight; never enable it on a daily schedule.+ # exception to report-only preflight. Schedules do not retain installable files.- name: Preserve the verified bytes and independent candidate sourceif: ${{ inputs.retain_installable }}working-directory: ${{ env.CANDIDATE_DIR }}@@ -203,6 +274,7 @@ jobs:python -m scripts.release_candidate retain --source-commit "$SOURCE_COMMIT" \--artifacts "$RUNNER_TEMP/release-artifacts" \--output "$RUNNER_TEMP/retained-candidate"+ cp "$RUNNER_TEMP/release-plan/release-notes.md" "$RUNNER_TEMP/retained-candidate/release-notes.md"- name: Transfer prepared candidate pending native acceptanceid: prepared@@ -233,8 +305,8 @@ jobs:verified:name: Candidate required- needs: [candidate, native]- if: always()+ needs: [plan, candidate, native]+ if: always() && needs.plan.result == 'success' && needs.plan.outputs.prepare == 'true'runs-on: ubuntu-latesttimeout-minutes: 10steps:diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 5e2bbb55f..2153d99a2 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -142,6 +142,8 @@ If your change genuinely needs to step outside this, please call it out explicitUse the [release checklist](./docs/releasing.md) for candidate preparation, package checks, documentation coordination, and the final publication handoff.+Stable feature releases and Stable patches are manual and share the same package workflow. Patches use generated change notes and update only affected documentation; they do not require a full wiki or promotional refresh. The Preview/dev line is intended for daily workflow delivery. The current first step supports opt-in daily candidate preparation only; publication remains separate and daily preparation is disabled by default. See the checklist for its activation boundary and remaining publication work.+A stable install must never combine Python from one version with a TUI from another. Publish in this order:1. Before pushing a tag, set the package version, verify the exact candidate, build the source distribution, all five platform wheels and TUI archives, and review licenses, source offer, and relinking materials. Obtain the maintainer's source-offer commitment before publication.diff --git a/docs/releasing.md b/docs/releasing.mdindex 9983df396..a213fa47c 100644--- a/docs/releasing.md+++ b/docs/releasing.md@@ -6,13 +6,27 @@ Use this checklist with the [Release Packaging Contract](../CONTRIBUTING.md#releStable is the default feed; Preview is opt-in. Both use one update flow and require confirmation before installation. Neither a faster cadence nor a subscription permits stopping tasks or restarting a gateway automatically. See [Updating nanobot](./updating.md) for user instructions.-| Release | When to prepare it | Public destination | User experience |+| Release | Trigger | Public destination | Documentation || --- | --- | --- | --- |-| Stable feature release | At the planned feature milestone | Final GitHub Release and PyPI; also index its manifest for Preview subscribers | Normal update notice |-| Stable patch | When a reviewed fix or small, compatible improvement is ready; do not wait for the next monthly milestone | Same stable destinations and checks | Normal update notice, no Preview opt-in required |-| Preview | On maintainer request, from reviewed changes with passing checks; potentially daily | GitHub prerelease and protected `release-index` catalogue; not PyPI | Same update notice for subscribers, with risk shown before installation |+| Stable feature release | Manual, when needed | Final GitHub Release and PyPI; also index its manifest for Preview subscribers | Full version documentation and any planned announcement |+| Stable patch | Manual, when a reviewed fix is ready; do not wait for a feature milestone | Same stable destinations and checks | Generated change notes and necessary upgrade instructions; update only affected documentation |+| Preview / dev | Daily workflow, after maintainers enable it | GitHub prerelease and protected `release-index` catalogue; not PyPI | Generated change notes; no new documentation edition for each build |-Packaging is maintainer-triggered, not scheduled or push-triggered. Record the requested channel, exact source and candidate identity; preparation does not authorize publication. Unchanged source, failed checks, missing assets, incomplete acceptance or absent approval leaves the last verified release in place. There is no daily-release promise. Acceptance must cover the supported stable baseline and an earlier Preview, including skipped previews, not just the previous build.+These are three publication lines, not three build systems. Feature and patch releases both use `channel=stable`; dev uses the existing `preview` channel. A patch does not require a Preview first or a complete wiki and promotional refresh. Preserve necessary tests and release checks, and reuse unaffected evidence under the [verification guidance](../.agent/workflow.md).++Implementation status: **Verify Release Candidate** supports manual preparation and opt-in daily Preview preparation. It generates draft notes and reuses the same five-platform build and acceptance jobs. It does not publish. Automatic prerelease upload, signing handoff and catalogue advancement are not connected yet; PyPI publication remains manual. Daily preparation is disabled by default. Do not describe this first step as an available daily public release channel.++Record the requested channel, exact source and candidate identity. Unchanged source, failed checks, missing assets, incomplete acceptance or absent approval leaves the last verified release in place. Scheduled execution can be delayed; there is no promise of a new release every day. Acceptance must cover the supported stable baseline and an earlier Preview, including skipped previews, not just the previous build.++### Shared preparation entry++Run **Verify Release Candidate** at the chosen source ref with the existing `next_stable`, `channel` and optional `retain_installable` inputs. Both Stable release sizes use the same entry. The workflow generates `release-notes.md` from commit subjects and includes it in candidate reports and an explicitly retained installable handoff. Review necessary upgrade instructions and security wording before publication. These notes are local artifacts, not a GitHub Release, including a draft Release.++Stable notes start at the preceding final release on the selected source line, ignoring Preview tags. Preview notes can start at the preceding Preview's source. Neither uses an unrelated branch's newest tag. The planned source is the event SHA throughout the run; preparation does not follow a moving branch.++For daily preparation, maintainers can later set `NANOBOT_PREVIEW_BASE` to the next unreleased final version and explicitly enable `NANOBOT_DAILY_CANDIDATES_ENABLED=true`. The schedule is currently 00:17 UTC. Only the official repository's `main` can use it. It requires successful latest push CI for that exact SHA and skips a source/base already accepted by this workflow. Failed candidates can run again; manual dispatch remains available to retain a new handoff. Both paths share the existing workflow run number for `.devN`. Update the base after its final release; an already tagged base is refused.++Daily runs retain small reports only, not the optional installable handoff. They still use the existing five native runners and temporary wheel transfers, so review the runner and storage cost before enabling the variable. This is a preparation switch, not permission to sign or publish. No repository variable or protection setting is changed by adding this workflow code.### Stable patch procedure@@ -21,10 +35,10 @@ Packaging is maintainer-triggered, not scheduled or push-triggered. Record the r3. Publish approved immutable files in order: GitHub, PyPI, public-download checks, then the catalogue's `stable` pointer. Preserve `preview` and withdrawal history. A stable patch older than an installed Preview must not be offered as a downgrade.4. Publish concise fix notes and required operator actions. Users without this updater need their original installation method for the first upgrade; external package/deployment owners retain their route.-### Maintainer-triggered Preview procedure+### Preview procedure1. Select an exact reviewed `main` commit with passing required CI; skip it if its source SHA matches the last accepted candidate. Record the next unreleased stable base and an unused increasing Preview sequence.-2. Run **Verify Release Candidate** for that ref and base. It prepares a version-only candidate, builds the WebUI and five native TUI bundles once, and runs macOS arm64/x64, Linux arm64/x64 and Windows x64 clean-install and packaged update/recovery acceptance against the exact manifest-bound wheels without publication. Ordinary PR CI keeps its Linux x64/Windows x64 matrix; the manually requested candidate pays for all five native runners. Require the **Candidate required** check to pass; build-only reports are insufficient. Users receive built packages, not a checkout requiring Bun.+2. Use **Verify Release Candidate** for that ref and base, manually or through enabled daily preparation. It prepares a version-only candidate, builds the WebUI and five native TUI bundles once, and runs macOS arm64/x64, Linux arm64/x64 and Windows x64 clean-install and packaged update/recovery acceptance against the exact manifest-bound wheels without publication. Ordinary PR CI keeps its Linux x64/Windows x64 matrix; candidate preparation uses all five native runners. Require the **Candidate required** check to pass; build-only reports are insufficient. Users receive built packages, not a checkout requiring Bun.3. Select `retain_installable` and preserve the accepted `installable-candidate` handoff before expiry. Temporary `candidate-native` inputs and `prepared-candidate` artifacts are not accepted handoffs. Complete real historical-baseline and interactive acceptance against those exact bytes; the automated fault-injection fixtures do not establish compatibility with a previously published version or interactive desktop behavior. Keep candidate SHA, manifest hash, coverage, known issues and source-offer approval together; CI reports alone are neither installable artifacts nor publication consent.4. With separate approval, publish immutable `v<version>` at the **candidate** commit and a GitHub prerelease, never the latest stable release. Upload the complete verified set, manifest and notes; make the pinned installer source publicly reachable.5. Verify all public sizes/hashes and clean public install/update acceptance before advancing `preview` with a new catalogue generation. Validate against the latest catalogue, preserve `stable` and withdrawals, and serialize stable, Preview and withdrawal writes. A stale publisher must reread and revalidate.@@ -36,17 +50,17 @@ Use Python version ordering: `0.3.6.dev42 < 0.3.6.dev43 < 0.3.6 < 0.3.7.dev1` (iBefore offering public Preview, obtain approval for index ownership/protection, publication credentials, source retention and exact packaged/public-download acceptance. Candidate preparation does not activate a public channel, schedule, protected publisher or PyPI upload. Preserve approved release bytes and source outside expiring CI storage for their required lifetime.-Automate steps within an explicitly requested run, not the decision to build or publish. Keep builds read-only, publication permissions in a protected stage, the last accepted source/version recorded and one serialized catalogue writer. Announce Preview availability only after verifying its public feed. Any discovery hint must be dismissible; do not show an update badge for an unavailable channel or enroll users merely because they check.+Stable releases remain manual. Daily Preview preparation requires the explicit opt-in above; automatic publication needs a separate reviewed implementation and activation. Keep builds read-only and publication permissions in the protected stage. Keep one serialized catalogue writer. Announce Preview availability only after verifying its public feed. Any discovery hint must be dismissible; do not show an update badge for an unavailable channel or enroll users merely because they check.## Prepare a candidate1. Choose the previous release and exact candidate commit. Use a clean worktree without local configuration, sessions, credentials or unrelated changes.2. Update `project.version` in `pyproject.toml` and the final source-only fallback in `nanobot/__init__.py`. Private WebUI/TUI versions are not the Python release version.-3. Review the final tag range; prepare highlights, upgrade/rollback guidance, acknowledgements and full changelog. Verify counts: commits are not merged PRs. Coordinate security disclosures separately.+3. Review the generated change notes and add required upgrade/rollback instructions. Feature releases can add highlights and acknowledgements; ordinary patches do not need a full announcement. Verify counts: commits are not merged PRs. Coordinate security disclosures separately.4. Run Python, WebUI and TUI CI checks against the final commit, not an earlier PR head. Review installation, configuration, session and API changes.5. Run `uv build --out-dir <artifact-directory>` in a clean output directory without `NANOBOT_SKIP_WEBUI_BUILD`. The build hook bundles WebUI in sdist and wheel; the wheel is built from the sdist.6. Run `twine check` on intermediates, inspect contents and record SHA-256 hashes. Test installation in an isolated environment outside the checkout and upgrade from previous stable with disposable configuration/sessions, never a maintainer's live workspace.-7. Prepare the documentation PR in `Re-bin/nanobot-web` under its `MAINTAINING.md`: review English and all nine translations, preserve Nightly and previous releases, update latest-version redirects and run the full site quality gate. Pin source links to the candidate and confirm they match the eventual tag. Do not advertise an unpublished version.+7. For feature releases, prepare the version documentation in `Re-bin/nanobot-web` under its `MAINTAINING.md`. For patches, update only affected instructions and translations; do not require a new complete manual or promotional page when the existing documentation still applies. Preserve existing URLs and previous versions, and verify affected site routes. Pin source references where applicable and never advertise an unpublished package. Preview notes cover development changes without creating a documentation edition each day.8. Review pinned Bun/OpenTUI licenses, corresponding source and relinking instructions. Check upstream revision availability and runtime/lockfile/notice agreement. Obtain the maintainer's commitment to the [source offer](../tui/SOURCE_OFFER.md) for its full stated period, at least three years after release; tests cannot grant it.9. Build all five native targets with publication scripts, ad-hoc signing macOS before packaging.- Verify archive checksums, manifests, architecture, licenses/notices and embedded source, including checkout-matching bytes for `tui/scripts/targets.ts` and `tui/scripts/target-bindings.ts`. Run supported native smoke tests, record coverage and exact-head CI evidence, and label cross-compiled-only targets.@@ -138,7 +152,7 @@ The proof authenticates release approval, not reproducible builds or harmless co5. Make the release and complete artifact set public. Verify every file against the accepted manifest, including native fallback/source-install archives. Platform-wheel TUI startup must not need downloads.6. Upload only the checked `nanobot_ai-X.Y.Z.tar.gz` and five final wheels to PyPI, not the universal intermediate or stale shared `dist/` files. There is no automatic PyPI publication workflow.7. Verify clean PyPI installation, bundled WebUI and download-free TUI startup. After all public GitHub/PyPI files pass, advance `stable`, preserving Preview and withdrawals; check discovery for both subscriptions. Only then merge the wiki PR: its `main` deploys automatically. Confirm all localized `/docs/latest/` routes select the new version and old-version links still work.-8. Announce the release, add its dated [Release Archive](./release-archive.md) entry, complete coordinated advisories/reporter notifications, and record links/status in the release tracking issue.+8. Add the dated [Release Archive](./release-archive.md) entry and record publication links/status. Feature releases can include a separate announcement; ordinary patches can use the generated notes with necessary additions. Complete any coordinated advisory and reporter notifications separately.## If a gate fails@@ -212,7 +226,7 @@ Discovery grants no installation authority. Only the official managed venv and s## Non-publishing preview preflight-**Verify Release Candidate** is manual, read-only preparation: no tags/releases, PyPI or catalogue writes. It builds/checks five platform wheels, sdist and licensed fallback archives. Cross-compilation is neither native execution nor release approval.+**Verify Release Candidate** is read-only preparation, either manually requested or explicitly enabled for daily Preview: no tags/releases, PyPI or catalogue writes. It builds/checks five platform wheels, sdist and licensed fallback archives. Cross-compilation is neither native execution nor release approval.Default retention is small identity/manifest/probe reports and installation guide for **three days**, without installable binaries. `retain_installable` preserves those exact checked artifacts plus a self-contained shallow Git repository for **one day** (about 400 MB). Keep this storage exception off for routine preflight or schedules; assess storage and call it out explicitly in workflow-change PRs before merge. Preserve approved handoffs before expiry; rebuilding expired files cannot reuse their verification. The source contains only candidate/source-parent history, not configuration or untracked files. `handoff.json` is written only after copied artifacts verify; interruption is not an accepted handoff.diff --git a/scripts/release_plan.py b/scripts/release_plan.pynew file mode 100644index 000000000..b4c63f988--- /dev/null+++ b/scripts/release_plan.py@@ -0,0 +1,143 @@+"""Plan candidate preparation and write draft notes; never publish a release."""++from __future__ import annotations++import argparse+import json+import re+import subprocess+from pathlib import Path++from packaging.version import Version+from pydantic import BaseModel++from nanobot.releases import release_version++ROOT = Path(__file__).resolve().parents[1]+++def git(root: Path, *args: str) -> str:+ return subprocess.run(["git", *args], cwd=root, check=True, capture_output=True,+ text=True, encoding="utf-8", timeout=30).stdout.strip()+++class WorkflowRun(BaseModel):+ head_sha: str+ display_title: str+ event: str+ run_number: int+ run_attempt: int+ status: str+ conclusion: str | None+++class WorkflowRuns(BaseModel):+ workflow_runs: list[WorkflowRun]+++def workflow_runs(workflow: str, source: str, query: str) -> list[WorkflowRun]:+ result = subprocess.run(+ ["gh", "api", f"repos/HKUDS/nanobot/actions/workflows/{workflow}/runs"+ f"?head_sha={source}&per_page=100&{query}"],+ check=True, capture_output=True, text=True, encoding="utf-8", timeout=60,+ )+ return WorkflowRuns.model_validate_json(result.stdout).workflow_runs+++def daily_needed(source: str, base: str, ci: list[WorkflowRun], candidates: list[WorkflowRun]) -> bool:+ """Only prepare the scheduled main SHA after its latest push CI succeeds."""+ matching = [run for run in ci if run.head_sha == source and run.event == "push"]+ latest = max(matching, key=lambda run: (run.run_number, run.run_attempt), default=None)+ if latest is None or latest.status != "completed" or latest.conclusion != "success":+ raise ValueError("The scheduled source has no successful latest push CI; wait for CI or repair it")+ title = f"Candidate preview {base} from {source}"+ return not any(+ run.head_sha == source and run.display_title == title+ and run.event in {"schedule", "workflow_dispatch"}+ and run.status == "completed" and run.conclusion == "success"+ for run in candidates+ )+++def previous_tag(root: Path, source: str, version: str) -> str:+ """Choose the preceding release on this source line, not the newest tag by date."""+ target = Version(version)+ candidates: list[tuple[Version, str]] = []+ for tag in git(root, "tag", "--list", "v*").splitlines():+ try:+ parsed = Version(release_version(tag[1:]))+ except ValueError:+ continue+ if parsed >= target or (not target.is_prerelease and parsed.is_prerelease):+ continue+ candidates.append((parsed, tag))+ for parsed, tag in sorted(candidates, reverse=True):+ # Preview preparation adds a version-only child that is not merged into main.+ ref = f"{tag}^" if parsed.is_devrelease else tag+ result = subprocess.run(["git", "merge-base", "--is-ancestor", ref, source], cwd=root,+ capture_output=True, check=False, timeout=30)+ if result.returncode == 0:+ return tag+ if result.returncode != 1:+ raise ValueError(f"Cannot resolve release history for {tag}")+ raise ValueError("No preceding release on this source line; review the release range manually")+++def render_notes(root: Path, *, source: str, version: str) -> str:+ previous = previous_tag(root, source, version)+ changes = git(root, "log", "--format=- %s (%h)", f"{previous}..{source}")+ return (+ f"# {version}\n\nChanges since {previous}:\n\n{changes or 'No code changes.'}\n\n"+ f"Source: `{source}`\n\n"+ "Draft generated from commit subjects. Review required upgrade instructions and "+ "coordinated disclosure wording before publication.\n"+ )+++def plan(root: Path, *, source: str, base: str, channel: str, sequence: int, scheduled: bool) -> dict[str, str]:+ if not re.fullmatch(r"[0-9a-f]{40}", source):+ raise ValueError("Use an exact full source commit SHA")+ # Both channels require a final base. Keep the candidate workflow's existing sequence.+ parsed = Version(release_version(base))+ if parsed.is_prerelease or parsed.is_postrelease or sequence < 1:+ raise ValueError("Use a final base and a positive candidate sequence")+ version = f"{base}.dev{sequence}" if channel == "preview" else base+ if channel not in {"stable", "preview"} or (scheduled and channel != "preview"):+ raise ValueError("Scheduled preparation is Preview only")+ if git(root, "tag", "--list", f"v{version}") or git(root, "tag", "--list", f"v{base}"):+ raise ValueError("Version or stable base is already tagged; choose an unused version")+ prepare = True+ if scheduled:+ prepare = daily_needed(+ source, base,+ workflow_runs("ci.yml", source, "event=push"),+ workflow_runs("release-candidate.yml", source, "status=success&branch=main"),+ )+ return {"prepare": str(prepare).lower(), "source_commit": source, "base": base,+ "channel": channel, "version": version}+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--source-commit", required=True)+ parser.add_argument("--base", required=True)+ parser.add_argument("--channel", required=True, choices=("stable", "preview"))+ parser.add_argument("--sequence", required=True, type=int)+ parser.add_argument("--scheduled", action="store_true")+ parser.add_argument("--output", required=True, type=Path)+ parser.add_argument("--github-output", required=True, type=Path)+ args = parser.parse_args()+ result = plan(ROOT, source=args.source_commit, base=args.base, channel=args.channel,+ sequence=args.sequence, scheduled=args.scheduled)+ if result["prepare"] == "true":+ notes = render_notes(ROOT, source=result["source_commit"], version=result["version"])+ args.output.mkdir(parents=True, exist_ok=False)+ (args.output / "release-notes.md").write_text(notes, encoding="utf-8")+ (args.output / "plan.json").write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")+ with args.github_output.open("a", encoding="utf-8") as stream:+ stream.writelines(f"{key}={value}\n" for key, value in result.items())+ print(json.dumps(result))+++if __name__ == "__main__":+ main()diff --git a/tests/scripts/test_ci_workflows.py b/tests/scripts/test_ci_workflows.pyindex 7125983db..babf01d8c 100644--- a/tests/scripts/test_ci_workflows.py+++ b/tests/scripts/test_ci_workflows.py@@ -46,7 +46,7 @@ def test_accepted_handoff_uses_the_producer_id_and_requires_native_success():jobs = workflow("release-candidate.yml")["jobs"]assert jobs["candidate"]["outputs"]["prepared_artifact_id"] == "${{ steps.prepared.outputs.artifact-id }}"verified = jobs["verified"]- assert set(verified["needs"]) == {"candidate", "native"}+ assert set(verified["needs"]) == {"plan", "candidate", "native"}gate = verified["steps"][0]assert gate["env"]["NATIVE_RESULT"] == "${{ needs.native.result }}"assert gate["run"] == 'test "$BUILD_RESULT" = success && test "$NATIVE_RESULT" = success'diff --git a/tests/scripts/test_release_plan.py b/tests/scripts/test_release_plan.pynew file mode 100644index 000000000..e6de41cee--- /dev/null+++ b/tests/scripts/test_release_plan.py@@ -0,0 +1,139 @@+import json+import sys++import pytest+import yaml++from scripts import release_plan+from scripts.release_plan import WorkflowRun, daily_needed, git, plan, previous_tag, render_notes++SOURCE = "a" * 40+++def run(*, number=1, attempt=1, status="completed", conclusion="success", source=SOURCE,+ event="push", title="CI"):+ return WorkflowRun(head_sha=source, display_title=title, event=event, run_number=number,+ run_attempt=attempt, status=status, conclusion=conclusion)+++def test_daily_preparation_requires_latest_exact_source_ci():+ assert daily_needed(SOURCE, "0.4.1", [run()], [])+ for ci in ([], [run(source="b" * 40)], [run(event="pull_request")],+ [run(), run(number=2, conclusion="failure")],+ [run(), run(attempt=2, status="in_progress", conclusion=None)]):+ with pytest.raises(ValueError, match="latest push CI"):+ daily_needed(SOURCE, "0.4.1", ci, [])+++def test_daily_preparation_skips_same_base_and_source_but_retries_failed_candidates():+ previous = run(event="schedule", title=f"Candidate preview 0.4.1 from {SOURCE}")+ assert not daily_needed(SOURCE, "0.4.1", [run()], [previous])+ assert daily_needed(SOURCE, "0.5.0", [run()], [previous])+ for candidate in (previous.model_copy(update={"conclusion": "failure"}),+ previous.model_copy(update={"display_title": "Disabled daily candidate"}),+ previous.model_copy(update={"display_title": f"Candidate stable 0.4.1 from {SOURCE}"})):+ assert daily_needed(SOURCE, "0.4.1", [run()], [candidate])+++def history(tmp_path):+ git(tmp_path, "init", "-q")+ git(tmp_path, "config", "user.name", "Test")+ git(tmp_path, "config", "user.email", "[email protected]")+ git(tmp_path, "config", "commit.gpgsign", "false")+ git(tmp_path, "commit", "--allow-empty", "-qm", "Initial release")+ git(tmp_path, "tag", "v0.4.0")+ git(tmp_path, "commit", "--allow-empty", "-qm", "Fix delivery")+ source = git(tmp_path, "rev-parse", "HEAD")+ git(tmp_path, "checkout", "--detach", "-q")+ git(tmp_path, "commit", "--allow-empty", "-qm", "Prepare preview")+ git(tmp_path, "tag", "v0.4.1.dev1")+ git(tmp_path, "checkout", "--detach", "-q", source)+ git(tmp_path, "commit", "--allow-empty", "-qm", "Fix startup")+ source = git(tmp_path, "rev-parse", "HEAD")+ return tmp_path, source+++def test_notes_follow_release_line_and_skip_preview_version_commits(history):+ root, source = history+ stable = render_notes(root, source=source, version="0.4.1")+ preview = render_notes(root, source=source, version="0.4.1.dev2")+ assert "Changes since v0.4.0" in stable+ assert "Fix delivery" in stable and "Fix startup" in stable+ assert "Changes since v0.4.1.dev1" in preview+ assert "Fix startup" in preview and "Fix delivery" not in preview+ assert "Prepare preview" not in preview+ # A newer tag from another development line must not select unrelated history.+ git(root, "checkout", "--detach", "-q", "v0.4.0")+ git(root, "commit", "--allow-empty", "-qm", "Other line")+ git(root, "tag", "v0.4.2")+ assert previous_tag(root, source, "0.5.0") == "v0.4.0"+++def test_manual_stable_and_preview_keep_existing_channel_and_sequence(history, monkeypatch):+ root, source = history+ def no_network(*args):+ pytest.fail("Manual preparation must not depend on the daily scheduler API")+ monkeypatch.setattr(release_plan, "workflow_runs", no_network)+ stable = plan(root, source=source, base="0.4.1", channel="stable", sequence=42, scheduled=False)+ preview = plan(root, source=source, base="0.4.1", channel="preview", sequence=42, scheduled=False)+ assert stable == {"prepare": "true", "source_commit": source, "base": "0.4.1",+ "channel": "stable", "version": "0.4.1"}+ assert preview["version"] == "0.4.1.dev42"+ with pytest.raises(ValueError, match="already tagged"):+ plan(root, source=source, base="0.4.0", channel="preview", sequence=42, scheduled=False)+ with pytest.raises(ValueError, match="already tagged"):+ plan(root, source=source, base="0.4.1", channel="preview", sequence=1, scheduled=False)+++def test_cli_writes_only_local_notes_and_identity(history, tmp_path, monkeypatch):+ root, source = history+ monkeypatch.setattr(release_plan, "ROOT", root)+ output = tmp_path / "notes"+ github_output = tmp_path / "outputs"+ before = git(root, "show-ref")+ monkeypatch.setattr(sys, "argv", ["release_plan", "--source-commit", source, "--base", "0.4.1",+ "--channel", "stable", "--sequence", "7", "--output", str(output),+ "--github-output", str(github_output)])+ release_plan.main()+ assert "Fix startup" in (output / "release-notes.md").read_text()+ assert json.loads((output / "plan.json").read_text())["version"] == "0.4.1"+ assert "prepare=true\n" in github_output.read_text()+ assert git(root, "show-ref") == before+++def test_unchanged_daily_plan_does_not_create_a_candidate_handoff(history, tmp_path, monkeypatch):+ root, source = history+ monkeypatch.setattr(release_plan, "ROOT", root)+ previous = run(source=source, event="schedule", title=f"Candidate preview 0.4.1 from {source}")+ monkeypatch.setattr(release_plan, "workflow_runs", lambda workflow, *_:+ [run(source=source)] if workflow == "ci.yml" else [previous])+ output = tmp_path / "skipped"+ github_output = tmp_path / "outputs"+ monkeypatch.setattr(sys, "argv", ["release_plan", "--source-commit", source, "--base", "0.4.1",+ "--channel", "preview", "--sequence", "7", "--scheduled",+ "--output", str(output), "--github-output", str(github_output)])+ release_plan.main()+ assert "prepare=false\n" in github_output.read_text()+ assert not output.exists()+++def test_workflow_keeps_preparation_read_only_and_daily_opt_in():+ workflow = yaml.load((release_plan.ROOT / ".github/workflows/release-candidate.yml").read_text(),+ Loader=yaml.BaseLoader)+ assert workflow["permissions"] == {"contents": "read"}+ jobs = workflow["jobs"]+ assert "vars.NANOBOT_DAILY_CANDIDATES_ENABLED == 'true'" in jobs["plan"]["if"]+ assert "github.event_name == 'workflow_dispatch'" in jobs["plan"]["if"]+ assert "Disabled daily candidate" in workflow["run-name"]+ assert "NANOBOT_DAILY_CANDIDATES_ENABLED" in workflow["run-name"]+ assert jobs["plan"]["permissions"] == {"contents": "read", "actions": "read"}+ assert jobs["candidate"]["if"] == "needs.plan.outputs.prepare == 'true'"+ assert "needs.plan.outputs.prepare == 'true'" in jobs["verified"]["if"]+ assert workflow["concurrency"]["cancel-in-progress"] == "false"+ assert workflow["concurrency"]["group"] == "release-candidate-${{ github.event_name }}"+ retained = [step for job in jobs.values() for step in job.get("steps", [])+ if step.get("name") in {"Preserve the verified bytes and independent candidate source",+ "Retain accepted installable candidate for separate approval"}]+ assert len(retained) == 2+ assert all("inputs.retain_installable" in step["if"] for step in retained)