~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(release): publish the distributions verified by the release gate (#6648)
LearningCircuitf9605c3f008f
diff --git a/.github/scripts/release_package.py b/.github/scripts/release_package.pynew file mode 100644index 0000000000..aa5127fa36--- /dev/null+++ b/.github/scripts/release_package.py@@ -0,0 +1,397 @@+"""Bind published Python distributions to the artifacts tested by a release run."""++import argparse+import hashlib+import http.client+import json+import os+import re+import subprocess+import tarfile+import time+import urllib.request+import zipfile+from email.parser import BytesParser+from pathlib import Path+++def digest(path):+ with path.open("rb") as stream:+ return hashlib.file_digest(stream, "sha256").hexdigest()+++def fullmatch(pattern, value, label):+ if not isinstance(value, str) or not re.fullmatch(pattern, value):+ raise ValueError(f"Invalid {label}")+ return value+++def distributions(directory):+ paths = sorted(directory.iterdir())+ if len(paths) != 2 or any(+ path.is_symlink() or not path.is_file() for path in paths+ ):+ raise ValueError("Expected exactly two regular distribution files")+ wheels = [path for path in paths if path.name.endswith(".whl")]+ sdists = [path for path in paths if path.name.endswith(".tar.gz")]+ if len(wheels) != 1 or len(sdists) != 1:+ raise ValueError("Expected one wheel and one source distribution")+ for path in paths:+ fullmatch(r"[A-Za-z0-9_.+-]+", path.name, "distribution filename")+ return wheels[0], sdists[0]+++def package_version(directory):+ wheel, sdist = distributions(directory)+ with zipfile.ZipFile(wheel) as archive:+ names = [+ name+ for name in archive.namelist()+ if name.count("/") == 1 and name.endswith(".dist-info/METADATA")+ ]+ if len(names) != 1:+ raise ValueError("Wheel has no unique package metadata")+ wheel_metadata = BytesParser().parsebytes(archive.read(names[0]))+ # These bytes must survive the build and artifact transfer.+ prefix = "local_deep_research/web/static/dist/"+ names = archive.namelist()+ if prefix + ".vite/manifest.json" not in names or any(+ not any(+ name.startswith(prefix) and name.endswith(suffix)+ for name in names+ )+ for suffix in (".js", ".css")+ ):+ raise ValueError("Wheel is missing built frontend assets")+ with tarfile.open(sdist, "r:gz") as archive:+ entries = [+ entry+ for entry in archive.getmembers()+ if entry.name.count("/") == 1+ and entry.name.endswith("/PKG-INFO")+ and entry.isfile()+ ]+ if len(entries) != 1:+ raise ValueError(+ "Source distribution has no unique package metadata"+ )+ with archive.extractfile(entries[0]) as stream:+ sdist_metadata = BytesParser().parsebytes(stream.read())+ version = wheel_metadata["Version"]+ fullmatch(r"[0-9][A-Za-z0-9.+!_-]*", version, "package version")+ for metadata in (wheel_metadata, sdist_metadata):+ name = re.sub(r"[-_.]+", "-", metadata.get("Name", "")).lower()+ if name != "local-deep-research" or metadata["Version"] != version:+ raise ValueError("Wheel and sdist package metadata disagree")+ return version+++def manifest(directory, sha, run_id, attempt):+ fullmatch(r"[0-9a-f]{40}", sha, "release SHA")+ fullmatch(r"[1-9][0-9]*", run_id, "release run ID")+ fullmatch(r"[1-9][0-9]*", attempt, "artifact run attempt")+ return {+ "schema": 1,+ "sha": sha,+ "run_id": run_id,+ "run_attempt": attempt,+ "version": package_version(directory),+ "files": {path.name: digest(path) for path in distributions(directory)},+ }+++_PEP440 = re.compile(+ r"""+ v?+ (?:(?P<epoch>[0-9]+)!)?+ (?P<release>[0-9]+(?:\.[0-9]+)*)+ (?:[-_.]?(?P<pre_l>alpha|a|beta|b|preview|pre|c|rc)[-_.]?(?P<pre_n>[0-9]+)?)?+ (?:-(?P<post_n1>[0-9]+)|[-_.]?(?P<post_l>post|rev|r)[-_.]?(?P<post_n2>[0-9]+)?)?+ (?:[-_.]?(?P<dev_l>dev)[-_.]?(?P<dev_n>[0-9]+)?)?+ (?:\+(?P<local>[a-z0-9]+(?:[-_.][a-z0-9]+)*))?+ """,+ re.VERBOSE,+)+_PRE = {"alpha": "a", "beta": "b", "c": "rc", "pre": "rc", "preview": "rc"}+++def normalize_version(value):+ """Return the PEP 440 normal form, as build backends write to METADATA.++ Mirrors ``str(packaging.version.Version(value))`` without the dependency,+ because this script runs on bare runners before anything is installed.+ """+ match = _PEP440.fullmatch(value.strip().lower())+ if not match:+ raise ValueError("Invalid package version")+ parts = []+ if match["epoch"] and int(match["epoch"]):+ parts.append(f"{int(match['epoch'])}!")+ parts.append(".".join(str(int(n)) for n in match["release"].split(".")))+ if match["pre_l"]:+ label = _PRE.get(match["pre_l"], match["pre_l"])+ parts.append(f"{label}{int(match['pre_n'] or 0)}")+ if match["post_n1"] is not None or match["post_l"]:+ number = match["post_n1"] or match["post_n2"] or 0+ parts.append(f".post{int(number)}")+ if match["dev_l"]:+ parts.append(f".dev{int(match['dev_n'] or 0)}")+ if match["local"]:+ local = re.split(r"[-_.]", match["local"])+ parts.append(+ "+" + ".".join(str(int(p)) if p.isdigit() else p for p in local)+ )+ return "".join(parts)+++def verify(directory, path, expected_hash, sha, run_id, attempt=None, tag=None):+ fullmatch(r"[0-9a-f]{64}", expected_hash, "manifest SHA256")+ if digest(path) != expected_hash:+ raise ValueError(+ "Release manifest digest does not match the tested artifact"+ )+ data = json.loads(path.read_text(encoding="utf-8"))+ if not isinstance(data, dict):+ raise ValueError("Release manifest is not an object")+ actual = manifest(directory, sha, run_id, attempt or data["run_attempt"])+ if data != actual:+ raise ValueError(+ "Distribution hashes or release identity do not match the manifest"+ )+ # The tag comes from the raw __version__ string; the wheel carries its+ # PEP 440 normal form (e.g. 1.2.0-rc1 is built as 1.2.0rc1).+ if tag is not None and (+ not tag.startswith("v")+ or normalize_version(tag[1:]) != normalize_version(actual["version"])+ ):+ raise ValueError("Dispatch tag does not match package version")+ return actual+++def api(endpoint):+ result = subprocess.run(+ [+ "gh",+ "api",+ "--method",+ "GET",+ "-H",+ "Accept: application/vnd.github+json",+ endpoint,+ ],+ check=True,+ capture_output=True,+ text=True,+ timeout=60,+ )+ return json.loads(result.stdout)+++def validate_source(repo, payload, fetch=api):+ """Validate immutable artifact ownership and the successful release gates."""+ sha = fullmatch(r"[0-9a-f]{40}", payload["sha"], "release SHA")+ run_id = fullmatch(r"[1-9][0-9]*", str(payload["run_id"]), "release run ID")+ artifact_id = fullmatch(+ r"[1-9][0-9]*", str(payload["artifact_id"]), "artifact ID"+ )+ fullmatch(r"[0-9a-f]{64}", payload["manifest_sha256"], "manifest SHA256")+ fullmatch(r"v[0-9][A-Za-z0-9.+!_-]*", payload["tag"], "release tag")+ root = f"repos/{repo}"+ run = fetch(f"{root}/actions/runs/{run_id}")+ if (+ run["repository"]["full_name"] != repo+ or run["path"].split("@", 1)[0] != ".github/workflows/release.yml"+ or run["head_sha"] != sha+ or run["event"] not in {"push", "workflow_dispatch"}+ # release.yml runs for pushes to main and for the pushed v* tag,+ # whose name (head_branch) is the release tag it derives.+ or run["head_branch"] not in {"main", payload["tag"]}+ ):+ raise ValueError(+ "Source is not a release workflow run for the requested commit"+ )+ # The parent is still in progress while waiting for this publisher.+ # Verify its completed gates instead of requiring run-level success.+ jobs = {}+ for page in range(1, 101):+ response = fetch(+ f"{root}/actions/runs/{run_id}/jobs?filter=all&per_page=100&page={page}"+ )+ rows = response["jobs"]+ if not isinstance(rows, list):+ raise ValueError("Invalid source job response")+ for job in rows:+ previous = jobs.get(job["name"])+ if previous is None or job["id"] > previous["id"]:+ jobs[job["name"]] = job+ if len(rows) < 100:+ break+ else:+ raise ValueError("Source job pagination exceeded its limit")+ for name in ("release-gate / Release Gate Summary", "build"):+ job = jobs.get(name, {})+ if (+ job.get("status") != "completed"+ or job.get("conclusion") != "success"+ ):+ raise ValueError(f"Required source job did not succeed: {name}")+ if fetch(f"{root}/compare/{sha}...heads/main")["status"] not in {+ "ahead",+ "identical",+ }:+ raise ValueError("Release commit is not an ancestor of main")+ artifact = fetch(f"{root}/actions/artifacts/{artifact_id}")+ match = re.fullmatch(+ r"verified-python-dist-([1-9][0-9]*)", artifact["name"]+ )+ if (+ not match+ or artifact["expired"] is not False+ or str(artifact["id"]) != artifact_id+ or str(artifact["workflow_run"]["id"]) != run_id+ or artifact["workflow_run"]["head_sha"] != sha+ ):+ raise ValueError(+ "Artifact is expired or does not belong to the verified release run"+ )+ return match[1]+++def output(name, value):+ with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as stream:+ stream.write(f"{name}={value}\n")+++class PublishedHashMismatch(ValueError):+ """A tested file is on PyPI with different bytes; waiting cannot help."""+++def check_published_hashes(expected, response):+ if not isinstance(expected, dict) or len(expected) != 2:+ raise ValueError("Missing tested distribution hashes")+ actual = {+ entry["filename"]: entry["digests"]["sha256"]+ for entry in response["urls"]+ }+ # PyPI files are immutable, so a present file with another hash is final.+ # Missing files may still be propagating and stay retryable.+ if any(+ name in actual and actual[name] != value+ for name, value in expected.items()+ ):+ raise PublishedHashMismatch(+ "PyPI distribution hashes differ from the tested artifacts"+ )+ if actual != expected:+ raise ValueError(+ "PyPI does not list exactly the tested distribution files"+ )+++# Seconds to wait between PyPI JSON lookups, so a slow PyPI index does not+# fail a release whose files uploaded correctly: 610 s of backoff sleeps, or+# about 15 minutes worst case once the nine 30 s request timeouts are added.+PUBLISHED_RETRY_DELAYS = (10, 20, 40, 60, 120, 120, 120, 120)+++def verify_published(+ delays=PUBLISHED_RETRY_DELAYS,+ opener=urllib.request.urlopen,+ sleep=time.sleep,+):+ # PACKAGE_VERSION comes from the tag; PyPI indexes the normal form.+ version = normalize_version(+ fullmatch(+ r"[0-9][A-Za-z0-9.+!_-]*",+ os.environ["PACKAGE_VERSION"],+ "package version",+ )+ )+ expected = json.loads(os.environ["EXPECTED_HASHES"])+ for attempt in range(len(delays) + 1):+ try:+ with opener(+ f"https://pypi.org/pypi/local-deep-research/{version}/json",+ timeout=30,+ ) as response:+ check_published_hashes(expected, json.load(response))+ print("PyPI file hashes match the release gate's tested artifacts")+ return+ # URLError and read timeouts are both OSError subclasses; a response+ # cut off mid-body raises http.client.IncompleteRead, which is not.+ except (OSError, http.client.HTTPException, ValueError) as exc:+ if isinstance(exc, PublishedHashMismatch) or attempt == len(delays):+ raise+ print(+ f"Waiting {delays[attempt]}s for matching package hashes "+ f"on PyPI: {exc}",+ flush=True,+ )+ sleep(delays[attempt])+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "command", choices=("create", "verify", "source", "published")+ )+ args = parser.parse_args()+ try:+ if args.command == "published":+ verify_published()+ elif args.command == "source":+ event = json.loads(+ Path(os.environ["GITHUB_EVENT_PATH"]).read_text(+ encoding="utf-8"+ )+ )+ attempt = validate_source(+ os.environ["GITHUB_REPOSITORY"], event["client_payload"]+ )+ output("artifact_attempt", attempt)+ elif args.command == "create":+ data = manifest(+ Path("dist"),+ os.environ["GITHUB_SHA"],+ os.environ["GITHUB_RUN_ID"],+ os.environ["GITHUB_RUN_ATTEMPT"],+ )+ path = Path("release-package.json")+ path.write_text(+ json.dumps(data, sort_keys=True) + "\n", encoding="utf-8"+ )+ output("manifest_sha256", digest(path))+ else:+ data = verify(+ Path("dist"),+ Path("release-package.json"),+ os.environ["MANIFEST_SHA256"],+ os.environ["RELEASE_SHA"],+ os.environ["RELEASE_RUN_ID"],+ os.environ.get("ARTIFACT_ATTEMPT"),+ os.environ.get("RELEASE_TAG"),+ )+ output(+ "file_hashes",+ json.dumps(+ data["files"], sort_keys=True, separators=(",", ":")+ ),+ )+ except (+ OSError,+ http.client.HTTPException,+ ValueError,+ KeyError,+ TypeError,+ AttributeError,+ tarfile.TarError,+ zipfile.BadZipFile,+ subprocess.SubprocessError,+ ) as exc:+ print(f"::error::Release package verification failed: {exc}")+ return 1+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.ymlindex b115db235f..933d0020df 100644--- a/.github/workflows/publish.yml+++ b/.github/workflows/publish.yml@@ -1,570 +1,129 @@name: Publish to PyPI+run-name: PyPI release ${{ github.event.client_payload.run_id }} artifact ${{ github.event.client_payload.artifact_id }}-# SECURITY: Only triggered via repository_dispatch from release.yml-# (after security gate passes). We intentionally do NOT support-# workflow_dispatch because that would bypass security checks.-# To re-publish, trigger a new release through release.yml.-#-# REPRODUCIBILITY: repository_dispatch runs on default-branch HEAD at-# dispatch time — NOT the release commit. The `release` env approval is-# human-paced, so main can move between the release commit and the-# dispatch (on v1.9.0 it was 4 PRs ahead, and PyPI shipped code absent-# from the tag/Docker image). Both build jobs therefore check out-# `client_payload.sha` — the exact commit every gate ran against — and-# fail closed if the dispatcher didn't pin it.+# Keep this top-level workflow for PyPI Trusted Publishing. The release gate+# builds and tests the distributions; this workflow verifies and publishes+# those exact bytes, even when main advances during environment approval.on:repository_dispatch:types: [publish-pypi]-permissions: {} # Minimal top-level for OSSF Scorecard Token-Permissions+permissions: {}jobs:- # Build frontend if package.json exists (isolated, no secrets)- build-frontend:- runs-on: ubuntu-latest- outputs:- has-frontend: ${{ steps.check.outputs.has-frontend }}- container:- # Node 24 to match `package.json`'s `engines: { node: ">=24.0.0" }`.- # Was previously node:20 — npm could resolve dependencies that target- # APIs missing on 20 and the wheel-building publish path could ship- # frontend assets that break at runtime on the Node-24 Docker image.- image: node:24-alpine@sha256:d1b3b4da11eefd5941e7f0b9cf17783fc99d9c6fc34884a665f40a06dbdfc94f # node:24-alpine- # Note: Network is needed for npm ci to work, but no secrets are available- options: --user 1001- permissions:- contents: read-- steps:- - name: Harden the runner (Audit all outbound calls)- uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1- with:- egress-policy: audit-- - name: Validate pinned release commit- # POSIX sh (this job's container is Alpine — no bash). Fail closed:- # without a full 40-hex SHA, checkout would silently fall back to- # default-branch HEAD and reintroduce the drift this pin prevents.- # The length test matters: grep -E matches PER LINE, so a crafted- # multiline value ("<40-hex>\n<junk>") would pass the regex alone;- # ${#VAR} counts bytes in POSIX sh, so -eq 40 also excludes any- # embedded newline. Ancestry (sha actually on main) is enforced in- # build-package — this container has no python3/gh; this job holds- # no secrets and its output only reaches PyPI through build-package,- # which checks out the same validated sha.- env:- RELEASE_SHA: ${{ github.event.client_payload.sha }}- run: |- if [ "${#RELEASE_SHA}" -ne 40 ] || ! printf '%s' "$RELEASE_SHA" | grep -qE '^[0-9a-f]{40}$'; then- echo "::error::client_payload.sha is missing or not a full commit SHA — refusing to build from default-branch HEAD. The dispatcher (release.yml trigger-pypi) must pin the release commit."- exit 1- fi- echo "Building from pinned release commit $RELEASE_SHA"-- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1-- with:- ref: ${{ github.event.client_payload.sha }}- persist-credentials: false-- - name: Check for frontend assets- id: check- run: |- if [ -f "package.json" ]; then- echo "has-frontend=true" >> "$GITHUB_OUTPUT"- echo "Found package.json - will build frontend"- else- echo "has-frontend=false" >> "$GITHUB_OUTPUT"- echo "ERROR: No package.json found - frontend build is required for PyPI releases"- exit 1- fi-- - name: Build frontend- if: steps.check.outputs.has-frontend == 'true'- run: |- echo "=== Frontend Build Process Starting ==="- echo "Current directory: $(pwd)"- echo "Node version: $(node --version)"- echo "NPM version: $(npm --version)"-- # Install dependencies from root package.json- echo ""- echo "📦 Installing dependencies..."- # Use npm ci for reproducible builds from lockfile- npm ci --ignore-scripts --no-audit --no-fund- echo "✅ Dependencies installed"-- # Show pre-build directory structure- echo ""- echo "📁 Pre-build directory structure:"- echo "Contents of src/local_deep_research/web/static/:"- find src/local_deep_research/web/static/ -maxdepth 1 -type f -exec ls -la {} + 2>/dev/null || echo "Directory not found"-- # Build with Vite (outputs to src/local_deep_research/web/static/dist)- echo ""- echo "🔨 Running Vite build..."- npm run build- echo "✅ Vite build completed"-- # Show post-build directory structure- echo ""- echo "📁 Post-build directory structure:"- echo "Contents of src/local_deep_research/web/static/:"- find src/local_deep_research/web/static/ -maxdepth 1 -type f -exec ls -la {} + 2>/dev/null- echo ""- echo "Contents of src/local_deep_research/web/static/dist/:"- find src/local_deep_research/web/static/dist/ -maxdepth 1 -type f -exec ls -la {} + 2>/dev/null- echo ""- echo "Looking for manifest.json:"- find src/local_deep_research/web/static/dist -name "manifest.json" -type f 2>/dev/null || echo "No manifest.json found"-- # Verify the build completed successfully- if [ ! -f "src/local_deep_research/web/static/dist/.vite/manifest.json" ]; then- echo "❌ ERROR: Build failed - manifest.json not created at expected location"- echo "Expected location: src/local_deep_research/web/static/dist/.vite/manifest.json"- echo "Actual dist contents:"- find src/local_deep_research/web/static/dist -type f | head -20- exit 1- fi-- echo "✅ Found manifest.json at: src/local_deep_research/web/static/dist/.vite/manifest.json"- echo "Manifest contents (first 10 lines):"- head -10 src/local_deep_research/web/static/dist/.vite/manifest.json-- # Create build marker- echo ""- echo "📝 Creating build marker..."- echo "{\"status\":\"complete\",\"built\":\"$(date -Iseconds)\"}" > src/local_deep_research/web/static/.frontend-built- echo "✅ Build marker created"-- - name: Upload frontend artifacts- if: steps.check.outputs.has-frontend == 'true'- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1- with:- name: frontend-assets- path: src/local_deep_research/web/static/- retention-days: 1- include-hidden-files: true # Ensure .vite directory is included-- # Build Python package (isolated, no PyPI access)build-package:- needs: build-frontend+ name: Verify tested release packageruns-on: ubuntu-latest- container:- image: python:3.12-slim@sha256:971f04b358cf483ec445a8d388fb55267451f080d90fb136c8e69684a02a9604 # python:3.12-slim+ timeout-minutes: 10permissions:contents: read-+ actions: read+ outputs:+ file_hashes: ${{ steps.verify.outputs.file_hashes }}+ artifact_id: ${{ steps.publisher-upload.outputs.artifact-id }}steps:- - name: Harden the runner (Audit all outbound calls)- uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1- with:- egress-policy: audit-- - name: Validate pinned release commit- # Same fail-closed shape guard as build-frontend (length test: see- # comment there), plus the ANCESTRY check that only this job can- # run (python3 in the container): the pinned sha must be reachable- # from main. Anyone able to send repository_dispatch (repo write /- # the PAT holder) chooses the payload — without this check they- # could point the build at ANY commit object in the repo network- # (scratch branches, fork-PR heads) that never passed review or the- # release gates. release.yml's own build job verifies its sha is on- # main, but a forged dispatch bypasses release.yml entirely; the- # `release` environment approval on the publish job is then the- # only barrier, and an approver has no reason to suspect a- # legitimate-looking pending deployment. Enforced here (not in- # build-frontend) because every byte that reaches PyPI flows- # through this job's checkout.- env:- RELEASE_SHA: ${{ github.event.client_payload.sha }}- GH_TOKEN: ${{ github.token }}- run: |- if [ "${#RELEASE_SHA}" -ne 40 ] || ! printf '%s' "$RELEASE_SHA" | grep -qE '^[0-9a-f]{40}$'; then- echo "::error::client_payload.sha is missing or not a full commit SHA — refusing to build from default-branch HEAD. The dispatcher (release.yml trigger-pypi) must pin the release commit."- exit 1- fi- python3 - <<'PYEOF'- import json- import os- import sys- import urllib.request-- sha = os.environ["RELEASE_SHA"]- repo = os.environ["GITHUB_REPOSITORY"]- req = urllib.request.Request(- f"https://api.github.com/repos/{repo}/compare/{sha}...heads/main",- headers={- "Authorization": f"Bearer {os.environ['GH_TOKEN']}",- "Accept": "application/vnd.github+json",- },- )- try:- with urllib.request.urlopen(req) as resp:- status = json.load(resp)["status"]- except urllib.error.HTTPError as exc:- # 404 = sha unknown to the repo network. Fail closed either way.- print(f"::error::compare API rejected sha {sha}: HTTP {exc.code}")- sys.exit(1)- # base=sha, head=main: main being "ahead" of (or "identical" to)- # the sha means the sha is an ancestor of main. "diverged" or- # "behind" means it is not.- if status not in ("ahead", "identical"):- print(- f"::error::pinned sha {sha} is not an ancestor of main "- f"(compare status: {status}) — refusing to build unreviewed code"- )- sys.exit(1)- print(f"Pinned sha is on main (compare status: {status})")- PYEOF- echo "Building from pinned release commit $RELEASE_SHA"-- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1-- with:- ref: ${{ github.event.client_payload.sha }}- persist-credentials: false-- - name: Install build dependencies- run: |- apt-get update && apt-get install -y libsqlcipher-dev build-essential- pip install pdm==2.26.2-- - name: Download frontend artifacts- if: needs.build-frontend.outputs.has-frontend == 'true'- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1- continue-on-error: true- with:- name: frontend-assets- path: src/local_deep_research/web/static/-- - name: Verify frontend build artifacts- run: |- echo "=== Frontend Artifacts Verification ==="- echo "Current directory: $(pwd)"- echo ""- echo "📁 Checking downloaded artifacts structure:"- echo "Contents of src/:"- find src/ -maxdepth 1 -type f -exec ls -la {} + 2>/dev/null || echo "src/ directory not found"- echo ""- echo "Contents of src/local_deep_research/:"- find src/local_deep_research/ -maxdepth 1 -type f -exec ls -la {} + 2>/dev/null || echo "src/local_deep_research/ not found"- echo ""- echo "Contents of src/local_deep_research/web/:"- find src/local_deep_research/web/ -maxdepth 1 -type f -exec ls -la {} + 2>/dev/null || echo "src/local_deep_research/web/ not found"- echo ""- echo "Contents of src/local_deep_research/web/static/:"- find src/local_deep_research/web/static/ -maxdepth 1 -type f -exec ls -la {} + 2>/dev/null || echo "src/local_deep_research/web/static/ not found"-- # Check if dist directory exists- echo ""- echo "🔍 Checking for dist directory..."- if [ ! -d "src/local_deep_research/web/static/dist" ]; then- echo "❌ ERROR: Frontend dist directory not found!"- echo "Expected location: src/local_deep_research/web/static/dist"- echo "Actual structure of static directory:"- find src/local_deep_research/web/static -type d 2>/dev/null | head -20- echo "The frontend build artifacts are missing."- exit 1- fi- echo "✅ Found dist directory at: src/local_deep_research/web/static/dist"-- # Show dist directory structure- echo ""- echo "📁 Dist directory structure:"- echo "Contents of dist/:"- find src/local_deep_research/web/static/dist/ -maxdepth 1 -type f -exec ls -la {} + 2>/dev/null- echo ""- echo "All files in dist (recursive):"- find src/local_deep_research/web/static/dist -type f | head -20-- # Check for critical files- echo ""- echo "🔍 Checking for manifest.json..."- # Check both possible locations for manifest.json- MANIFEST_PATH=""- if [ -f "src/local_deep_research/web/static/dist/.vite/manifest.json" ]; then- MANIFEST_PATH="src/local_deep_research/web/static/dist/.vite/manifest.json"- elif [ -f "src/local_deep_research/web/static/dist/manifest.json" ]; then- MANIFEST_PATH="src/local_deep_research/web/static/dist/manifest.json"- fi-- if [ -z "$MANIFEST_PATH" ]; then- echo "❌ ERROR: Vite manifest.json not found!"- echo "Checked locations:"- echo " - src/local_deep_research/web/static/dist/.vite/manifest.json"- echo " - src/local_deep_research/web/static/dist/manifest.json"- echo "Looking for any manifest.json files:"- find src/local_deep_research/web/static -name "manifest.json" -type f 2>/dev/null || echo "None found"- echo "Checking if .vite directory exists:"- find src/local_deep_research/web/static/dist/ -maxdepth 1 -name ".*" -type d || echo "No hidden directories found"- echo ""- echo "This is likely due to artifact transfer losing the hidden .vite directory."- echo "The include-hidden-files option should fix this."- echo "The frontend build appears to be incomplete - cannot continue."- exit 1- fi- echo "✅ Found manifest.json at: $MANIFEST_PATH"- echo "Manifest size: $(wc -c < "$MANIFEST_PATH") bytes"-- # Check for JS files- echo ""- echo "🔍 Checking for JavaScript files..."- JS_COUNT=$(find src/local_deep_research/web/static/dist -name "*.js" -type f | wc -l)- if [ "$JS_COUNT" -eq 0 ]; then- echo "❌ ERROR: No JavaScript files found!"- echo "Expected JS files in dist/"- echo "The frontend build appears to be incomplete."- exit 1- fi- echo "✅ Found $JS_COUNT JavaScript file(s)"- echo "JS files:"- find src/local_deep_research/web/static/dist -name "*.js" -type f | head -5-- # Check for CSS files- echo ""- echo "🔍 Checking for CSS files..."- CSS_COUNT=$(find src/local_deep_research/web/static/dist -name "*.css" -type f | wc -l)- if [ "$CSS_COUNT" -eq 0 ]; then- echo "❌ ERROR: No CSS files found!"- echo "Expected CSS files in dist/"- echo "The frontend build appears to be incomplete."- exit 1- fi- echo "✅ Found $CSS_COUNT CSS file(s)"- echo "CSS files:"- find src/local_deep_research/web/static/dist -name "*.css" -type f | head -5-- # Check for build marker- echo ""- echo "🔍 Checking for build marker..."- if [ ! -f "src/local_deep_research/web/static/.frontend-built" ]; then- echo "⚠️ WARNING: Frontend build marker not found (non-critical)"- else- echo "✅ Found build marker"- echo "Build marker contents:"- cat src/local_deep_research/web/static/.frontend-built- fi-- echo ""- echo "=== ✅ Frontend build artifacts verified successfully ==="- echo "Summary:"- echo " - Dist directory: ✓"- echo " - Manifest.json: ✓"- echo " - JS files: $JS_COUNT file(s)"- echo " - CSS files: $CSS_COUNT file(s)"-- - name: Build Python package- run: |- echo "=== Python Package Build ==="- echo "Current directory: $(pwd)"- echo ""- echo "📦 Building Python package with PDM..."- pdm build- echo ""- echo "✅ Package build completed"- echo ""- echo "📁 Package contents:"- find dist/ -maxdepth 1 -type f -exec ls -la {} + 2>/dev/null- echo ""- echo "Package sizes:"- du -h dist/*-- - name: Enforce package artifact policy- run: python .github/scripts/package_artifact_policy.py dist/-- - name: Upload package- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1- with:- name: python-dist- path: dist/- retention-days: 1-- # Publish (ONLY job with PyPI access)+ - name: Harden runner+ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1+ with:+ egress-policy: audit+ # This is trusted default-branch policy, not code from a dispatch payload.+ - name: Checkout verification policy+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - name: Validate source release run and artifact ownership+ id: source+ env:+ GH_TOKEN: ${{ github.token }}+ run: python3 .github/scripts/release_package.py source+ - name: Download tested release artifact by ID+ uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1+ with:+ github-token: ${{ github.token }}+ run-id: ${{ github.event.client_payload.run_id }}+ artifact-ids: ${{ github.event.client_payload.artifact_id }}+ merge-multiple: true+ path: tested-package/+ - name: List packages+ run: ls -l tested-package/dist/+ - name: Enforce package artifact policy+ run: python .github/scripts/package_artifact_policy.py tested-package/dist/+ - name: Verify tested package identity and hashes+ id: verify+ working-directory: tested-package+ env:+ RELEASE_SHA: ${{ github.event.client_payload.sha }}+ RELEASE_RUN_ID: ${{ github.event.client_payload.run_id }}+ RELEASE_TAG: ${{ github.event.client_payload.tag }}+ ARTIFACT_ATTEMPT: ${{ steps.source.outputs.artifact_attempt }}+ MANIFEST_SHA256: ${{ github.event.client_payload.manifest_sha256 }}+ run: python3 ../.github/scripts/release_package.py verify+ - name: Transfer verified distributions to publisher+ id: publisher-upload+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: python-dist-${{ github.run_attempt }}+ path: tested-package/dist/+ if-no-files-found: error+ retention-days: 14++ # No checkout, installation or package execution in the OIDC-enabled job.publish:needs: build-packageruns-on: ubuntu-latestenvironment: releasepermissions:id-token: write- attestations: write # Required for generating attestations-steps:- - name: Harden Runner- uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1- with:- egress-policy: audit-- - name: Download package- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1- with:- name: python-dist- path: dist/-- - name: List packages- run: |- echo "=== Downloaded Package Artifacts ==="- echo "📦 Packages in dist/:"- ls -lh dist/- echo ""- echo "Package details:"- for file in dist/*; do- echo " - $(basename "$file"): $(du -h "$file" | cut -f1)"- done-- - name: Verify package contents- run: |- echo "=== Package Content Verification ==="- echo "Verifying package contains frontend assets..."- echo ""-- # Install wheel to inspect package- echo "📦 Installing wheel for package inspection..."- pip install wheel==0.46.2-- # Find the wheel file- WHEEL_FILE=$(find dist -name "*.whl" -type f 2>/dev/null | head -1)- TAR_FILE=$(find dist -name "*.tar.gz" -type f 2>/dev/null | head -1)-- if [ -z "$WHEEL_FILE" ]; then- echo "❌ ERROR: No wheel file found in dist/"- echo "Found files:"- find dist/ -maxdepth 1 -type f -exec ls -la {} + 2>/dev/null- exit 1- fi-- echo "✅ Found wheel file: $WHEEL_FILE"- echo "Wheel size: $(du -h "$WHEEL_FILE" | cut -f1)"- echo ""-- if [ -n "$TAR_FILE" ]; then- echo "✅ Found source distribution: $TAR_FILE"- echo "Source dist size: $(du -h "$TAR_FILE" | cut -f1)"- fi- echo ""-- echo "🔍 Inspecting wheel contents..."- # Extract and check for frontend files- python -m zipfile -l "$WHEEL_FILE" > wheel_contents.txt-- TOTAL_FILES=$(wc -l < wheel_contents.txt)- echo "Total files in wheel: $TOTAL_FILES"- echo ""-- # Count different file types- echo "📊 File type breakdown:"- echo " Python files: $(grep -c '\.py' wheel_contents.txt || echo 0)"- echo " JavaScript files: $(grep -c '\.js' wheel_contents.txt || echo 0)"- echo " CSS files: $(grep -c '\.css' wheel_contents.txt || echo 0)"- echo " JSON files: $(grep -c '\.json' wheel_contents.txt || echo 0)"- echo " HTML files: $(grep -c '\.html' wheel_contents.txt || echo 0)"- echo ""-- # Check for critical frontend directories/files- echo "🔍 Checking for frontend assets..."-- echo "Looking for dist directory..."- if ! grep -q "local_deep_research/web/static/dist/" wheel_contents.txt; then- echo "❌ ERROR: Frontend dist directory not found in package!"- echo "Package is missing frontend build artifacts."- echo "Static files found in package:"- grep "static" wheel_contents.txt | head -10 || echo "No static files found"- exit 1- fi- echo "✅ Found dist directory"-- echo ""- echo "Looking for JavaScript files..."- JS_IN_WHEEL=$(grep -c "local_deep_research/web/static/dist.*\.js" wheel_contents.txt || echo 0)- if [ "$JS_IN_WHEEL" -eq 0 ]; then- echo "❌ ERROR: Frontend JS files not found in package!"- echo "JavaScript files in package:"- grep "\.js" wheel_contents.txt | head -10 || echo "No JS files found"- exit 1- fi- echo "✅ Found $JS_IN_WHEEL JavaScript file(s) in dist"-- echo ""- echo "Looking for CSS files..."- CSS_IN_WHEEL=$(grep -c "local_deep_research/web/static/dist.*\.css" wheel_contents.txt || echo 0)- if [ "$CSS_IN_WHEEL" -eq 0 ]; then- echo "❌ ERROR: Frontend CSS files not found in package!"- echo "CSS files in package:"- grep "\.css" wheel_contents.txt | head -10 || echo "No CSS files found"- exit 1- fi- echo "✅ Found $CSS_IN_WHEEL CSS file(s) in dist"-- echo ""- echo "Looking for manifest.json..."- if ! grep -q "local_deep_research/web/static/dist/.vite/manifest.json" wheel_contents.txt; then- echo "⚠️ WARNING: manifest.json not found in package (may be okay)"- else- echo "✅ Found manifest.json"- fi-- echo ""- echo "=== ✅ Package verification successful ==="- echo "Summary:"- echo " - Wheel file: ✓"- echo " - Frontend dist: ✓"- echo " - JS files: $JS_IN_WHEEL file(s)"- echo " - CSS files: $CSS_IN_WHEEL file(s)"- echo ""- echo "Sample frontend assets in package:"- grep "local_deep_research/web/static/dist/" wheel_contents.txt | head -10-- - name: Generate attestations- uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2- with:- subject-path: 'dist/*'-- - name: Pre-publish summary- env:- EVENT_NAME: ${{ github.event_name }}- DISPATCH_TAG: ${{ github.event.client_payload.tag }}- DISPATCH_PRERELEASE: ${{ github.event.client_payload.prerelease }}- RELEASE_TAG: ${{ github.event.release.tag_name }}- RELEASE_PRERELEASE: ${{ github.event.release.prerelease }}- run: |- echo "=== 🚀 Ready to Publish ==="- echo ""- echo "📦 Package Information:"- # Handle both release event and repository_dispatch- if [ "$EVENT_NAME" = "repository_dispatch" ]; then- echo " - Trigger: repository_dispatch"- echo " - Tag: $DISPATCH_TAG"- echo " - Prerelease: $DISPATCH_PRERELEASE"- else- echo " - Trigger: release"- echo " - Tag: $RELEASE_TAG"- echo " - Prerelease: $RELEASE_PRERELEASE"- fi- echo ""- echo "📁 Package files to publish:"- ls -lh dist/- echo ""- echo "✅ All checks passed - proceeding with publication"-- - name: Publish to Test PyPI- if: (github.event_name == 'release' && github.event.release.prerelease == true) || (github.event_name == 'repository_dispatch' && github.event.client_payload.prerelease == true)- uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2- with:- repository-url: https://test.pypi.org/legacy/- skip-existing: true # Don't fail if version already exists-- - name: Publish to PyPI- if: (github.event_name == 'release' && github.event.release.prerelease != true) || (github.event_name == 'repository_dispatch' && github.event.client_payload.prerelease != true)- uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2- with:- skip-existing: true # Don't fail if version already exists+ - name: Harden runner+ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1+ with:+ egress-policy: audit+ - name: Download verified package+ uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1+ with:+ artifact-ids: ${{ needs.build-package.outputs.artifact_id }}+ merge-multiple: true+ path: dist/+ - name: Recheck hashes before publication+ env:+ EXPECTED_HASHES: ${{ needs.build-package.outputs.file_hashes }}+ run: |+ python3 - <<'PYCODE'+ import hashlib+ import json+ import os+ from pathlib import Path+ expected = json.loads(os.environ["EXPECTED_HASHES"])+ files = list(Path("dist").iterdir())+ assert len(expected) == 2 and {p.name for p in files} == set(expected), "distribution set changed"+ for path in files:+ assert path.is_file() and not path.is_symlink(), "invalid distribution file"+ with path.open("rb") as stream:+ actual = hashlib.file_digest(stream, "sha256").hexdigest()+ assert actual == expected[path.name], f"distribution digest changed: {path.name}"+ print("Publishing the exact distributions tested by the release gate")+ PYCODE+ - name: Publish to Test PyPI+ if: github.event.client_payload.prerelease == true+ uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2+ with:+ repository-url: https://test.pypi.org/legacy/+ skip-existing: true+ - name: Publish to PyPI+ if: github.event.client_payload.prerelease != true+ uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2+ with:+ skip-existing: true# Verify the published package is installable (skipped for prereleases which go to Test PyPI)verify-publish:- needs: publish+ needs: [publish, build-package]if: ${{ !(github.event_name == 'release' && github.event.release.prerelease == true) && !(github.event_name == 'repository_dispatch' && github.event.client_payload.prerelease == true) }}runs-on: ubuntu-latest- timeout-minutes: 15+ # Covers the PyPI hash lookup (610 s of backoff sleeps, about 15 minutes+ # worst case including per-request timeouts) plus the install retries.+ timeout-minutes: 30permissions:contents: read@@ -596,10 +155,16 @@ jobs:sudo apt-get updatesudo apt-get install -y libsqlcipher-dev- - name: Wait for PyPI index to update- run: |- echo "Waiting 60 seconds for PyPI index propagation..."- sleep 60+ - name: Checkout verification policy+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false++ - name: Verify published file hashes+ env:+ PACKAGE_VERSION: ${{ steps.version.outputs.version }}+ EXPECTED_HASHES: ${{ needs.build-package.outputs.file_hashes }}+ run: python3 .github/scripts/release_package.py published- name: Verify package installationrun: |diff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.ymlindex 5cef90e51d..b0253a496e 100644--- a/.github/workflows/release-gate.yml+++ b/.github/workflows/release-gate.yml@@ -21,6 +21,13 @@ name: Release Gateon:workflow_call: # Called by release.yml+ outputs:+ package_artifact_id:+ description: Immutable artifact containing the tested wheel and sdist+ value: ${{ jobs.pip-install-check.outputs.artifact_id }}+ package_manifest_sha256:+ description: SHA256 of the tested distribution manifest+ value: ${{ jobs.pip-install-check.outputs.manifest_sha256 }}workflow_dispatch: # Manual triggerschedule:# Run daily at 2 AM UTC to catch security issues early@@ -328,6 +335,9 @@ jobs:# └─────────────────────────────────────────────────────────────────┘pip-install-check:name: pip Install Verification+ outputs:+ artifact_id: ${{ steps.package-upload.outputs.artifact-id }}+ manifest_sha256: ${{ steps.package-manifest.outputs.manifest_sha256 }}runs-on: ubuntu-latesttimeout-minutes: 15permissions:@@ -357,11 +367,7 @@ jobs:- name: Install Node.js for Vite builduses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0with:- # Match package.json's `engines: { node: ">=24.0.0" }` and- # publish.yml's node:24-alpine. Building the wheel-tested- # frontend on Node 20 here while the real publish runs on- # Node 24 means the gate validates a different runtime than- # ships, defeating the gate's stated purpose.+ # Match package.json and the Docker frontend build.node-version: '24'- name: Set up PDM (build only)@@ -371,12 +377,31 @@ jobs:- name: Build Vite frontend assetsrun: |- npm ci+ # These assets ship in the published wheel: never run dependency+ # install scripts while producing them.+ npm ci --ignore-scripts --no-audit --no-fundnpm run build+ if [ ! -f src/local_deep_research/web/static/dist/.vite/manifest.json ]; then+ echo "::error::Vite build did not produce its manifest"+ exit 1+ fi- name: Build wheel and source distribution with PDMrun: pdm build+ # Record the hashes before anything installs, imports or runs the built+ # package or its dependencies in this workspace. The in-job verify step+ # after the smoke tests only catches accidental rewrites of dist/: code+ # that ran on this runner could also tamper with the verifier (the+ # checked-out script or the interpreter running it). Protection against+ # hostile rewrites comes from the later jobs on separate runners+ # (package-install-matrix, release.yml's build job and publish.yml),+ # which check the downloaded artifact against the manifest digest+ # recorded here before any package code ran.+ - name: Record built package hashes+ id: package-manifest+ run: python .github/scripts/release_package.py create+- name: Enforce package artifact policyrun: python .github/scripts/package_artifact_policy.py dist/@@ -402,9 +427,10 @@ jobs:echo "This simulates what end users experience with: pip install local-deep-research"echo ""- WHEEL=$(find dist/ -maxdepth 1 -name '*.whl' -print -quit)- if [ -z "$WHEEL" ]; then- echo "::error::No wheel found in dist/"+ # Install the wheel whose hash was recorded above.+ WHEEL=$(python -c 'import json; print(next(f"dist/{n}" for n in json.load(open("release-package.json"))["files"] if n.endswith(".whl")))')+ if [ ! -f "$WHEEL" ]; then+ echo "::error::Recorded wheel not found in dist/"exit 1fiecho "Wheel: $WHEEL"@@ -436,7 +462,7 @@ jobs:# of "PyPI project page silently broken" failures pip-install-check# cannot see. Installed transiently inside the throwaway venv.pip install --quiet twine- twine check --strict "$WHEEL"+ twine check --strict dist/*echo ""echo "=== Installing [mcp] extra so ldr-mcp can resolve ==="@@ -476,6 +502,93 @@ jobs:echo ""echo "✅ pip install verification passed — wheel is safe to publish"+ - name: Verify tested distributions are unchanged+ env:+ RELEASE_SHA: ${{ github.sha }}+ RELEASE_RUN_ID: ${{ github.run_id }}+ ARTIFACT_ATTEMPT: ${{ github.run_attempt }}+ MANIFEST_SHA256: ${{ steps.package-manifest.outputs.manifest_sha256 }}+ run: python .github/scripts/release_package.py verify++ - name: Upload tested distributions+ id: package-upload+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: verified-python-dist-${{ github.run_attempt }}+ path: |+ dist/+ release-package.json+ if-no-files-found: error+ retention-days: 14++ package-install-matrix:+ name: Package install (${{ matrix.python }}, ${{ matrix.distribution }})+ needs: pip-install-check+ runs-on: ubuntu-latest+ timeout-minutes: 20+ permissions:+ contents: read+ strategy:+ fail-fast: false+ matrix:+ include:+ - python: '3.13'+ distribution: wheel+ - python: '3.14'+ distribution: wheel+ - python: '3.12'+ distribution: sdist+ steps:+ - name: Harden runner+ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1+ with:+ egress-policy: audit+ - name: Checkout verification scripts+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - name: Set up Python+ uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: ${{ matrix.python }}+ - name: Download tested distributions+ uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1+ with:+ artifact-ids: ${{ needs.pip-install-check.outputs.artifact_id }}+ merge-multiple: true+ - name: Verify distribution hashes+ env:+ RELEASE_SHA: ${{ github.sha }}+ RELEASE_RUN_ID: ${{ github.run_id }}+ MANIFEST_SHA256: ${{ needs.pip-install-check.outputs.manifest_sha256 }}+ run: python .github/scripts/release_package.py verify+ - name: Install SQLCipher build dependencies+ run: |+ sudo apt-get update+ sudo apt-get install -y libsqlcipher-dev+ - name: Install distribution with fresh pip resolution+ env:+ DISTRIBUTION: ${{ matrix.distribution }}+ run: |+ python -m venv /tmp/package-install-env+ . /tmp/package-install-env/bin/activate+ if [ "$DISTRIBUTION" = "wheel" ]; then+ PACKAGE=(dist/*.whl)+ else+ PACKAGE=(dist/*.tar.gz)+ fi+ pip install --no-cache-dir "${PACKAGE[0]}"+ pip check+ # Run outside the checkout so only the installed package is tested.+ cd /tmp+ python - <<'PYCODE'+ import importlib.resources as resources+ import local_deep_research+ assets = resources.files("local_deep_research").joinpath("web/static/dist")+ assert assets.joinpath(".vite/manifest.json").is_file(), "missing installed frontend manifest"+ print(f"Installed v{local_deep_research.__version__} with frontend assets")+ PYCODE+# ============================================# CPU baseline smoke test under qemu-emulated CPUs#@@ -796,6 +909,7 @@ jobs:# comments for the v1.4.0 incident. Removing this dependency silently# allows broken wheels to be published to PyPI.- pip-install-check+ - package-install-matrix# CPU baseline smoke — catches dependency wheels that raise the# x86 instruction-set baseline and SIGILL on older CPUs (#4480)- cpu-baseline-smoke@@ -858,6 +972,7 @@ jobs:check_result "${{ needs.journal-data-integration.result }}" || true# CRITICAL — DO NOT REMOVE: without this line, broken wheels pass the gatecheck_result "${{ needs.pip-install-check.result }}" || true+ check_result "${{ needs.package-install-matrix.result }}" || truecheck_result "${{ needs.cpu-baseline-smoke.result }}" || truecheck_result "${{ needs.check-code-scanning-alerts.result }}" || true@@ -1115,6 +1230,13 @@ jobs:FAILED="true"fi+ if [ "${{ needs.package-install-matrix.result }}" = "success" ]; then+ echo "✅ **Package install matrix**: Passed — supported Python versions and sdist"+ else+ echo "❌ **Package install matrix**: ${{ needs.package-install-matrix.result }}"+ FAILED="true"+ fi+# ============================================# CPU baseline smoke (qemu)# Catches dependency wheels compiled past the supported x86diff --git a/.github/workflows/release-package-tests.yml b/.github/workflows/release-package-tests.ymlnew file mode 100644index 0000000000..a76341d4ad--- /dev/null+++ b/.github/workflows/release-package-tests.yml@@ -0,0 +1,35 @@+name: Release Package Tests++on:+ pull_request:+ paths:+ - ".github/workflows/release-package-tests.yml"+ - ".github/workflows/release-gate.yml"+ - ".github/workflows/release.yml"+ - ".github/workflows/publish.yml"+ - ".github/scripts/release_package.py"+ - "tests/ci/standalone/test_release_package.py"+ workflow_dispatch:++permissions:+ contents: read++jobs:+ policy-tests:+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - name: Harden runner+ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1+ with:+ egress-policy: audit+ - name: Checkout+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - name: Set up Python+ uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: '3.12'+ - name: Test CI policies without loading the application+ run: python -m unittest discover -s tests/ci/standalone -p 'test_release_package*.py' -vdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex f2ad1ce567..75133f39d3 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -258,6 +258,7 @@ jobs:contents: readpull-requests: readid-token: write # Required for cosign keyless signing with GitHub OIDC+ attestations: write # Attest the tested Python artifacts at the release SHAsteps:- name: Harden the runner (Audit all outbound calls)@@ -277,8 +278,23 @@ jobs:# a feature-branch commit, or a manual dispatch from a stale branch,# would otherwise sail through every gate. `fetch-depth: 0` above# makes origin/main reachable for the merge-base check.+ #+ # publish.yml accepts a source run only when its head_branch (the+ # ref name) is `main` or the release tag. This guard refuses a+ # manual dispatch from anything that isn't `main` or shaped like a+ # version tag (v*.*.*, an unquoted glob that also lets through refs+ # like v1.2.3-evil); the "Determine version" step below requires the+ # exact `v$VERSION` tag before Docker is promoted for a release that+ # PyPI would reject.+ env:+ EVENT_NAME: ${{ github.event_name }}+ REF_NAME: ${{ github.ref_name }}run: |set -euo pipefail+ if [[ "$EVENT_NAME" == "workflow_dispatch" && "$REF_NAME" != "main" && "$REF_NAME" != v*.*.* ]]; then+ echo "::error::workflow_dispatch from '$REF_NAME' — run it from main or a version tag"+ exit 1+ fiif ! git merge-base --is-ancestor "$GITHUB_SHA" origin/main; thenecho "::error::Build commit $GITHUB_SHA is not an ancestor of origin/main — refusing to release"exit 1@@ -290,6 +306,7 @@ jobs:env:EVENT_NAME: ${{ github.event_name }}GIT_REF: ${{ github.ref }}+ REF_NAME: ${{ github.ref_name }}run: |if [[ "$EVENT_NAME" = "push" && "$GIT_REF" =~ ^refs/tags/ ]]; then# Extract version from tag (remove 'v' prefix)@@ -298,6 +315,12 @@ jobs:# Get version from __version__.py (main branch push or manual trigger)VERSION=$(grep -oP '(?<=__version__ = ")[^"]*' src/local_deep_research/__version__.py)fi+ # A dispatch from a tag must name the release it builds: publish.yml+ # requires head_branch to be `main` or exactly this release tag.+ if [[ "$EVENT_NAME" = "workflow_dispatch" && "$REF_NAME" != "main" && "$REF_NAME" != "v$VERSION" ]]; then+ echo "::error::workflow_dispatch from '$REF_NAME' builds v$VERSION; publish.yml would reject this source ref"+ exit 1+ fiecho "version=$VERSION" >> "$GITHUB_OUTPUT"echo "tag=v$VERSION" >> "$GITHUB_OUTPUT"SHORT_SHA="${GITHUB_SHA:0:7}"@@ -331,6 +354,30 @@ jobs:fiecho "Version verified: $EXPECTED_VERSION"+ - name: Download tested Python distributions+ if: steps.check_release.outputs.exists == 'false'+ uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1+ with:+ artifact-ids: ${{ needs.release-gate.outputs.package_artifact_id }}+ merge-multiple: true+ path: ${{ runner.temp }}/tested-python/++ - name: Verify Python artifacts before attestation+ if: steps.check_release.outputs.exists == 'false'+ working-directory: ${{ runner.temp }}/tested-python+ env:+ RELEASE_SHA: ${{ github.sha }}+ RELEASE_RUN_ID: ${{ github.run_id }}+ RELEASE_TAG: ${{ steps.version.outputs.tag }}+ MANIFEST_SHA256: ${{ needs.release-gate.outputs.package_manifest_sha256 }}+ run: python3 "$GITHUB_WORKSPACE/.github/scripts/release_package.py" verify++ - name: Attest tested Python artifacts at the release commit+ if: steps.check_release.outputs.exists == 'false'+ uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2+ with:+ subject-path: '${{ runner.temp }}/tested-python/dist/*'+# SBOM generation uses the SHA-pinned trivy-action with an explicit# binary version pin. Previously this step shelled out# `apt-get install -y trivy` from the (unpinned) Aqua apt repo, which@@ -1498,7 +1545,7 @@ jobs:# publish.yml would fail with `invalid-publisher`. Tracked in# pypa/gh-action-pypi-publish#166 and pypi/warehouse#11096.trigger-pypi:- needs: [build, prerelease-docker, publish-docker]+ needs: [build, release-gate, prerelease-docker, publish-docker]if: ${{ !cancelled() && needs.prerelease-docker.result == 'success' && needs.publish-docker.result == 'success' && needs.build.outputs.release_exists == 'false' }}runs-on: ubuntu-latestenvironment: release@@ -1506,6 +1553,7 @@ jobs:contents: readoutputs:dispatch_time: ${{ steps.dispatch-time.outputs.timestamp }}+ publish_title: PyPI release ${{ github.run_id }} artifact ${{ needs.release-gate.outputs.package_artifact_id }}steps:- name: Harden the runner (Audit all outbound calls)@@ -1524,6 +1572,8 @@ jobs:env:RELEASE_TAG: ${{ needs.build.outputs.tag }}RELEASE_SHA: ${{ github.sha }}+ PACKAGE_ARTIFACT_ID: ${{ needs.release-gate.outputs.package_artifact_id }}+ PACKAGE_MANIFEST_SHA256: ${{ needs.release-gate.outputs.package_manifest_sha256 }}with:# PAT_TOKEN: repository_dispatch from a workflow run cannot be# fired with GITHUB_TOKEN — the API rejects it to prevent@@ -1540,15 +1590,11 @@ jobs:// dispatch — true prereleases (if added later) would need a// separate trigger path that flips this flag.//- // `sha` pins publish.yml's checkout to the release commit.- // repository_dispatch runs on default-branch HEAD *at dispatch- // time*, and the `release` env approval is human-paced — on- // v1.9.0 the approval came ~30h after the release commit, so- // publish.yml built from a HEAD that was 4 PRs ahead of the- // tag: PyPI 1.9.0 contains code that is not in the v1.9.0- // tag, Docker image, or release notes. The SHA (not the tag)- // must be passed because create-release creates the git tag- // only AFTER PyPI succeeds — the tag does not exist yet here.+ // Forward the immutable artifact tested by this release run.+ if (!/^[1-9][0-9]*$/.test(process.env.PACKAGE_ARTIFACT_ID || '') ||+ !/^[0-9a-f]{64}$/.test(process.env.PACKAGE_MANIFEST_SHA256 || '')) {+ throw new Error('Release gate did not return verified package outputs');+ }await github.rest.repos.createDispatchEvent({owner: context.repo.owner,repo: context.repo.repo,@@ -1556,6 +1602,9 @@ jobs:client_payload: {tag: process.env.RELEASE_TAG,sha: process.env.RELEASE_SHA,+ run_id: String(context.runId),+ artifact_id: process.env.PACKAGE_ARTIFACT_ID,+ manifest_sha256: process.env.PACKAGE_MANIFEST_SHA256,prerelease: false}});@@ -1570,7 +1619,11 @@ jobs:needs: [build, trigger-pypi]if: ${{ !cancelled() && needs.trigger-pypi.result == 'success' }}runs-on: ubuntu-latest- timeout-minutes: 90+ # Must exceed the inner wall-clock poll budget (max_wait below) plus+ # the initial 30s sleep and the worst-case last poll (one gh+jq call+ # started just before the budget ends, then its 30s sleep): 7200s+ # against 6300 + 30 + 30s leaves about 14 minutes of headroom.+ timeout-minutes: 120permissions:contents: readactions: read # Required for gh run list@@ -1593,23 +1646,36 @@ jobs:GH_REPO: ${{ github.repository }}RELEASE_TAG: ${{ needs.build.outputs.tag }}DISPATCH_TIME: ${{ needs.trigger-pypi.outputs.dispatch_time }}+ PUBLISH_TITLE: ${{ needs.trigger-pypi.outputs.publish_title }}run: |# pipefail is essential here: the poll loop pipes `gh run list`# into `jq`, and without pipefail a transient `gh` failure# (network, auth, rate limit) is swallowed by `jq` returning# empty input, causing the loop to spin silently for the full- # 40-minute budget rather than surfacing the error immediately.+ # poll budget rather than surfacing the error immediately.set -euo pipefailecho "Monitoring publish.yml for tag $RELEASE_TAG (dispatched at $DISPATCH_TIME)..."# Wait for the dispatched run to start (repository_dispatch is async)sleep 30- max_wait=2400 # 40 minutes- elapsed=0+ # 105 minutes. publish.yml's automated worst case is about 45+ # minutes (build-package 10 + upload + verify-publish 30, whose+ # PyPI hash lookup alone can take about 15). The rest is an+ # allowance for approving publish.yml's `release` environment,+ # so a slow PyPI index cannot produce a false "timed_out" that+ # opens a failure issue and skips create-release.+ #+ # The budget is wall-clock time (bash $SECONDS), not a sum of the+ # sleeps: each `gh run list | jq` poll takes a few seconds, and+ # over ~200 polls that would push the loop past the job's+ # timeout-minutes, which cancels the job before the failure-issue+ # step below can run.+ max_wait=6300+ start=$SECONDSconclusion=""- while [ "$elapsed" -lt "$max_wait" ]; do+ while [ $((SECONDS - start)) -lt "$max_wait" ]; do# Compare timestamps numerically — lexicographic comparison# breaks when GitHub returns sub-second precision (e.g.# "...:56.500Z" sorts before "...:56Z"). fromdateiso8601@@ -1617,17 +1683,16 @@ jobs:# 60s buffer tolerates minor clock skew between the runner and# GitHub's API. Stderr is intentionally NOT redirected so gh# failures stay visible in the runner log.- run=$(gh run list --workflow=publish.yml --limit=20 --json status,conclusion,createdAt \- | jq -r --arg since "$DISPATCH_TIME" '+ run=$(gh run list --workflow=publish.yml --limit=20 --json status,conclusion,createdAt,displayTitle \+ | jq -r --arg since "$DISPATCH_TIME" --arg title "$PUBLISH_TITLE" 'def to_epoch: sub("\\.[0-9]+Z$"; "Z") | fromdateiso8601;(($since | to_epoch) - 60) as $s- | [.[] | select((.createdAt | to_epoch) >= $s)] | .[0]+ | [.[] | select(.displayTitle == $title and (.createdAt | to_epoch) >= $s)] | .[0]')if [ "$run" = "null" ] || [ -z "$run" ]; thenecho "publish.yml: waiting for run to appear..." >&2sleep 30- elapsed=$((elapsed + 30))continuefi@@ -1640,7 +1705,6 @@ jobs:fisleep 30- elapsed=$((elapsed + 30))doneif [ -z "$conclusion" ]; then@@ -1674,23 +1738,11 @@ jobs:const pypi = process.env.PYPI_RESULT || 'unknown';const title = `PyPI publish failure for ${tag}`;- // publish.yml fails closed without a full 40-hex client_payload.sha- // (the pinned release commit — NOT main HEAD, which may have moved- // during the approval wait). Embed the exact ready-to-paste- // re-dispatch command so an on-call maintainer under incident- // pressure cannot follow a stale two-field payload shape.- const redispatch = '```\ngh api repos/' + owner + '/' + repo + '/dispatches \\\n'- + " -f event_type=publish-pypi \\\n"- + " -F 'client_payload[tag]=" + tag + "' \\\n"- + " -F 'client_payload[sha]=" + context.sha + "'\n```";- const action = pypi === 'timed_out'- ? '**Suggested action:** publish.yml did not complete within 40 minutes. Check the [Actions tab](https://github.com/' + owner + '/' + repo + '/actions)'- + ' — if the run never appeared, this likely indicates a dispatch issue; re-trigger with:\n' + redispatch- + '\nIf still running, no action may be needed.'- : '**Suggested action:** Inspect publish.yml logs in the [Actions tab](https://github.com/' + owner + '/' + repo + '/actions), fix the underlying cause,'- + ' then either (a) re-dispatch publish.yml with:\n' + redispatch- + '\nand re-run release.yml to complete create-release, or (b) manually publish the GitHub Release if Docker promote also succeeded.'- + ' See docs/RELEASE_GUIDE.md "Recovery from PyPI failure".';+ const action = '**Suggested action:** Inspect the matching publish.yml run in the [Actions tab](https://github.com/' + owner + '/' + repo + '/actions).'+ + ' Re-run failed publisher jobs to preserve the original tested artifact and dispatch payload.'+ + ' If no publisher run exists, re-run the failed release jobs to dispatch it.'+ + ' Expired artifacts require a fresh release gate run; do not rebuild in the publisher.'+ + ' See docs/RELEASE_GUIDE.md "Recovery from PyPI failure".';const body = `## PyPI publish failed for ${tag}\n\nResult: \`${pypi}\`\n\nNote: At this point in the atomicity flow, Docker promote (publish-docker job) has already succeeded — the Docker release tags exist and are signed. Only PyPI and the GitHub Release are missing.\n\n${action}`;diff --git a/docs/RELEASE_GUIDE.md b/docs/RELEASE_GUIDE.mdindex 53a14025a3..05c2dd6bf0 100644--- a/docs/RELEASE_GUIDE.md+++ b/docs/RELEASE_GUIDE.md@@ -65,13 +65,22 @@ order:2. `publish-docker` — retags the prerelease manifest as `:1.6.9`,`:1.6`, `:latest` (no rebuild, digest-preserving), then re-verifiesdigest + cosign + Trivy on the promoted tag.- 3. `trigger-pypi` — dispatches `publish.yml` via `repository_dispatch`+ 3. `trigger-pypi` — dispatches `publish.yml` with the release run ID,+ immutable package artifact ID, commit SHA and manifest digest. The+ gate builds the wheel and sdist once, records their hashes before+ anything installs or imports them (and re-checks them after the smoke+ tests), verifies wheel installation on Python 3.12–3.14 and sdist+ installation on 3.12, and retains the tested artifacts for 14 days. Publishing verifies and uploads those bytes+ via `repository_dispatch`(PyPI Trusted Publishing requires the publish step to run in atop-level workflow, so this can't be a reusable workflow_call).4. `monitor-pypi` — polls `publish.yml` for completion. The inner- polling loop times out at 40 minutes (after which the job fails);- the surrounding GH Actions `timeout-minutes` is 90 to leave a- safety margin around the poll budget.+ polling loop times out after 105 minutes of wall-clock time (after+ which the job fails): about 45 minutes of automated worst case in+ `publish.yml` (including the 30-minute `verify-publish` window) plus+ an allowance for approving its `release` environment. The+ surrounding GH Actions `timeout-minutes` is 120 to leave a safety+ margin around the poll budget.5. `create-release` — publishes the GitHub Release withSBOM/sig/provenance assets. Runs **last**, gated on all of theabove succeeding, so the public Release never points at missing@@ -99,17 +108,14 @@ succeeded, PyPI failed. At this point Docker `:1.6.9` / `:1.6` /`monitor-pypi` opens a tracking issue labeled `ci-cd`. To recover:1. Inspect the `publish.yml` workflow run, fix the underlying cause.-2. Manually re-dispatch PyPI publish. `client_payload[sha]` is REQUIRED- (publish.yml fails closed without it) and must be the full 40-hex- release commit — the commit the failed `release.yml` run built, NOT- current main HEAD (main may have moved during the approval wait).- Get it with `gh run view <release-run-id> --json headSha`:- ```bash- gh api repos/LearningCircuit/local-deep-research/dispatches \- -f event_type=publish-pypi \- -F 'client_payload[tag]=v<X.Y.Z>' \- -F 'client_payload[sha]=<40-hex release commit>'- ```+2. Re-run failed jobs in the matching `publish.yml` run. Its title names+ the source release run and immutable artifact ID. Re-running preserves+ the original dispatch payload and tested distributions. If no publisher+ run was created, re-run the failed release jobs to dispatch it.+ An expired or deleted package artifact requires a fresh release gate run+ to build and verify new artifacts before dispatching again. The publisher+ deliberately has no build step. A dispatch containing only a tag and SHA+ is insufficient: the run ID, artifact ID and manifest SHA256 are required.3. Once PyPI publishes successfully, manually create the GitHub Releasefrom the existing tag (the SBOM/sig/provenance artifacts are stilluploaded as workflow artifacts on the failed `release.yml` run; you@@ -175,6 +181,9 @@ with auto-notes plus AI summary only).- No inputs are required: the workflow reads the version from`src/local_deep_research/__version__.py` at HEAD. To release anolder or different version, use Option B (push a version tag).+- Dispatch from `main`, or from the `v<version>` tag that matches+ `__version__.py` at that tag. The build job refuses any other ref,+ because `publish.yml` would reject its source run.### Option B: Version Tags- `git tag v0.4.3 && git push origin v0.4.3`diff --git a/docs/ci/workflow-status.md b/docs/ci/workflow-status.mdindex 4af25746a1..7de07cccc8 100644--- a/docs/ci/workflow-status.md+++ b/docs/ci/workflow-status.md@@ -29,18 +29,19 @@<!-- BEGIN GENERATED -->-**71 workflows:** 1 disabled · 3 stale · 1 manual-only · 66 active+**72 workflows:** 1 disabled · 4 stale · 1 manual-only · 66 active## ⚠ Disabled workflows| Workflow | Disabled where | Last direct run ||---|---|---|-| `nuclei.yml` | `release-gate.yml:195` (commented) | never |+| `nuclei.yml` | `release-gate.yml:202` (commented) | never |## ⚠ Stale (scheduled but no recent successful run)| Workflow | Cron | Last successful run ||---|---|---|+| `osv-scanner.yml` | `39 12 * * 1` | never || `puppeteer-e2e-tests.yml` | `0 2 * * 0` | never || `release-gate.yml` | `0 2 * * *` | never || `update-precommit-hooks.yml` | `0 8 * * 5` | never |@@ -106,7 +107,6 @@| `gitleaks.yml` | last 30 days | PR, manual, schedule(0 3 * * *) | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/gitleaks.yml?query=event%3Aschedule) || `ossf-scorecard.yml` | last 30 days | branch_protection_rule, schedule(0 8 * * 1), manual, push:main | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/ossf-scorecard.yml?query=event%3Aschedule) || `osv-scanner-scheduled.yml` | last 30 days | push:main, schedule(41 21 * * 1), manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/osv-scanner-scheduled.yml?query=event%3Aschedule) |-| `osv-scanner.yml` | last 30 days | PR, merge_group, schedule(39 12 * * 1), manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/osv-scanner.yml?query=event%3Aschedule) || `sbom.yml` | last 30 days | manual, schedule(0 10 * * 3), release | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/sbom.yml?query=event%3Aschedule) || `security-mxss-browser-tests.yml` | last 30 days | PR, manual, schedule(30 2 * * *) | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/security-mxss-browser-tests.yml?query=event%3Aschedule) || `update-dependencies.yml` | last 30 days | workflow_call, manual, schedule(0 8 * * 3) | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/update-dependencies.yml?query=event%3Aschedule) |@@ -129,6 +129,7 @@| `mcp-tests.yml` | last 30 days | push:main, PR, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/mcp-tests.yml) || `milvus-tests.yml` | last 30 days | push:main, PR, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/milvus-tests.yml) || `pr-triage.yml` | last 30 days | PR, pull_request_review | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/pr-triage.yml) |+| `release-package-tests.yml` | last 30 days | PR, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/release-package-tests.yml) || `release.yml` | last 30 days | push:main, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/release.yml) || `ui-full-shards.yml` | last 30 days | PR, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/ui-full-shards.yml) || `version_check.yml` | last 30 days | push:main, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/version_check.yml) |diff --git a/tests/ci/standalone/test_release_package.py b/tests/ci/standalone/test_release_package.pynew file mode 100644index 0000000000..595d813d98--- /dev/null+++ b/tests/ci/standalone/test_release_package.py@@ -0,0 +1,457 @@+"""Standalone tests for release artifact identity and source-run validation."""++# allow: no-sut-import — imports the standalone CI script directly.++import copy+import http.client+import importlib.util+import io+import json+import tarfile+import tempfile+import unittest+import unittest.mock+import urllib.error+import zipfile+from pathlib import Path++ROOT = Path(__file__).resolve().parents[3]+SPEC = importlib.util.spec_from_file_location(+ "release_package", ROOT / ".github/scripts/release_package.py"+)+POLICY = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(POLICY)+SHA = "a" * 40+++class PackageTests(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ self.addCleanup(self.temp.cleanup)+ self.directory = Path(self.temp.name) / "dist"+ self.directory.mkdir()+ self.wheel = (+ self.directory / "local_deep_research-1.2.3-py3-none-any.whl"+ )+ self.sdist = self.directory / "local_deep_research-1.2.3.tar.gz"+ self.build()+ self.data = POLICY.manifest(self.directory, SHA, "123", "1")+ self.path = Path(self.temp.name) / "manifest.json"+ self.path.write_text(json.dumps(self.data))+ self.hash = POLICY.digest(self.path)++ def build(+ self, wheel_version="1.2.3", sdist_version="1.2.3", frontend=True+ ):+ with zipfile.ZipFile(self.wheel, "w") as archive:+ archive.writestr(+ "local_deep_research-1.2.3.dist-info/METADATA",+ f"Name: local-deep-research\nVersion: {wheel_version}\n",+ )+ if frontend:+ for name in (+ ".vite/manifest.json",+ "assets/app.js",+ "assets/app.css",+ ):+ archive.writestr(+ "local_deep_research/web/static/dist/" + name, "{}"+ )+ data = f"Name: local-deep-research\nVersion: {sdist_version}\n".encode()+ with tarfile.open(self.sdist, "w:gz") as archive:+ member = tarfile.TarInfo("local_deep_research-1.2.3/PKG-INFO")+ member.size = len(data)+ archive.addfile(member, io.BytesIO(data))++ def verify(self, **kwargs):+ args = dict(+ expected_hash=self.hash,+ sha=SHA,+ run_id="123",+ attempt="1",+ tag="v1.2.3",+ )+ args.update(kwargs)+ return POLICY.verify(self.directory, self.path, **args)++ def test_clean_artifact_and_rerun_preserved_attempt(self):+ self.assertEqual(self.verify(), self.data)+ self.assertEqual(self.verify(attempt=None), self.data)++ def test_changed_artifact_and_manifest_fail(self):+ with zipfile.ZipFile(self.wheel, "a") as archive:+ archive.writestr("changed.py", "value = 1")+ with self.assertRaisesRegex(ValueError, "hashes"):+ self.verify()+ self.path.write_text("{}")+ with self.assertRaisesRegex(ValueError, "digest"):+ self.verify()++ def test_identity_and_version_mismatch_fail(self):+ for args in (+ {"sha": "b" * 40},+ {"run_id": "124"},+ {"attempt": "2"},+ {"tag": "v9.9.9"},+ {"expected_hash": "0" * 64},+ ):+ with self.subTest(args=args), self.assertRaises(ValueError):+ self.verify(**args)++ def test_tag_matches_the_normalized_package_version(self):+ self.wheel.unlink()+ self.sdist.unlink()+ self.build(wheel_version="1.2.0rc1", sdist_version="1.2.0rc1")+ self.data = POLICY.manifest(self.directory, SHA, "123", "1")+ self.path.write_text(json.dumps(self.data))+ self.hash = POLICY.digest(self.path)+ for tag in ("v1.2.0-rc1", "v1.2.0rc1", "v1.2.0.RC1", "v1.2.0c1"):+ with self.subTest(tag=tag):+ self.assertEqual(self.verify(tag=tag), self.data)+ for tag in ("v1.2.0", "v1.2.0rc2", "1.2.0rc1", "v1.2.0-rc1-x"):+ with self.subTest(tag=tag), self.assertRaises(ValueError):+ self.verify(tag=tag)++ def test_version_normalization_matches_pep_440(self):+ cases = {+ "1.2.0-rc1": "1.2.0rc1",+ "1.2.0_RC_1": "1.2.0rc1",+ "1.0alpha": "1.0a0",+ "1.0-beta.2": "1.0b2",+ "1.0pre3": "1.0rc3",+ "01.02.03": "1.2.3",+ "1.0-1": "1.0.post1",+ "1.0.rev2": "1.0.post2",+ "1.0-dev": "1.0.dev0",+ "1.0rc1.post2.dev3": "1.0rc1.post2.dev3",+ "0!1.0": "1.0",+ "2!1.0+Local-01_x": "2!1.0+local.1.x",+ "v1.10.7": "1.10.7",+ }+ for raw, normal in cases.items():+ with self.subTest(raw=raw):+ self.assertEqual(POLICY.normalize_version(raw), normal)+ for raw in ("1.2.0-", "rc1", "1..2", "1.0+"):+ with self.subTest(raw=raw), self.assertRaises(ValueError):+ POLICY.normalize_version(raw)++ def test_distribution_set_and_links_fail(self):+ extra = self.directory / "extra.txt"+ extra.write_text("unexpected")+ with self.assertRaises(ValueError):+ self.verify()+ extra.unlink()+ self.sdist.unlink()+ self.sdist.symlink_to(self.wheel)+ with self.assertRaises(ValueError):+ self.verify()++ def test_frontend_and_matching_package_metadata_are_required(self):+ for args in ({"frontend": False}, {"sdist_version": "2.0.0"}):+ with self.subTest(args=args), self.assertRaises(ValueError):+ self.build(**args)+ POLICY.manifest(self.directory, SHA, "123", "1")++ def test_each_built_frontend_asset_is_required(self):+ prefix = "local_deep_research/web/static/dist/"+ for missing in (+ ".vite/manifest.json",+ "assets/app.js",+ "assets/app.css",+ ):+ self.build()+ with zipfile.ZipFile(self.wheel) as archive:+ entries = {+ name: archive.read(name)+ for name in archive.namelist()+ if name != prefix + missing+ }+ with zipfile.ZipFile(self.wheel, "w") as archive:+ for name, data in entries.items():+ archive.writestr(name, data)+ with (+ self.subTest(missing=missing),+ self.assertRaisesRegex(ValueError, "frontend"),+ ):+ POLICY.manifest(self.directory, SHA, "123", "1")++ def test_identifiers_reject_newlines_and_partial_values(self):+ for sha, run_id, attempt in (+ (SHA + "\n", "123", "1"),+ (SHA[:8], "123", "1"),+ (SHA, "../1", "1"),+ (SHA, "123", "0"),+ ):+ with (+ self.subTest(sha=sha, run_id=run_id, attempt=attempt),+ self.assertRaises(ValueError),+ ):+ POLICY.manifest(self.directory, sha, run_id, attempt)+++class PublishedTests(unittest.TestCase):+ def test_existing_files_must_match_tested_hashes(self):+ expected = {"package.whl": "a" * 64, "package.tar.gz": "b" * 64}+ response = {+ "urls": [+ {"filename": name, "digests": {"sha256": value}}+ for name, value in expected.items()+ ]+ }+ POLICY.check_published_hashes(expected, response)+ response["urls"][0]["digests"]["sha256"] = "c" * 64+ with self.assertRaisesRegex(ValueError, "differ"):+ POLICY.check_published_hashes(expected, response)+ with self.assertRaises(ValueError):+ POLICY.check_published_hashes(expected, {"urls": []})+++class PublishedRetryTests(unittest.TestCase):+ expected = {"package.whl": "a" * 64, "package.tar.gz": "b" * 64}++ def setUp(self):+ patcher = unittest.mock.patch.dict(+ "os.environ",+ {+ "PACKAGE_VERSION": "1.2.3",+ "EXPECTED_HASHES": json.dumps(self.expected),+ },+ )+ patcher.start()+ self.addCleanup(patcher.stop)+ self.sleeps = []++ def opener(self, responses):+ def open_url(url, timeout):+ self.assertEqual(+ url, "https://pypi.org/pypi/local-deep-research/1.2.3/json"+ )+ response = responses.pop(0)+ if isinstance(response, Exception):+ raise response+ return io.BytesIO(json.dumps(response).encode())++ return open_url++ def published(self, hashes):+ return {+ "urls": [+ {"filename": name, "digests": {"sha256": value}}+ for name, value in hashes.items()+ ]+ }++ def test_default_schedule_sleeps_610_seconds(self):+ self.assertEqual(sum(POLICY.PUBLISHED_RETRY_DELAYS), 610)++ def test_slow_index_is_retried_with_backoff(self):+ responses = [+ urllib.error.URLError("unavailable"),+ TimeoutError("read timed out"),+ {"urls": []},+ self.published(self.expected),+ ]+ POLICY.verify_published(+ (1, 2, 3, 4), self.opener(responses), self.sleeps.append+ )+ self.assertEqual(self.sleeps, [1, 2, 3])+ self.assertEqual(responses, [])++ def test_truncated_response_is_retried(self):+ responses = [+ http.client.IncompleteRead(b"{", 10),+ http.client.RemoteDisconnected("closed"),+ self.published(self.expected),+ ]+ POLICY.verify_published(+ (1, 2), self.opener(responses), self.sleeps.append+ )+ self.assertEqual(self.sleeps, [1, 2])+ self.assertEqual(responses, [])++ def test_truncated_response_fails_cleanly_after_the_schedule(self):+ responses = [http.client.IncompleteRead(b"{", 10)] * 2+ # main() calls verify_published() with its bound defaults.+ defaults = ((1,), self.opener(responses), self.sleeps.append)+ with (+ unittest.mock.patch.object(+ POLICY.verify_published, "__defaults__", defaults+ ),+ unittest.mock.patch(+ "sys.argv", ["release_package.py", "published"]+ ),+ unittest.mock.patch("sys.stdout", io.StringIO()) as stdout,+ ):+ self.assertEqual(POLICY.main(), 1)+ self.assertEqual(self.sleeps, [1])+ self.assertEqual(responses, [])+ self.assertIn(+ "::error::Release package verification failed", stdout.getvalue()+ )++ def test_present_file_with_other_hash_fails_immediately(self):+ # PyPI files are immutable (skip-existing may leave foreign bytes),+ # so retrying a real mismatch only burns monitor-pypi's budget.+ wrong = self.published({**self.expected, "package.whl": "c" * 64})+ responses = [urllib.error.URLError("unavailable"), wrong, wrong]+ with self.assertRaises(POLICY.PublishedHashMismatch):+ POLICY.verify_published(+ (1, 2, 3), self.opener(responses), self.sleeps.append+ )+ self.assertEqual(self.sleeps, [1])+ self.assertEqual(responses, [wrong])++ def test_missing_files_and_not_found_are_retried(self):+ partial = self.published({"package.whl": "a" * 64})+ not_found = urllib.error.HTTPError(+ "https://pypi.org", 404, "Not Found", {}, None+ )+ responses = [not_found, partial, self.published(self.expected)]+ POLICY.verify_published(+ (1, 2), self.opener(responses), self.sleeps.append+ )+ self.assertEqual(self.sleeps, [1, 2])++ def test_incomplete_file_set_fails_after_the_schedule(self):+ partial = self.published({"package.whl": "a" * 64})+ with self.assertRaisesRegex(ValueError, "exactly"):+ POLICY.verify_published(+ (1, 2), self.opener([partial] * 3), self.sleeps.append+ )+ self.assertEqual(self.sleeps, [1, 2])++ def test_unnormalized_version_queries_the_normal_form(self):+ urls = []++ def open_url(url, timeout):+ urls.append(url)+ return io.BytesIO(+ json.dumps(self.published(self.expected)).encode()+ )++ with unittest.mock.patch.dict(+ "os.environ", {"PACKAGE_VERSION": "1.2.3-rc1"}+ ):+ POLICY.verify_published((), open_url, self.sleeps.append)+ self.assertEqual(+ urls, ["https://pypi.org/pypi/local-deep-research/1.2.3rc1/json"]+ )+++class SourceTests(unittest.TestCase):+ def setUp(self):+ self.payload = {+ "sha": SHA,+ "run_id": "123",+ "artifact_id": "456",+ "manifest_sha256": "b" * 64,+ "tag": "v1.2.3",+ }+ self.run = {+ "repository": {"full_name": "owner/repo"},+ "path": ".github/workflows/release.yml",+ "head_sha": SHA,+ "event": "push",+ "head_branch": "main",+ "status": "in_progress",+ }+ self.jobs = [+ {+ "id": i,+ "name": name,+ "status": "completed",+ "conclusion": "success",+ }+ for i, name in enumerate(+ ("release-gate / Release Gate Summary", "build"), 1+ )+ ]+ self.artifact = {+ "id": 456,+ "name": "verified-python-dist-1",+ "expired": False,+ "workflow_run": {"id": 123, "head_sha": SHA},+ }+ self.ancestry = "ahead"+ self.calls = []++ def fetch(self, endpoint):+ self.calls.append(endpoint)+ if "/jobs?" in endpoint:+ return {"jobs": self.jobs}+ if "/artifacts/" in endpoint:+ return self.artifact+ if "/compare/" in endpoint:+ return {"status": self.ancestry}+ return self.run++ def validate(self):+ return POLICY.validate_source("owner/repo", self.payload, self.fetch)++ def test_in_progress_release_with_successful_gates_is_valid(self):+ self.assertEqual(self.validate(), "1")+ self.assertTrue(+ any("/artifacts/456" in endpoint for endpoint in self.calls)+ )++ def test_wrong_workflow_commit_event_and_repository_fail(self):+ original = copy.deepcopy(self.run)+ for changes in (+ {"path": ".github/workflows/other.yml"},+ {"head_sha": "c" * 40},+ {"event": "pull_request"},+ {"repository": {"full_name": "another/repo"}},+ {"head_branch": "feature"},+ {"head_branch": "v9.9.9"},+ {"head_branch": None},+ ):+ self.run = {**original, **changes}+ with self.subTest(changes=changes), self.assertRaises(ValueError):+ self.validate()++ def test_main_and_release_tag_sources_are_valid(self):+ for head_branch in ("main", "v1.2.3"):+ self.run = {**self.run, "head_branch": head_branch}+ with self.subTest(head_branch=head_branch):+ self.assertEqual(self.validate(), "1")++ def test_failed_skipped_missing_and_superseded_gates_fail(self):+ original = copy.deepcopy(self.jobs)+ for state in ("failure", "skipped", "cancelled", None):+ self.jobs = copy.deepcopy(original)+ self.jobs[0]["conclusion"] = state+ with self.subTest(state=state), self.assertRaises(ValueError):+ self.validate()+ self.jobs = []+ with self.assertRaises(ValueError):+ self.validate()+ self.jobs = original + [+ {**original[0], "id": 999, "conclusion": "failure"}+ ]+ with self.assertRaises(ValueError):+ self.validate()++ def test_artifact_ownership_and_expiration_are_required(self):+ original = copy.deepcopy(self.artifact)+ for changes in (+ {"expired": True},+ {"id": 789},+ {"name": "python-dist"},+ {"workflow_run": {"id": 789, "head_sha": SHA}},+ {"workflow_run": {"id": 123, "head_sha": "c" * 40}},+ ):+ self.artifact = {**original, **changes}+ with self.subTest(changes=changes), self.assertRaises(ValueError):+ self.validate()++ def test_unreviewed_commit_and_incomplete_payload_fail(self):+ self.ancestry = "diverged"+ with self.assertRaises(ValueError):+ self.validate()+ self.payload["sha"] += "\n"+ with self.assertRaises(ValueError):+ self.validate()+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/ci/test_package_artifact_policy.py b/tests/ci/test_package_artifact_policy.pyindex cd8628707b..cafe38e2f6 100644--- a/tests/ci/test_package_artifact_policy.py+++ b/tests/ci/test_package_artifact_policy.py@@ -6,7 +6,9 @@from __future__ import annotations+import copyimport io+import reimport statimport subprocessimport sys@@ -229,9 +231,385 @@ def test_real_release_builds_enforce_the_artifact_policy(runs = [step.get("run", "") for step in steps]commands = [line.strip() for run in runs for line in run.splitlines()]- assert "pdm build" in commandsassert "pdm build --no-sdist" not in commands- assert "python .github/scripts/package_artifact_policy.py dist/" in commands+ if workflow_path == RELEASE_GATE:+ assert "pdm build" in commands+ assert (+ "python .github/scripts/package_artifact_policy.py dist/"+ in commands+ )+ else:+ assert "pdm build" not in commands+ assert (+ "python .github/scripts/package_artifact_policy.py tested-package/dist/"+ in commands+ )+ assert any("release_package.py verify" in run for run in runs)+++RELEASE_WORKFLOW = REPO_ROOT / ".github" / "workflows" / "release.yml"+++def _console_scripts():+ config = tomllib.loads(PYPROJECT.read_text(encoding="utf-8"))+ return tuple(sorted(config["project"].get("scripts", {})))+++# A marker-list check: a step counts as running the built package (or its+# dependencies, or inspecting dist/ before the hashes are recorded) when its+# ``run`` contains any of these substrings. It is a tripwire for ordinary+# edits, not a shell parser; a new way of executing the package needs a new+# marker here.+_PACKAGE_EXECUTION_MARKERS = (+ "package_artifact_policy.py",+ "pip install",+ "pip3 install",+ "pdm install",+ "pdm sync",+ "uv run",+ "uv pip",+ "python -c",+ "python -",+ "python3 -c",+ "python3 -",+ "entry_points",+ "twine",+ "ldr ",+ *_console_scripts(),+)++_MANIFEST_OUTPUT = "${{ steps.package-manifest.outputs.manifest_sha256 }}"+++def _runs_package(run):+ return any(marker in run for marker in _PACKAGE_EXECUTION_MARKERS)+++def _upload_paths(step):+ path = (step.get("with") or {}).get("path", "")+ return [line.strip() for line in str(path).splitlines() if line.strip()]+++def _package_binding_violations(steps):+ """Return why ``steps`` could record or upload bytes that were not tested."""+ runs = [step.get("run", "") for step in steps]+ creates = [+ i for i, run in enumerate(runs) if "release_package.py create" in run+ ]+ if len(creates) != 1:+ return ["expected exactly one manifest create step"]+ create = creates[0]+ problems = []+ builds = [+ i+ for i, run in enumerate(runs)+ if "pdm build" in (line.strip() for line in run.splitlines())+ ]+ if not builds or builds[-1] > create:+ problems.append("manifest create step does not follow pdm build")+ executions = [i for i, run in enumerate(runs) if _runs_package(run)]+ problems += [+ f"step {i} ({steps[i].get('name')}) runs package code before create"+ for i in executions+ if i < create+ ]+ verifies = [+ i+ for i, run in enumerate(runs)+ if "release_package.py verify" in run+ and steps[i].get("env", {}).get("MANIFEST_SHA256") == _MANIFEST_OUTPUT+ ]+ for i in verifies:+ step = steps[i]+ if (+ "if" in step+ or step.get("continue-on-error") not in (None, False)+ or re.search(r"\|\|\s*(true|:)(\s|$)", runs[i])+ ):+ problems.append(+ f"verify step {i} ({step.get('name')}) can be skipped"+ )+ last_execution = max(executions, default=create)+ if not any(i > last_execution for i in verifies):+ problems.append("no hash verification after the package smoke tests")+ uploads = [+ i+ for i, step in enumerate(steps)+ if str(step.get("uses", "")).startswith("actions/upload-artifact@")+ ]+ if not uploads or not verifies or min(uploads) < max(verifies):+ problems.append("distributions are uploaded before re-verification")+ elif any(max(verifies) < i < min(uploads) for i in executions):+ problems.append("package code runs between verification and upload")+ problems += [+ f"upload step {i} ({steps[i].get('name')}) omits release-package.json"+ for i in uploads+ if "release-package.json" not in _upload_paths(steps[i])+ ]+ return problems+++def _step_index(steps, text):+ return next(+ i for i, step in enumerate(steps) if text in step.get("run", "")+ )+++def test_release_gate_records_hashes_before_running_the_package():+ workflow = yaml.safe_load(RELEASE_GATE.read_text(encoding="utf-8"))+ steps = workflow["jobs"]["pip-install-check"]["steps"]+ create = _step_index(steps, "release_package.py create")+ assert steps[create]["id"] == "package-manifest"++ assert _package_binding_violations(steps) == []+++def _mutants(steps):+ """Yield (label, steps, expected problem) for each rule of the check."""+ create = _step_index(steps, "release_package.py create")+ install = _step_index(steps, "pip install")+ verify = _step_index(steps, "release_package.py verify")+ upload = next(+ i+ for i, step in enumerate(steps)+ if str(step.get("uses", "")).startswith("actions/upload-artifact@")+ )++ late_create = copy.deepcopy(steps)+ late_create.insert(install + 1, late_create.pop(create))+ yield "create after install", late_create, "runs package code before"++ no_reverify = [s for i, s in enumerate(steps) if i != verify]+ yield "no re-verification", no_reverify, "no hash verification after"++ early_upload = copy.deepcopy(steps)+ early_upload.insert(verify, early_upload.pop(upload))+ yield "upload before verify", early_upload, "uploaded before re-verif"++ commands = (+ "pip3 install dist/*.whl",+ "pdm install",+ "pdm sync",+ "uv run pytest",+ "uv pip install dist/*.whl",+ "ldr --version",+ "python3 -c 'import local_deep_research'",+ "python3 - <<'PY'",+ *_console_scripts(),+ )+ for command in commands:+ early = copy.deepcopy(steps)+ early.insert(create, {"name": "early", "run": command})+ yield f"{command!r} before create", early, "runs package code before"++ between = copy.deepcopy(steps)+ between.insert(upload, {"name": "late", "run": command})+ yield (+ f"{command!r} between verify and upload",+ between,+ "runs between verification and upload",+ )++ for label, change in (+ ("continue-on-error", {"continue-on-error": True}),+ ("if condition", {"if": "success()"}),+ ("always condition", {"if": "${{ always() }}"}),+ ("|| true", {"run": steps[verify]["run"] + " || true"}),+ ("|| :", {"run": steps[verify]["run"] + " || :"}),+ ):+ skippable = copy.deepcopy(steps)+ skippable[verify].update(change)+ yield f"verify with {label}", skippable, "can be skipped"++ for label, path in (+ ("without release-package.json", "dist/\n"),+ ("naming the manifest in a comment", "dist/ # release-package.json\n"),+ ):+ no_manifest = copy.deepcopy(steps)+ no_manifest[upload]["with"]["path"] = path+ yield f"upload {label}", no_manifest, "omits release-package.json"+++def test_package_binding_check_rejects_every_mutant():+ """Each rule fires on its own mutant of the real job, with its own reason."""+ workflow = yaml.safe_load(RELEASE_GATE.read_text(encoding="utf-8"))+ steps = workflow["jobs"]["pip-install-check"]["steps"]+ missed = []+ for label, mutant, expected in _mutants(steps):+ problems = _package_binding_violations(mutant)+ if not any(expected in problem for problem in problems):+ missed.append((label, problems))++ assert missed == []+++def test_console_scripts_are_execution_markers():+ scripts = _console_scripts()++ assert scripts+ assert set(scripts) <= set(_PACKAGE_EXECUTION_MARKERS)+++def _dispatch_guard(step_name, env):+ """Run the workflow_dispatch refusal block of a release.yml build step."""+ workflow = yaml.safe_load(RELEASE_WORKFLOW.read_text(encoding="utf-8"))+ step = next(+ step+ for step in workflow["jobs"]["build"]["steps"]+ if step.get("name") == step_name+ )+ lines = step["run"].splitlines()+ start = next(+ i+ for i, line in enumerate(lines)+ if line.lstrip().startswith("if [[")+ and "workflow_dispatch" in line+ and "REF_NAME" in line+ )+ end = next(i for i in range(start, len(lines)) if lines[i].strip() == "fi")+ assert set(step["env"]) >= {"EVENT_NAME", "REF_NAME"}+ return subprocess.run(+ ["bash", "-c", "\n".join(lines[start : end + 1])],+ env={"PATH": "/usr/bin:/bin", **env},+ check=False,+ capture_output=True,+ text=True,+ timeout=30,+ ).returncode+++ ("event", "ref", "allowed"),+ [+ ("workflow_dispatch", "main", True),+ ("workflow_dispatch", "v1.2.3", True),+ ("workflow_dispatch", "feature/release-fix", False),+ ("workflow_dispatch", "v1.2", False),+ ("push", "main", True),+ ("push", "v1.2.3", True),+ ],+)+def test_release_refuses_dispatches_publish_would_reject(event, ref, allowed):+ """Mirror publish.yml's head_branch rule before Docker is promoted."""+ code = _dispatch_guard(+ "Verify build commit is on main",+ {"EVENT_NAME": event, "REF_NAME": ref},+ )++ assert (code == 0) is allowed+++ ("event", "ref", "allowed"),+ [+ ("workflow_dispatch", "main", True),+ ("workflow_dispatch", "v1.2.3", True),+ ("workflow_dispatch", "v1.2.4", False),+ # A prefix-match mutant (`!= v"$VERSION"*`) would wrongly accept+ # this: "v1.2.30" starts with "v1.2.3" but names a different+ # release than VERSION=1.2.3.+ ("workflow_dispatch", "v1.2.30", False),+ ("push", "main", True),+ ],+)+def test_release_dispatch_tag_must_name_the_built_version(event, ref, allowed):+ code = _dispatch_guard(+ "Determine version",+ {"EVENT_NAME": event, "REF_NAME": ref, "VERSION": "1.2.3"},+ )++ assert (code == 0) is allowed+++def test_release_dispatch_guard_runs_after_version_is_assigned():+ """The guard must see the real VERSION, not an unset/stale one."""+ workflow = yaml.safe_load(RELEASE_WORKFLOW.read_text(encoding="utf-8"))+ step = next(+ step+ for step in workflow["jobs"]["build"]["steps"]+ if step.get("name") == "Determine version"+ )+ lines = step["run"].splitlines()+ version_assign = next(+ i+ for i, line in enumerate(lines)+ if line.lstrip().startswith("VERSION=")+ )+ guard_if = next(+ i+ for i, line in enumerate(lines)+ if line.lstrip().startswith("if [[")+ and "workflow_dispatch" in line+ and "REF_NAME" in line+ )++ assert guard_if > version_assign+++def test_monitor_pypi_window_exceeds_the_publish_path():+ """A slow PyPI index must not look like a failed publish.++ monitor-pypi opens a failure issue and skips create-release when its+ poll budget runs out, so it has to outlast publish.yml's automated+ worst case with room left over for the ``release`` environment approval.+ """+ release = yaml.safe_load(RELEASE_WORKFLOW.read_text(encoding="utf-8"))+ publish = yaml.safe_load(PUBLISH_WORKFLOW.read_text(encoding="utf-8"))+ monitor = release["jobs"]["monitor-pypi"]+ run = next(+ step["run"]+ for step in monitor["steps"]+ if "max_wait=" in step.get("run", "")+ )+ max_wait = int(re.search(r"^\s*max_wait=(\d+)\s*$", run, re.M)[1])+ automated = sum(+ publish["jobs"][job]["timeout-minutes"] * 60+ for job in ("build-package", "verify-publish")+ )+ approval_allowance = 45 * 60++ assert max_wait >= automated + approval_allowance++ # The budget must be wall-clock time. A counter that only adds up the+ # sleeps ignores how long each ``gh run list | jq`` poll takes, so the+ # loop could outlive the job timeout (which cancels the failure-issue+ # step) before max_wait ran out.+ assert re.search(r"^\s*start=\$SECONDS\s*$", run, re.M)+ assert re.search(+ r'^\s*while \[ \$\(\(SECONDS - start\)\) -lt "\$max_wait" \]; do\s*$',+ run,+ re.M,+ )+ assert not re.search(r"elapsed=\$\(\(elapsed \+", run)++ # The job timeout must not cut the poll loop short: it has to cover the+ # initial sleep, the whole budget, and a last poll that starts just+ # before the budget ends (a slow gh call plus its 30s sleep), with room+ # left for the runner setup and the failure-issue step.+ initial_sleep = last_sleep = 30+ last_poll_allowance = 5 * 60+ setup_and_report_allowance = 5 * 60+ assert monitor["timeout-minutes"] * 60 >= (+ initial_sleep+ + max_wait+ + last_poll_allowance+ + last_sleep+ + setup_and_report_allowance+ )+++def test_release_gate_frontend_install_skips_dependency_scripts():+ workflow = yaml.safe_load(RELEASE_GATE.read_text(encoding="utf-8"))+ steps = workflow["jobs"]["pip-install-check"]["steps"]+ npm = [+ line.strip()+ for step in steps+ for line in step.get("run", "").splitlines()+ if line.strip().startswith("npm ci")+ ]++ assert npm+ assert all("--ignore-scripts" in line.split() for line in npm)@pytest.mark.parametrize("kind", ["wheel", "sdist"])diff --git a/tests/web/test_vite_asset_pipeline.py b/tests/web/test_vite_asset_pipeline.pyindex 68309b7781..b5bb2a92a5 100644--- a/tests/web/test_vite_asset_pipeline.py+++ b/tests/web/test_vite_asset_pipeline.py@@ -228,15 +228,21 @@ class TestReleasedInstallGetsDist:"git does not consider src/.../web/static/dist ignored")- def test_publish_builds_the_frontend_and_fails_closed_before_packaging(+ def test_release_builds_the_frontend_and_fails_closed_before_packaging(self,):- """publish.yml must not be able to build a wheel with no dist/."""- text = PUBLISH_WF.read_text(encoding="utf-8")+ """The gate builds the exact distributions later downloaded by publish.yml."""+ text = RELEASE_GATE_WF.read_text(encoding="utf-8")lines = text.splitlines()+ publish = PUBLISH_WF.read_text(encoding="utf-8")+ assert (+ "artifact-ids: ${{ github.event.client_payload.artifact_id }}"+ in publish+ )+ assert "pdm build" not in publishassert "npm run build" in text, (- "publish.yml no longer builds the frontend; a PyPI release would "+ "release-gate.yml no longer builds the frontend; a PyPI release would ""ship without static/dist")@@ -253,83 +259,34 @@ class TestReleasedInstallGetsDist:"Vite build would now flow into `pdm build` unnoticed")- dist_in_wheel = _shell_if_block(- lines,- lambda ln: (- "wheel_contents.txt" in ln- and "local_deep_research/web/static/dist/" in ln- and ".vite" not in ln- ),- )- assert any("exit 1" in ln for ln in dist_in_wheel), (- "the wheel is no longer required to contain static/dist"- )-- def test_wheel_gate_treats_a_manifest_missing_from_the_wheel_as_ok(self):- """DEFECT: the one check that would catch a manifest-less wheel warns.-- ``pdm-backend`` decides what lands in the wheel, and the manifest- lives in a DOT directory (``dist/.vite/``) while the JS and CSS do- not. So the exact packaging accident that is plausible -- hidden- directory dropped, bundles kept -- is the one the gate waves- through: the JS/CSS checks ``exit 1``, the manifest check prints- "may be okay". The resulting install renders the- ``_fallback_assets`` comment and no script tags at all (see- ``TestMissingOrBrokenManifest``).- """- lines = PUBLISH_WF.read_text(encoding="utf-8").splitlines()+ assert "python .github/scripts/release_package.py create" in text- manifest_in_wheel = _shell_if_block(- lines,- lambda ln: (- "wheel_contents.txt" in ln and "dist/.vite/manifest.json" in ln- ),- )- block = "\n".join(manifest_in_wheel)+ def test_publisher_verifies_the_tested_frontend_artifact(self):+ """The producer and publisher both enforce the frontend artifact contract.- assert "WARNING" in block and "may be okay" in block, (- "this test pins a KNOWN GAP; if the manifest check was made "- "fatal, delete this test and assert `exit 1` instead"- )- assert "exit 1" not in block, (- "manifest check is now fatal -- good; update this test"+ Real wheel fixtures exercise missing manifest, JS and CSS failures in+ tests/ci/standalone/test_release_package.py without loading the app.+ """+ text = PUBLISH_WF.read_text(encoding="utf-8")+ assert "release_package.py verify" in text+ assert (+ "EXPECTED_HASHES: ${{ needs.build-package.outputs.file_hashes }}"+ in text)+ assert "release_package.py published" in text+ assert "npm run build" not in text+ assert "pdm build" not in text- for var in ("JS_IN_WHEEL", "CSS_IN_WHEEL"):- fatal = _shell_if_block(- lines,- lambda ln, var=var: f'"${var}"' in ln and "-eq 0" in ln,- )- assert any("exit 1" in ln for ln in fatal), (- f"the {var} check stopped being fatal; a wheel with no "- "bundles could now ship"- )-- def test_release_gate_installs_the_wheel_without_inspecting_dist(self):- """The pre-release wheel gate cannot catch a manifest-less wheel.-- release-gate.yml is the job that builds a wheel and pip-installs- it into a clean venv -- the natural place to assert the shipped- package actually contains ``web/static/dist/.vite/manifest.json``.- It checks importability, dependency resolution and entry points,- and nothing about static assets.- """+ def test_release_gate_verifies_installed_frontend_assets(self):+ """Wheel and sdist installation must preserve the Vite manifest."""text = RELEASE_GATE_WF.read_text(encoding="utf-8")-- assert "npm run build" in text and "pdm build" in text, (- "release-gate no longer builds a wheel from built frontend "- "assets; this test's premise is gone"- )- assert "pip install --no-cache-dir" in text, (- "release-gate no longer pip-installs the wheel"- )- assert "manifest.json" not in text, (- "release-gate now mentions manifest.json -- if it asserts the "- "wheel contains it, this gap is closed and the test should "- "assert that instead"- )- assert "static/dist" not in text, (- "release-gate now mentions static/dist -- see above"+ assert "npm run build" in text and "pdm build" in text+ assert "pip install --no-cache-dir" in text+ assert "release_package.py create" in text+ assert 'assets.joinpath(".vite/manifest.json").is_file()' in text+ assert (+ 'resources.files("local_deep_research").joinpath("web/static/dist")'+ in text)def test_production_image_gets_dist_only_through_the_wheel(self):