🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🔧 chore(skills): add manual CLI npm release workflow (#22184)
AmAzing-2986d051d9af
diff --git a/.agents/skills/cli-npm-release/SKILL.md b/.agents/skills/cli-npm-release/SKILL.mdnew file mode 100644index 00000000000..1450d9404c4--- /dev/null+++ b/.agents/skills/cli-npm-release/SKILL.md@@ -0,0 +1,132 @@+---+name: cli-npm-release+description: 'Manual-only npm release preparation for @lobehub/cli (lh): establish evidence-backed release gates, prepare one verified tarball, hand a single publication entry point to a human, then verify registry availability. Never publishes automatically.'+disable-model-invocation: true+user-invocable: true+argument-hint: '[target-version] [--tag latest|next|beta]'+---++# CLI npm Release++The agent prepares and verifies; an authorized human publishes. Optimize for **one clear next action**, not a long checklist pasted into chat. Preserve the guarantee that **the published bytes are the tested bytes**.++## Invocation and boundaries++- Run only on explicit skill invocation: `/skill:cli-npm-release`, `/cli-npm-release`, `$cli-npm-release`, or the harness's equivalent. A generic release request, version bump, another skill, subagent, hook, or CI is not authorization to invoke this workflow. Arguments are data, not shell code.+- Keep `disable-model-invocation: true` and `agents/openai.yaml`'s implicit invocation prohibition. If a harness cannot enforce manual discovery, keep this skill out of its automatic discovery.+- **Never execute `scripts/humanPublish.mjs`, its prepared copy, `npm publish` (including dry runs), any equivalent package-manager/registry mutation, or a publishing workflow.** You may prepare the human entry point and print its invocation. Never test it by executing it or drive its terminal confirmation for the user.+- Do not log in to npm, request tokens/OTPs, inspect credential files, or print secrets. Human authentication and 2FA stay in the human's terminal. Public registry reads need no publisher credentials.+- No automatic commits, pushes, Git tags, branch switching, root app version changes, or releases of other packages. Repository synchronization is a separate, explicitly authorized task.+- Preserve unrelated edits. Never reset, clean, stash, or delete generated caches to manufacture a passing tree. Dirty release inputs or environment repairs require the user's resolution or approval of an isolated preparation environment.+- A simpler UX must **not** offer directory-based publishing, rebuilding at publication time, or bypass flags as an alternative to the verified artifact.++## State and communication++```text+PREPARING → BLOCKED or READY_FOR_HUMAN_PUBLICATION+ ↓ human acts+ SUBMITTED / PROCESSING → VERIFIED+ → UNCONFIRMED / UNKNOWN / MISMATCH / CHANNEL_CHANGED+```++`READY` is not published. A zero publish exit code or HTTP 202 is not proof of registry availability. `VERIFIED` requires the exact version, full integrity and selected tag to match.++Use the user's language. Explain only milestones and blockers; do not narrate every file read. Put release notes, checksums and logs in the persistent report. Ask once for unresolved release decisions; do not repeatedly ask users to approve routine local checks.++## 1. Establish inputs and create the release record++Read [references/preparation.md](references/preparation.md) for exact commands and [references/record.md](references/record.md) for the evidence contract.++Inspect current manifests, build scripts, locks, Git state and tool versions. Read npm stable and selected-channel metadata from `https://registry.npmjs.org`.++- Confirm target and tag before edits. If omitted, recommend a version and explain briefly; never silently bump a local version already ahead of npm.+- Require valid SemVer newer than the selected channel (stable if a new channel), and explicit version-not-found for the exact target. Network/auth/registry errors are not availability. Prereleases must use an explicitly confirmed non-`latest` tag.+- Initialize a **durable directory outside the repository**, not a disposable `/tmp` directory. Use `scripts/release.mjs init <absolute-directory>`; it creates `release.json` with every gate `UNKNOWN`.+- Keep `release.json`, `report.md`, the source patch, logs, evidence and tarball together. Never commit credentials or incidental artifacts. Preserve them for the next release and transfer the entire directory unchanged if the publisher uses another machine.++## 2. Resolve the baseline and affected scope++Resolve baseline provenance in this order:++1. Published package's `gitHead`, verified against the local commit.+2. A previous release record binding source SHA **and patch** to the registry's full `dist.integrity`, with successful post-publish verification.+3. A verified release-specific tag/reference whose relationship to the published package is evidenced.++Check ancestry against the candidate. **A commit that bumped `package.json`, or a commit merely being an ancestor, does not establish release provenance.** If unresolved, ask for the missing release reference and mark `baseline: UNKNOWN`; do not invent complete release notes or allow `READY`.++Run `scripts/release.mjs scope <repo-root> <full-baseline-sha>` once and save its JSON. It maps actual package names and follows workspace dependency edges across both revisions. It is a conservative starting scope, not a precise bundle reachability claim. Review imports/build inputs, root locks, offline report dependencies and deleted files; record justified narrowing rather than repeatedly scanning the same packages.++Inspect the release diff, not only local edits. Write concise **Added / Fixed / Changed / Breaking changes and upgrade notes** with commit/PR references. Separate version metadata from behavior. Identify backend-dependent outcomes; merged PRs do not establish deployment.++## 3. Complete evidence-backed gates++All gates are mandatory entries in `release.json`:++`baseline`, `version`, `scope`, `lintTests`, `types`, `bundleTests`, `acceptance`, `backend`, `build`, `tarball`, `smoke`.++- `PASS`: inspected evidence, its location, what it proves and inspection time. Command gates additionally need successful command receipts.+- `FAIL`: observed failure, with remediation.+- `UNKNOWN`: missing/uninspected evidence or a check not run. **Blocks readiness.**+- `EXEMPT`: allowed only for `acceptance` or `backend`, with a specific applicability reason. Not a waiver for missing access, time or evidence.++Use `release.mjs run` to retain full logs and actual exit codes without shell pipelines. It records execution, **not gate approval**. Load the testing skill when selecting or diagnosing release tests. Run the release-scoped lint/tests, repository type gate and explicit CLI bundle/config tests in the preparation reference. Never run repository-wide `bun run test`.++Apply `../acceptance/SKILL.md`: inspect existing reports and evidence first; map coverage to each changed outcome and check subsequent changes. Reuse valid evidence without rerunning just for a release. Verify only missing/invalidated outcomes against the candidate and the appropriate real backend/surface. `--help` is packaging smoke, not feature acceptance. Lack of approved test credentials is a blocker, not an exemption.++For new backend contracts, record target environment, actual deployed contract/version evidence or a real compatible backend round-trip. **Neither “merged into canary” nor “should have acceptance” is evidence.** Unverified required contracts block readiness.++## 4. Build, pack and verify the exact artifact++Follow [references/preparation.md](references/preparation.md): run `prepublishOnly`, verify generated outputs, pack, stamp checksums, inspect the archive, then install the tarball with npm in a disposable directory outside the repo.++- `npm pack` does not run `prepublishOnly`.+- Artifact paths come from the current build configuration and `pack.json`, not hardcoded worker extensions.+- Verify all bin aliases, man pages, offline report and relevant native behavior; reject unresolved workspace runtime dependencies or unintended/private files.+- Do not mutate global CLI installations, connect personal daemons or borrow personal credentials for smoke tests.+- Review lint autofixes and retain all release-input diffs. Changed inputs invalidate affected checks; rebuild and retest before packing again. Never overwrite a handed-off tarball. Use a new preparation directory for a changed candidate.++## 5. Hand off one human-only command++Complete `report.md`, then run the **non-publishing** helper:++```bash+node "$SKILL_DIR/scripts/release.mjs" handoff "$RELEASE_DIR"+```++It fails closed on missing gates/evidence/receipts, changed tarball, occupied version or changed channel; seals the record and local evidence; copies the standalone human entry point into the release directory; and prints **one concrete command**. It cannot judge the truth or coverage of evidence for you: do not mark a gate `PASS` merely to make it succeed.++Reply in this shape, replacing all examples with real results:++> **0.0.74 已准备好,尚未发布。**+> 下一步:你在自己的终端执行下面这一条命令。+> `[the exact single command printed by handoff]`+> 完成后告诉我;我会核对 npm 版本、完整性和频道。+> 详细记录:`<absolute report.md path>`++Do not paste the full audit report or inline hash program into chat. For `BLOCKED`, give the missing proof and next action instead; **do not generate a runnable publication command**.++The human entry point checks the seal, artifact, gates, npm identity, exact target availability and unchanged channel; asks the human to confirm the version; rechecks immediately before publishing the tarball with `--ignore-scripts`. This flag avoids lifecycle execution on the already built/tested tarball; it never replaces `prepublishOnly`. `whoami` proves identity, not publishing permission. Login/2FA remains human-owned. TTY/confirmation is an accidental-use guard, not an authorization sandbox; the agent prohibition still applies.++## 6. Verify after the human reports publication++The preparation stops at the human handoff, **not** at read-only post-publication verification. After the user reports a publish attempt, run:++```bash+node "$SKILL_DIR/scripts/release.mjs" verify "$RELEASE_DIR"+```++This only reads npm and writes local verification records. It performs up to eight checks with increasing delays, a ten-minute polling budget and bounded individual registry calls (an in-flight query may finish after the budget).++- HTTP 202 / “being processed”: accepted for processing; do not call it failed or already available.+- Temporary version 404 or old tag: `PENDING`; wait, do not repeat publishing. Thirty seconds of invisibility is not proof of failure.+- Version, **full** integrity and selected tag match: `VERIFIED`.+- Budget exhausted: `UNCONFIRMED`; retain artifact and attempt history. A later invocation can resume read-only verification without rebuilding.+- Registry errors: `UNKNOWN`; distinguish these from absence. Integrity mismatch or unexpected channel movement requires investigation, not automatic tag changes or republishing.++If diagnostics are needed, first ask for the publish command's redacted result/status. Do not scan arbitrary npm/auth logs. Never compare a truncated integrity preview as if it proved byte equality.++## 7. Repository synchronization and next release++Report two independent statuses: **npm publication** and **repository synchronization**. Offer the version-bump PR only after explicit user authorization, through the `pr` skill; do not silently include incidental lint changes. Confirm their scope if inclusion is needed.++Record PR URL and `NOT_REQUESTED / PR_OPEN / MERGED` under `repositorySync`. A created PR is not a merged change. Update only that field after sealing; do not rewrite the prepared source SHA to a later PR/merge SHA. Keep the original source patch, tarball integrity and verification history as the next release's provenance. Publication can be verified while repository synchronization is still pending.diff --git a/.agents/skills/cli-npm-release/agents/openai.yaml b/.agents/skills/cli-npm-release/agents/openai.yamlnew file mode 100644index 00000000000..5b1f887a913--- /dev/null+++ b/.agents/skills/cli-npm-release/agents/openai.yaml@@ -0,0 +1,2 @@+policy:+ allow_implicit_invocation: falsediff --git a/.agents/skills/cli-npm-release/references/preparation.md b/.agents/skills/cli-npm-release/references/preparation.mdnew file mode 100644index 00000000000..69ff90e5150--- /dev/null+++ b/.agents/skills/cli-npm-release/references/preparation.md@@ -0,0 +1,153 @@+# Preparation commands and artifact checks++Use these recipes after explicit invocation. Read current scripts every time; these commands are not a substitute for checking the actual build chain. Paths here assume the repository root unless stated otherwise. Never execute `humanPublish.mjs` from an agent.++## Inputs and durable storage++Inspect:++- `AGENTS.md`, `apps/cli/package.json`, `apps/cli/tsdown.config.ts`;+- root and CLI workspace/lock files;+- `apps/cli/scripts/copyReportTemplate.ts`, `apps/workbench/package.json` and its report build script/config;+- `.github/workflows/preview-cli.yml` and build inputs it references.++```bash+git status --short+git branch --show-current+git rev-parse HEAD+node --version+bun --version+pnpm --version+npm --version+npm view @lobehub/cli dist-tags --json --registry=https://registry.npmjs.org+npm view @lobehub/cli@latest version gitHead dist.integrity --json --registry=https://registry.npmjs.org+```++Node must satisfy the package's actual `engines.node`. Query the selected channel too when it differs from stable. Save the registry responses and inspection notes as evidence. Query the confirmed target explicitly; only an explicit version-not-found response proves absence. Do not suppress stderr and call a failed lookup a free version.++After confirming version and tag, initialize a unique durable directory. Set `TARGET` to the confirmed version; do not copy an example version from this document:++```bash+REPO_ROOT="$PWD"+SKILL_DIR="$REPO_ROOT/.agents/skills/cli-npm-release"+RELEASE_DIR="$HOME/.local/share/lobehub/cli-releases/$TARGET-$(date -u +%Y%m%dT%H%M%SZ)"+node "$SKILL_DIR/scripts/release.mjs" init "$RELEASE_DIR"+```++Fill `release.json` using [record.md](record.md). Do not mark anything passed yet. The record and report stay outside Git. If a baseline is unavailable, persist the blocked record rather than continuing into a guessed release.++## Baseline and scope++Verify a full baseline SHA and the evidence connecting it to the published package. Check `git merge-base --is-ancestor`. A previous record must have a matching registry integrity and a `VERIFIED` result, not just a filename/version match. Preserve its source patch:++- Metadata/format-only patches: inspect and account for them explicitly in release notes.+- Behavior-changing patches: reconstruct the actual old source snapshot for comparison; `baselineSHA..HEAD` alone would omit them. If reconstruction is unavailable, block the complete summary.++For a prerelease, include both stable and selected-channel comparisons when different. After provenance is established:++```bash+node "$SKILL_DIR/scripts/release.mjs" scope "$REPO_ROOT" "$BASE_SHA" > "$RELEASE_DIR/scope.json"+```++The helper matches manifest `name`, not arbitrary text mentioning a package, and considers dependencies at both revisions. Its conservative closure includes dev/build dependencies. Inspect reachability to narrow it; absence from a direct import scan is not proof a transitive dependency is unreachable. Also inspect root/build configuration outside that closure as applicable.++Use the recorded `paths` for `git log`, `git diff`, final dirty-input checks and `git diff --binary HEAD -- <release-input-paths...>`. Save the final patch as `release-input.patch`, including both staged and unstaged changes. An empty patch is valid if everything is committed. Untracked release inputs must be explicitly captured or resolved; do not pretend a tracked-only diff contains them. Do not include unrelated local edits or secrets.++Do not upgrade dependencies. Apply only the confirmed CLI version and necessary matching lock metadata with targeted edits. Preserve and review lint autofixes separately. Semantic fixes are new release inputs, not incidental release housekeeping.++## Command receipts and quality gates++The `run` helper launches argv directly, with **no shell**, retains combined stdout/stderr and propagates the actual exit code. It prints relative receipt/log paths under `logs/`. Pass these to gate `runs` and `evidence`; it never sets a gate to `PASS` for you.++```bash+node "$SKILL_DIR/scripts/release.mjs" run "$RELEASE_DIR" lint-tests -- \+ bun run check --lint --test <concrete-affected-source-and-test-paths...>+node "$SKILL_DIR/scripts/release.mjs" run "$RELEASE_DIR" types -- \+ bun run check --type++cd "$REPO_ROOT/apps/cli"+node "$SKILL_DIR/scripts/release.mjs" run "$RELEASE_DIR" bundle-tests -- \+ bunx vitest run --silent=passed-only bundle.test.ts tsdown.config.test.ts vitest.config.test.ts+```++Replace the path placeholder with existing source/test paths from the reviewed release scope, including shared packages. Do not blindly pass deleted files, or omit related tests because only a source file changed. Review all lint autofixes. Do not pipe checks to `tail`/`head`; output truncation must not hide exit status. Inspect logs from their recorded locations.++If dependencies are missing, use pnpm with the committed locks for both root and CLI workspaces, preferably `--frozen-lockfile`. No silent lock regeneration. A type failure remains a failed run, even if apparently pre-existing. Ask before environment repair (including removing generated caches), retain the failed receipt, explain the repair, and record the new run separately. An isolated clean environment is preferable to modifying an active developer environment.++## Acceptance and compatibility++Before new execution, build a coverage table in `report.md`:++| Changed outcome / PR | Required surface | Acceptance evidence and inspected result | Candidate compatibility | Backend environment / deployed evidence |+| -------------------- | ---------------- | ---------------------------------------- | ----------------------- | --------------------------------------- |++Inspect report contents and required artifacts, not just whether a PR has a link. Check later changes to relevant code, dependencies, configuration and environment. Note why evidence remains valid. Reuse completed acceptance; run only gaps under the acceptance skill. An unverified UI outcome cannot be relabeled a CLI-only check.++For each required server contract, name the target backend and prove it is available there. Deployment metadata identifying the relevant revision or a successful real contract interaction can support this. A merge SHA alone cannot. State self-hosted compatibility requirements without implying all installations have upgraded.++A `PASS` in the release record references this table and its underlying evidence. Missing reports/credentials/deployment facts mean `UNKNOWN`, not “probably tested in the PR.” Do not borrow npm credentials or personal product credentials to close a gap.++## Complete publication build++From `apps/cli`:++```bash+node "$SKILL_DIR/scripts/release.mjs" run "$RELEASE_DIR" build -- npm run prepublishOnly+node "$SKILL_DIR/scripts/release.mjs" run "$RELEASE_DIR" built-version -- node dist/index.js --version+node "$SKILL_DIR/scripts/release.mjs" run "$RELEASE_DIR" built-help -- node dist/index.js --help+```++The current lifecycle builds the workbench report, bundles the CLI and maintenance worker, requires/copies the offline report, and generates man pages. Verify the current chain rather than assuming it stays unchanged. The printed version must equal the confirmed target. Reconcile worker extensions with the actual loader reference and build output; do not assume `.js` when the output is `.mjs`.++A missing report, worker, manual, unresolved import or failed build blocks the release. A successful `npm pack` alone does not prove these steps ran.++## Pack and inspect++Still from `apps/cli`, after reviewing any current pack lifecycle scripts:++```bash+node "$SKILL_DIR/scripts/release.mjs" pack "$RELEASE_DIR"+node "$SKILL_DIR/scripts/release.mjs" stamp "$RELEASE_DIR"+```++`pack` calls **only `npm pack`**, writes separate JSON/stderr/exit records and refuses to overwrite an existing pack or handoff. `stamp` derives the filename from `pack.json`, verifies package/version, full integrity and size, and records SHA-256 plus local Node/platform. Neither approves gates or publishes.++Inspect the actual archive listing and packed `package.json`:++- Package name, target version, engines, dependencies, intended public access and registry.+- All declared bin aliases (`lh`, `lobe`, `lobehub`), correct executable shebang and mode.+- Main bundle, current maintenance worker, `dist/acceptance-report.html`, and all declared man pages; inspect manual redirects too.+- No secrets, local credentials, `.env`, private artifacts or unintended files. An eight-file listing alone is not proof the contents contain no secrets.+- No `workspace:`/`file:`/`link:` runtime dependencies; bundled imports must resolve outside the monorepo. Distinguish consumer runtime dependencies from devDependencies.++Retain the listing/inspection results. Use the exact absolute tarball path derived from `release.json`/`pack.json` in all subsequent steps. Never substitute a directory, workspace link or later rebuild.++## Disposable install and smoke++Create a disposable directory **outside** the repo. Inspect runtime dependency install scripts before running installation. Use npm to exercise consumer resolution; do not bypass a failed native install.++```bash+SMOKE_DIR="$(mktemp -d "${TMPDIR:-/tmp}/lh-cli-smoke.XXXXXX")"+node "$SKILL_DIR/scripts/release.mjs" run "$RELEASE_DIR" install -- \+ npm install --prefix "$SMOKE_DIR" --no-audit --no-fund --registry=https://registry.npmjs.org "$TARBALL"+node "$SKILL_DIR/scripts/release.mjs" run "$RELEASE_DIR" smoke-version -- \+ env LOBEHUB_CLI_HOME="$SMOKE_DIR/home" "$SMOKE_DIR/node_modules/.bin/lh" --version+node "$SKILL_DIR/scripts/release.mjs" run "$RELEASE_DIR" smoke-help -- \+ env LOBEHUB_CLI_HOME="$SMOKE_DIR/home" "$SMOKE_DIR/node_modules/.bin/lh" --help+node "$SKILL_DIR/scripts/release.mjs" run "$RELEASE_DIR" smoke-lobe -- \+ env LOBEHUB_CLI_HOME="$SMOKE_DIR/home" "$SMOKE_DIR/node_modules/.bin/lobe" --version+node "$SKILL_DIR/scripts/release.mjs" run "$RELEASE_DIR" smoke-lobehub -- \+ env LOBEHUB_CLI_HOME="$SMOKE_DIR/home" "$SMOKE_DIR/node_modules/.bin/lobehub" --version+```++Exercise changed command registration/manuals and applicable offline report rendering. For changed native dependencies, exercise actual native terminal behavior in an approved isolated environment; installation alone is not that check. Record actual runtime/platform limits; one macOS smoke is not Linux/Windows verification. Feature acceptance still needs actual affected outcomes, not help output.++Bind these checks to the recorded tarball. If anything changes after packing, use a new preparation directory and repeat affected gates. Keep the immutable prepared artifact and logs; the disposable smoke environment is not the release record.++## Handoff and later verification++Complete the record/report and invoke `handoff` as described in `SKILL.md`. It prints one human-only command with concrete paths. Transfer the whole directory unchanged when publishing elsewhere; on the destination, the human runs `node <transferred-directory>/tools/humanPublish.mjs`. Internal references are relative so the seal survives transfer.++The publisher authenticates independently and handles 2FA. A failed identity check happens before any publish attempt. Once an actual publish is attempted, `publish-attempt.json` prevents blind reruns, even after a nonzero exit or interruption. There is no force/retry bypass. Investigate and resolve registry state first; only a conclusively rejected attempt permits a newly prepared handoff.++After the user reports publication, run read-only `verify`. Each invocation creates a new `verification/<timestamp>.json` with timestamped attempts, observed version/full integrity/tags and final state. Preserve earlier pending/failed observations. If visibility is delayed, keep the existing artifact and wait; never rebuild or publish again just to make the query succeed.diff --git a/.agents/skills/cli-npm-release/references/record.md b/.agents/skills/cli-npm-release/references/record.mdnew file mode 100644index 00000000000..121f70d5b00--- /dev/null+++ b/.agents/skills/cli-npm-release/references/record.md@@ -0,0 +1,127 @@+# Release record and evidence contract++## Directory layout++Keep a durable directory outside the checkout, one per prepared candidate:++```text+release.json # machine-readable preparation and gate verdicts+release-input.patch # exact staged + unstaged release-input diff against source.sha+report.md # human-readable notes, coverage, compatibility, risks+scope.json # conservative workspace map + changed/dirty paths+logs/*.log # complete command outputs+logs/*.json # command/cwd/time/exit-code/log receipts+pack.json # actual npm pack output+pack-stderr.log+pack-run.json+<filename-from-pack.json> # the exact tarball+handoff.json # readiness seal, only created after successful validation+tools/ # copied standalone human publication entry and its modules+publish-attempt.json # written by the human entry; not proof of availability+verification/*.json # append-only, timestamped read-only verification rounds+```++`init` creates the skeleton of `release.json`. All paths inside it are **relative to this directory**, allowing intact transfer without changing the seal. Local evidence must be copied into the release directory; do not depend on ephemeral harness overflow files. Avoid credential-bearing URLs or raw auth/debug logs. Keep secrets out of commands/argv too: command receipts record arguments.++## Required fields++| Field | Meaning |+| ------------------------- | ----------------------------------------------------------------------------------------------------------------- |+| `schemaVersion` | `1` |+| `package`, `registry` | Exactly `@lobehub/cli`, `https://registry.npmjs.org` |+| `version`, `tag` | Confirmed SemVer and `latest`, `next` or `beta`; no prerelease on `latest` |+| `baseline.version` | Published version used for the primary release summary |+| `baseline.channelVersion` | Selected tag's exact version at preparation; `null` only if that tag does not exist |+| `baseline.stableVersion` | Published `latest` version, also used for comparison when creating a new channel |+| `baseline.sourceSha` | Full verified source commit for the primary baseline |+| `baseline.provenance` | `npm-gitHead`, `release-record`, or `verified-release-ref`; never `version-bump` |+| `source.sha` | Actual full source commit used to build; do not replace it later with a bump PR SHA |+| `source.patch` | Exact release-input patch against that SHA; file exists even when empty |+| `artifact` | `path`, `sha256`, full `integrity`, `size`, tested `node`, `platform`; populated by `stamp`, reviewed after smoke |+| `gates` | Every named gate below, even when blocked or exempt |+| `repositorySync` | `state`: `NOT_REQUESTED`, `PR_OPEN`, or `MERGED`; actual `pr` URL or `null` |++Version ordering uses SemVer precedence, including numeric prerelease identifiers; build metadata does not make an already used version newer. Exact-version availability is always checked against npm, not inferred from `dist-tags` alone. If a channel advances in either direction, the human entry stops rather than moving it back.++## Gate states++A new record starts with `UNKNOWN` for all eleven gates. Populate states only from observations, never to satisfy the validator.++A passing gate has this shape (example filenames must be replaced by captured files):++```json+{+ "checkedAt": "2026-11-03T09:00:00.000Z",+ "evidence": [+ {+ "ref": "logs/build-1793696400000.log",+ "note": "Inspected the full build log: workbench report, CLI/worker bundles and man pages completed without unresolved imports."+ }+ ],+ "runs": ["logs/build-1793696400000.json"],+ "status": "PASS"+}+```++- `evidence` must be nonempty. Each entry has `ref` (relative local file or HTTPS URL) and `note` explaining **what was inspected and proven**.+- `checkedAt` records the inspection time, not an invented execution time.+- `runs` is mandatory for `lintTests`, `types`, `bundleTests`, `build`, `smoke`. Every referenced receipt must have `exitCode: 0`, a command and an existing output log. Include all required successful commands for that gate, not just a convenient successful subset.+- Keep failed runs in the directory and explain them in the report. The passing gate references the successful replacement runs; failures do not disappear from history.+- A URL-shaped string is not proof of valid acceptance or deployment. The helper validates structure and local file availability, **not remote evidence truth, recency or coverage**. The agent must inspect those properties.++An exemption has a specific reason:++```json+{+ "reason": "Only CLI version metadata changed; there is no changed product behavior requiring new acceptance.",+ "status": "EXEMPT"+}+```++Only `acceptance` and `backend` can be exempt. Reusing valid acceptance is `PASS` with evidence, not `EXEMPT`. Missing credentials, missing reports, an unavailable backend or a deadline are `UNKNOWN`/`FAIL`, never exemption reasons.++For `FAIL` or `UNKNOWN`, retain observations in `evidence` when available and a `reason` describing the blocker and next action. Omitting a gate or spelling a different status cannot make the record ready.++## What each gate must establish++| Gate | Required proof |+| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `baseline` | Published package ↔ verified source reference; registry metadata / previous verified record, ancestry result and any baseline patch accounted for |+| `version` | User's target/tag decision, local/stable/channel versions, SemVer ordering, explicit exact-target absence and only intended metadata edits |+| `scope` | Reviewed dependency/build closure, release diff, deleted files, clean or explicitly captured release inputs; summary references agree with this scope |+| `lintTests` | Concrete release-scoped source/test paths, successful lint/test receipts and reviewed autofixes |+| `types` | Successful repository type gate, with any prior failure/approved repair disclosed |+| `bundleTests` | Explicit bundle/config regression receipts for the current release |+| `acceptance` | Outcome-by-outcome coverage table, inspected reusable evidence plus any newly verified gaps on the proper surfaces; or valid behavior-neutral exemption |+| `backend` | Target environment and actual deployment/contract support for each dependent outcome; or reason no new backend requirement applies |+| `build` | Complete `prepublishOnly` lifecycle, expected version/help, required generated outputs and no unresolved imports |+| `tarball` | Actual archive/packed manifest inspection, correct metadata/bin/files/runtime dependencies, private-file/content review, recorded fingerprints |+| `smoke` | Successful real npm tarball install outside the repo, all bin aliases, appropriate affected command/offline/native checks, actual runtime/platform limits |++For multi-outcome gates, cite the coverage table **and** underlying evidence. One passing outcome does not stand for all changed behavior. A read-only command's exit status alone does not prove the returned version or data was correct; inspect its output.++## Detailed report++`report.md` holds what should not crowd the chat:++1. Package, target/channel/registry, published baselines and provenance, source SHA plus patch, toolchain/platform.+2. Added/Fixed/Changed/Breaking changes and upgrade notes, with commit/PR references. No empty sections or unverified release claims.+3. Outcome/acceptance/backend coverage table; reuse rationale, deployment evidence, self-hosted requirements and known limitations.+4. Each gate's verdict, evidence and command receipts; failed attempts and approved repairs honestly recorded.+5. Exact artifact filename, hashes, size, inspected contents and smoke environment; transfer the whole directory unchanged.+6. Any remaining risk consistent with the verdict. Missing required verification is a blocker, not a footnote under `READY`.++The handoff helper seals this report, the preparation record, patch, local evidence/command receipts/logs, artifact and copied publication tools. Once handed off, do not edit them. Changed candidate/evidence requires new preparation and revalidation of affected gates. The seal detects accidental drift; it is not a signed supply-chain attestation.++Post-publication facts belong in **new** `verification/*.json` files, not by rewriting the prepublication report. Only `repositorySync` may be updated independently in `release.json`; it is deliberately outside the preparation seal. Mark `MERGED` only after actually observing the merge. A PR link proves creation, not integration.++## Interpreting publication records++- `publish-attempt.json`: the human entry records intent before calling npm. Exit zero becomes `SUBMITTED`, not `VERIFIED`. Interruption/nonzero remains uncertain until investigated. Its existence prevents blind repeat calls.+- `verification/*.json`: each round retains all observed responses, expected integrity and final result. `PENDING` observations may precede `VERIFIED`; they are not failed publications.+- `UNCONFIRMED`: polling budget exhausted, nothing established about eventual success/failure. Resume only read-only verification later.+- `UNKNOWN`: query/auth/network/schema problem; resolve that before drawing conclusions about availability.+- `MISMATCH` / `CHANNEL_CHANGED`: investigate the discrepancy; never fix by automatic republishing, retagging or unpublishing.+- `VERIFIED`: exact version and full registry integrity equal the prepared artifact, selected tag points to target. This proves registry availability/identity, not a new feature acceptance run.++A later release may reuse this directory as baseline provenance only after checking its verified result, source SHA/patch and full integrity against registry metadata. If these records are missing, ask for an independently verified reference rather than guessing from Git history.diff --git a/.agents/skills/cli-npm-release/scripts/humanPublish.mjs b/.agents/skills/cli-npm-release/scripts/humanPublish.mjsnew file mode 100644index 00000000000..61084a16415--- /dev/null+++ b/.agents/skills/cli-npm-release/scripts/humanPublish.mjs@@ -0,0 +1,87 @@+import { spawnSync } from 'node:child_process';+import { existsSync, writeFileSync } from 'node:fs';+import path from 'node:path';+import { createInterface } from 'node:readline/promises';+import { fileURLToPath } from 'node:url';++import { handoffDigest, localFile, readJson, requireReady } from './record.mjs';+import { assertUnpublished } from './registry.mjs';++// Human-only entry point. Agents must never execute this file, even for a dry run.+async function main() {+ if (!process.stdin.isTTY || !process.stdout.isTTY)+ throw new Error(+ 'Run manually in an interactive terminal; agents must not run this entry point',+ );+ const directory = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+ const record = readJson(path.join(directory, 'release.json'));+ const seal = readJson(path.join(directory, 'handoff.json'));+ const validate = () => {+ requireReady(record, directory);+ if (handoffDigest(record, directory) !== seal.digest)+ throw new Error('Handoff changed; repeat preparation, do not publish');+ };+ validate();+ const attemptPath = path.join(directory, 'publish-attempt.json');+ if (existsSync(attemptPath))+ throw new Error(+ 'A publication was already attempted. Ask the agent to verify registry state; do not retry blindly',+ );+ const identity = spawnSync('npm', ['whoami', `--registry=${record.registry}`], {+ stdio: 'inherit',+ timeout: 30000,+ });+ if (identity.error || identity.status !== 0) {+ throw new Error(+ `No confirmed npm identity. Run npm login --registry=${record.registry} yourself, then rerun this command. No publish was attempted`,+ );+ }+ assertUnpublished(record);+ const prompt = createInterface({ input: process.stdin, output: process.stdout });+ let answer;+ try {+ answer = await prompt.question(+ `Publish ${record.package}@${record.version} to ${record.tag}? Type ${record.version} to confirm: `,+ );+ } finally {+ prompt.close();+ }+ if (answer !== record.version) throw new Error('Cancelled; nothing published');+ assertUnpublished(record);+ validate();+ const attempt = {+ state: 'ATTEMPTED',+ startedAt: new Date().toISOString(),+ integrity: record.artifact.integrity,+ };+ writeFileSync(attemptPath, `${JSON.stringify(attempt, null, 2)}\n`, { flag: 'wx', mode: 0o600 });+ const result = spawnSync(+ 'npm',+ [+ 'publish',+ localFile(directory, record.artifact.path),+ '--access',+ 'public',+ '--tag',+ record.tag,+ `--registry=${record.registry}`,+ '--ignore-scripts',+ ],+ { stdio: 'inherit' },+ );+ Object.assign(attempt, {+ state: !result.error && result.status === 0 ? 'SUBMITTED' : 'UNCONFIRMED',+ exitCode: result.status,+ finishedAt: new Date().toISOString(),+ });+ writeFileSync(attemptPath, `${JSON.stringify(attempt, null, 2)}\n`, { mode: 0o600 });+ console.info(+ 'Publication attempt recorded. npm may process it asynchronously. Tell the agent to verify version, full integrity and tag; do not republish while visibility is pending.',+ );+ if (attempt.state !== 'SUBMITTED') process.exitCode = 1;+}++main().catch((error) => {+ console.error(error.message);+ process.exitCode = 1;+});diff --git a/.agents/skills/cli-npm-release/scripts/record.mjs b/.agents/skills/cli-npm-release/scripts/record.mjsnew file mode 100644index 00000000000..a4996dc9e1a--- /dev/null+++ b/.agents/skills/cli-npm-release/scripts/record.mjs@@ -0,0 +1,221 @@+import { createHash } from 'node:crypto';+import { readFileSync, statSync } from 'node:fs';+import path from 'node:path';++export const REGISTRY = 'https://registry.npmjs.org';+export const GATES = [+ 'baseline',+ 'version',+ 'scope',+ 'lintTests',+ 'types',+ 'bundleTests',+ 'acceptance',+ 'backend',+ 'build',+ 'tarball',+ 'smoke',+];+const COMMAND_GATES = new Set(['lintTests', 'types', 'bundleTests', 'build', 'smoke']);+const EXEMPTIBLE = new Set(['acceptance', 'backend']);++export function createRecord() {+ return {+ schemaVersion: 1,+ package: '@lobehub/cli',+ registry: REGISTRY,+ version: '',+ tag: '',+ baseline: {+ version: '',+ channelVersion: null,+ stableVersion: '',+ sourceSha: '',+ provenance: '',+ },+ source: { sha: '', patch: 'release-input.patch' },+ artifact: { path: '', sha256: '', integrity: '', size: 0, platform: '', node: '' },+ gates: Object.fromEntries(GATES.map((id) => [id, { status: 'UNKNOWN', evidence: [] }])),+ repositorySync: { state: 'NOT_REQUESTED', pr: null },+ };+}++function parseVersion(value) {+ const match =+ /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*))?(?:\+[\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*)?$/.exec(+ value,+ );+ if (!match) throw new Error(`Invalid SemVer: ${value}`);+ const prerelease = match[4]?.split('.') ?? [];+ if (prerelease.some((part) => /^0\d+$/.test(part))) throw new Error(`Invalid SemVer: ${value}`);+ return { core: match.slice(1, 4).map(BigInt), prerelease };+}++export function compareVersions(left, right) {+ const a = parseVersion(left);+ const b = parseVersion(right);+ for (let i = 0; i < 3; i++) {+ if (a.core[i] !== b.core[i]) return a.core[i] > b.core[i] ? 1 : -1;+ }+ if (!a.prerelease.length || !b.prerelease.length) {+ return Math.sign(b.prerelease.length) - Math.sign(a.prerelease.length);+ }+ for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i++) {+ const x = a.prerelease[i];+ const y = b.prerelease[i];+ if (x === y) continue;+ if (x === undefined) return -1;+ if (y === undefined) return 1;+ const xn = /^\d+$/.test(x);+ const yn = /^\d+$/.test(y);+ if (xn !== yn) return xn ? -1 : 1;+ return (xn ? BigInt(x) > BigInt(y) : x > y) ? 1 : -1;+ }+ return 0;+}++export function digest(bytes, algorithm = 'sha256', encoding = 'hex') {+ return createHash(algorithm).update(bytes).digest(encoding);+}++export function readJson(file) {+ return JSON.parse(readFileSync(file, 'utf8'));+}++export function localFile(directory, relative) {+ if (typeof relative !== 'string' || !relative || path.isAbsolute(relative)) {+ throw new Error('Expected a release-directory-relative path');+ }+ const file = path.resolve(directory, relative);+ if (!file.startsWith(`${path.resolve(directory)}${path.sep}`))+ throw new Error('Path escapes release directory');+ return file;+}++function readableFile(directory, ref, allowEmpty = false) {+ const file = localFile(directory, ref);+ const info = statSync(file);+ if (!info.isFile() || (!allowEmpty && !info.size))+ throw new Error(`Missing or empty file: ${ref}`);+ return file;+}++export function validateRecord(record, directory) {+ const errors = [];+ const check = (label, fn) => {+ try {+ fn();+ } catch (error) {+ errors.push(`${label}: ${error.message}`);+ }+ };+ check('release', () => {+ if (+ record.schemaVersion !== 1 ||+ record.package !== '@lobehub/cli' ||+ record.registry !== REGISTRY+ ) {+ throw new Error('Unsupported schema, package or registry');+ }+ if (!['latest', 'next', 'beta'].includes(record.tag))+ throw new Error('Confirm latest, next or beta');+ const version = parseVersion(record.version);+ if (version.prerelease.length && record.tag === 'latest')+ throw new Error('Prerelease cannot use latest');+ const baseline = record.baseline?.channelVersion ?? record.baseline?.stableVersion;+ if (compareVersions(record.version, baseline) <= 0)+ throw new Error('Target must be newer than channel baseline');+ parseVersion(record.baseline?.version);+ parseVersion(record.baseline?.stableVersion);+ });+ check('baseline provenance', () => {+ if (+ !['npm-gitHead', 'release-record', 'verified-release-ref'].includes(+ record.baseline?.provenance,+ )+ ) {+ throw new Error(+ 'Require npm gitHead, a verified release record or a verified release reference; never a guessed bump commit',+ );+ }+ if (!/^[\da-f]{40}$/.test(record.baseline?.sourceSha))+ throw new Error('Missing baseline source SHA');+ });+ check('source', () => {+ if (!/^[\da-f]{40}$/.test(record.source?.sha)) throw new Error('Missing candidate source SHA');+ readableFile(directory, record.source?.patch, true);+ });+ for (const id of GATES) {+ check(id, () => {+ const gate = record.gates?.[id];+ if (gate?.status === 'EXEMPT' && EXEMPTIBLE.has(id) && gate.reason?.trim()) return;+ if (gate?.status !== 'PASS') throw new Error(`Gate is ${gate?.status ?? 'missing'}`);+ if (!gate.checkedAt || !Number.isFinite(Date.parse(gate.checkedAt)))+ throw new Error('Missing inspection time');+ if (!Array.isArray(gate.evidence) || !gate.evidence.length)+ throw new Error('Missing inspected evidence');+ for (const evidence of gate.evidence) {+ if (!evidence.note?.trim()) throw new Error('Explain what the inspected evidence proves');+ if (evidence.ref.startsWith('https://')) {+ const url = new URL(evidence.ref);+ if (url.username || url.password) throw new Error('Credential-bearing evidence URL');+ } else {+ readableFile(directory, evidence.ref);+ }+ }+ if (COMMAND_GATES.has(id)) {+ if (!Array.isArray(gate.runs) || !gate.runs.length)+ throw new Error('Missing command receipts');+ for (const ref of gate.runs) {+ const run = readJson(readableFile(directory, ref));+ if (run.exitCode !== 0 || !run.command?.length)+ throw new Error(`Unsuccessful command receipt: ${ref}`);+ readableFile(directory, run.log, true);+ }+ }+ });+ }+ check('artifact', () => {+ const artifact = record.artifact;+ const bytes = readFileSync(readableFile(directory, artifact?.path));+ if (+ artifact.sha256 !== digest(bytes) ||+ artifact.integrity !== `sha512-${digest(bytes, 'sha512', 'base64')}` ||+ artifact.size !== bytes.length+ ) {+ throw new Error('Tarball checksum, integrity or size changed');+ }+ if (!artifact.node || !artifact.platform) throw new Error('Missing tested runtime/platform');+ });+ return errors;+}++export function requireReady(record, directory) {+ const errors = validateRecord(record, directory);+ if (errors.length) throw new Error(`BLOCKED\n${errors.join('\n')}`);+}++export function handoffDigest(record, directory) {+ const { repositorySync: _repositorySync, ...preparation } = record;+ const refs = new Set([+ record.source.patch,+ record.artifact.path,+ 'report.md',+ 'tools/humanPublish.mjs',+ 'tools/record.mjs',+ 'tools/registry.mjs',+ ]);+ for (const gate of Object.values(record.gates)) {+ for (const evidence of gate.evidence ?? []) {+ if (!evidence.ref.startsWith('https://')) refs.add(evidence.ref);+ }+ for (const ref of gate.runs ?? []) {+ refs.add(ref);+ refs.add(readJson(localFile(directory, ref)).log);+ }+ }+ const files = Object.fromEntries(+ [...refs].sort().map((ref) => [ref, digest(readFileSync(localFile(directory, ref)))]),+ );+ return digest(JSON.stringify({ preparation, files }));+}diff --git a/.agents/skills/cli-npm-release/scripts/registry.mjs b/.agents/skills/cli-npm-release/scripts/registry.mjsnew file mode 100644index 00000000000..cad950842a1--- /dev/null+++ b/.agents/skills/cli-npm-release/scripts/registry.mjs@@ -0,0 +1,120 @@+import { spawnSync } from 'node:child_process';+import { setTimeout } from 'node:timers/promises';++import { REGISTRY } from './record.mjs';++export function parseRegistryResult(result, missingVersion) {+ if (result.error) throw result.error;+ let value;+ try {+ value = JSON.parse(result.stdout);+ } catch {+ throw new Error('Registry did not return JSON; check network and npm configuration');+ }+ if (result.status !== 0) {+ if (+ missingVersion &&+ value?.error?.code === 'E404' &&+ value.error.summary === `No match found for version ${missingVersion}`+ )+ return null;+ throw new Error(`Registry lookup failed: ${value?.error?.code ?? result.status}`);+ }+ if (value === null || value?.error)+ throw new Error('Registry returned an empty or error payload');+ return value;+}++export function queryRegistry(spec, fields, missingVersion) {+ return parseRegistryResult(+ spawnSync(+ 'npm',+ [+ 'view',+ spec,+ ...fields,+ '--json',+ `--registry=${REGISTRY}`,+ '--fetch-retries=0',+ '--fetch-timeout=25000',+ ],+ { encoding: 'utf8', timeout: 30000, maxBuffer: 1024 * 1024 },+ ),+ missingVersion,+ );+}++export function assertUnpublished(record, query = queryRegistry) {+ const tags = query(record.package, ['dist-tags']);+ if (!tags || typeof tags !== 'object' || typeof tags.latest !== 'string')+ throw new Error('Invalid registry dist-tags');+ if ((tags[record.tag] ?? null) !== record.baseline.channelVersion) {+ throw new Error('Selected channel changed; stop and repeat preparation');+ }+ const version = query(`${record.package}@${record.version}`, ['version'], record.version);+ if (version !== null)+ throw new Error(+ 'Target is already published or its availability is unconfirmed; never overwrite or republish',+ );+}++export function publicationState(record, query = queryRegistry) {+ const version = query(+ `${record.package}@${record.version}`,+ ['version', 'dist.integrity'],+ record.version,+ );+ const tags = query(record.package, ['dist-tags']);+ if (!tags || typeof tags !== 'object' || typeof tags.latest !== 'string')+ throw new Error('Invalid registry dist-tags');+ const channel = tags[record.tag] ?? null;+ if (+ version !== null &&+ (typeof version.version !== 'string' ||+ typeof (version['dist.integrity'] ?? version.dist?.integrity) !== 'string')+ ) {+ throw new Error('Invalid registry version/integrity response');+ }+ if (+ version !== null &&+ (version.version !== record.version ||+ (version['dist.integrity'] ?? version.dist?.integrity) !== record.artifact.integrity)+ ) {+ return { state: 'MISMATCH', version, tags };+ }+ if (channel !== record.version && channel !== record.baseline.channelVersion) {+ return { state: 'CHANNEL_CHANGED', version, tags };+ }+ return {+ state: version !== null && channel === record.version ? 'VERIFIED' : 'PENDING',+ version,+ tags,+ };+}++export async function waitForPublication(+ record,+ {+ query = queryRegistry,+ sleep = setTimeout,+ delays = [0, 10000, 20000, 40000, 60000, 90000, 120000, 120000],+ onAttempt = () => {},+ } = {},+) {+ const attempts = [];+ const deadline = Date.now() + 10 * 60 * 1000;+ for (const delay of delays) {+ if (Date.now() + delay >= deadline) break;+ if (delay) await sleep(delay);+ let result;+ try {+ result = publicationState(record, query);+ } catch (error) {+ result = { state: 'UNKNOWN', error: error.message };+ }+ attempts.push({ at: new Date().toISOString(), ...result });+ onAttempt({ ...result, attempts });+ if (result.state !== 'PENDING') return { ...result, attempts };+ }+ return { state: 'UNCONFIRMED', attempts };+}diff --git a/.agents/skills/cli-npm-release/scripts/release.mjs b/.agents/skills/cli-npm-release/scripts/release.mjsnew file mode 100644index 00000000000..e86e8335e11--- /dev/null+++ b/.agents/skills/cli-npm-release/scripts/release.mjs@@ -0,0 +1,206 @@+import { spawnSync } from 'node:child_process';+import {+ closeSync,+ copyFileSync,+ existsSync,+ mkdirSync,+ openSync,+ readFileSync,+ writeFileSync,+} from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import {+ createRecord,+ digest,+ handoffDigest,+ localFile,+ readJson,+ requireReady,+} from './record.mjs';+import { assertUnpublished, waitForPublication } from './registry.mjs';+import { collectScope } from './scope.mjs';++const scripts = path.dirname(fileURLToPath(import.meta.url));+const json = (file, value, options) =>+ writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`, options);+const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;++function runCommand(directory, label, command) {+ if (!/^[\da-z-]+$/i.test(label) || !command.length)+ throw new Error('Use a simple log label and a command after --');+ mkdirSync(path.join(directory, 'logs'), { recursive: true });+ const id = `${label}-${Date.now()}`;+ const log = `logs/${id}.log`;+ const receipt = `logs/${id}.json`;+ const fd = openSync(localFile(directory, log), 'wx', 0o600);+ let result;+ const startedAt = new Date().toISOString();+ try {+ result = spawnSync(command[0], command.slice(1), { stdio: ['ignore', fd, fd] });+ } finally {+ closeSync(fd);+ }+ const exitCode = result.error ? 1 : (result.status ?? 1);+ json(localFile(directory, receipt), {+ command,+ cwd: process.cwd(),+ startedAt,+ finishedAt: new Date().toISOString(),+ exitCode,+ signal: result.signal,+ error: result.error?.message,+ log,+ });+ console.info(JSON.stringify({ exitCode, receipt, log }));+ process.exitCode = exitCode;+}++async function main() {+ const [action, directoryArg, ...args] = process.argv.slice(2);+ if (!directoryArg)+ throw new Error(+ 'Usage: release.mjs init|scope|run|pack|stamp|handoff|verify <directory> [arguments]',+ );+ const directory = path.resolve(directoryArg);+ if (action === 'init') {+ const git = spawnSync('git', ['rev-parse', '--show-toplevel'], {+ cwd: scripts,+ encoding: 'utf8',+ });+ if (git.status !== 0) throw new Error('Cannot establish repository root');+ const root = git.stdout.trim();+ if (directory === root || directory.startsWith(`${root}${path.sep}`))+ throw new Error('Store release artifacts outside the repository');+ mkdirSync(directory, { recursive: true });+ json(path.join(directory, 'release.json'), createRecord(), { flag: 'wx', mode: 0o600 });+ console.info(+ `Initialized ${directory}; every gate is UNKNOWN. Fill release.json and report.md with inspected evidence.`,+ );+ return;+ }+ if (action === 'scope') {+ console.info(JSON.stringify(collectScope(directory, args[0]), null, 2));+ return;+ }+ if (action === 'run') {+ if (args[1] !== '--')+ throw new Error('Usage: run <release-directory> <label> -- <command> [args...]');+ runCommand(directory, args[0], args.slice(2));+ return;+ }+ const recordPath = path.join(directory, 'release.json');+ const record = readJson(recordPath);+ if (action === 'pack') {+ if (+ existsSync(path.join(directory, 'handoff.json')) ||+ existsSync(path.join(directory, 'pack.json'))+ ) {+ throw new Error(+ 'Never overwrite a packed or handed-off artifact; use a new preparation directory',+ );+ }+ const manifest = readJson(path.join(process.cwd(), 'package.json'));+ if (manifest.name !== record.package || manifest.version !== record.version)+ throw new Error('Run pack from the confirmed CLI package directory');+ const result = spawnSync('npm', ['pack', '--json', '--pack-destination', directory], {+ encoding: 'utf8',+ maxBuffer: 16 * 1024 * 1024,+ });+ writeFileSync(path.join(directory, 'pack-stderr.log'), result.stderr ?? '');+ json(path.join(directory, 'pack-run.json'), {+ command: ['npm', 'pack', '--json', '--pack-destination', directory],+ cwd: process.cwd(),+ exitCode: result.error ? 1 : (result.status ?? 1),+ log: 'pack-stderr.log',+ });+ if (result.error || result.status !== 0)+ throw new Error('npm pack failed; see pack-stderr.log');+ writeFileSync(path.join(directory, 'pack.json'), result.stdout, { flag: 'wx' });+ console.info(+ 'Packed without publishing. Next: stamp, inspect and smoke-test; pack does not run prepublishOnly.',+ );+ return;+ }+ if (action === 'stamp') {+ if (existsSync(path.join(directory, 'handoff.json')))+ throw new Error('Already handed off; use a new preparation directory for a changed artifact');+ const packs = readJson(path.join(directory, 'pack.json'));+ if (!Array.isArray(packs) || packs.length !== 1)+ throw new Error('Expected exactly one npm pack artifact');+ const pack = packs[0];+ if (pack.name !== record.package || pack.version !== record.version)+ throw new Error('Packed package/version differs from confirmed release');+ const bytes = readFileSync(localFile(directory, pack.filename));+ const integrity = `sha512-${digest(bytes, 'sha512', 'base64')}`;+ if (integrity !== pack.integrity || pack.size !== bytes.length)+ throw new Error('npm pack metadata does not match tarball');+ record.artifact = {+ path: pack.filename,+ sha256: digest(bytes),+ integrity,+ size: bytes.length,+ node: process.version,+ platform: `${process.platform}-${process.arch}`,+ };+ json(recordPath, record);+ console.info(+ 'Artifact fingerprint recorded, not approved. Inspect the archive and smoke-test this exact tarball before marking gates PASS.',+ );+ return;+ }+ if (action === 'handoff') {+ if (existsSync(path.join(directory, 'handoff.json')))+ throw new Error('Already handed off; do not overwrite its record or tools');+ requireReady(record, directory);+ if (!readFileSync(path.join(directory, 'report.md'), 'utf8').trim())+ throw new Error('Missing detailed report');+ assertUnpublished(record);+ const tools = path.join(directory, 'tools');+ mkdirSync(tools, { recursive: true });+ for (const name of ['record.mjs', 'registry.mjs', 'humanPublish.mjs'])+ copyFileSync(path.join(scripts, name), path.join(tools, name));+ json(+ path.join(directory, 'handoff.json'),+ {+ state: 'READY_FOR_HUMAN_PUBLICATION',+ preparedAt: new Date().toISOString(),+ digest: handoffDigest(record, directory),+ },+ { flag: 'wx', mode: 0o600 },+ );+ console.info(+ `${record.package}@${record.version} prepared; NOT published. Human-only next step:\nnode ${quote(path.join(tools, 'humanPublish.mjs'))}\nReport: ${path.join(directory, 'report.md')}`,+ );+ return;+ }+ if (action === 'verify') {+ requireReady(record, directory);+ const seal = readJson(path.join(directory, 'handoff.json'));+ if (seal.digest !== handoffDigest(record, directory))+ throw new Error('Handoff changed; cannot verify against a different preparation');+ mkdirSync(path.join(directory, 'verification'), { recursive: true });+ const resultPath = path.join(directory, 'verification', `${Date.now()}.json`);+ const persist = (result) =>+ json(resultPath, {+ ...result,+ version: record.version,+ tag: record.tag,+ expectedIntegrity: record.artifact.integrity,+ });+ const result = await waitForPublication(record, { onAttempt: persist });+ persist(result);+ console.info(+ `${result.state}: ${record.package}@${record.version}\nRecord: ${resultPath}\nRepository sync: ${record.repositorySync?.state ?? 'NOT_REQUESTED'} (separate from npm publication)`,+ );+ if (result.state !== 'VERIFIED') process.exitCode = 1;+ return;+ }+ throw new Error(`Unknown action: ${action}`);+}++main().catch((error) => {+ console.error(error.message);+ process.exitCode = 1;+});diff --git a/.agents/skills/cli-npm-release/scripts/scope.mjs b/.agents/skills/cli-npm-release/scripts/scope.mjsnew file mode 100644index 00000000000..dd8a97dc767--- /dev/null+++ b/.agents/skills/cli-npm-release/scripts/scope.mjs@@ -0,0 +1,75 @@+import { execFileSync } from 'node:child_process';+import { existsSync, readFileSync } from 'node:fs';+import path from 'node:path';++export function collectScope(root, baseline) {+ if (!/^[\da-f]{40}$/.test(baseline)) throw new Error('Use the verified full baseline SHA');+ const git = (...args) =>+ execFileSync('git', args, { cwd: root, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 });+ git('merge-base', '--is-ancestor', baseline, 'HEAD');+ const baselinePaths = new Set(git('ls-tree', '-r', '--name-only', '-z', baseline).split('\0'));+ const paths = new Set([...git('ls-files', '-z').split('\0'), ...baselinePaths]);+ const manifests = [...paths].filter((file) => /^(apps|packages)\/.+\/package\.json$/.test(file));+ const packages = new Map();+ for (const file of manifests) {+ const versions = [];+ if (existsSync(path.join(root, file)))+ versions.push(JSON.parse(readFileSync(path.join(root, file), 'utf8')));+ if (baselinePaths.has(file)) versions.push(JSON.parse(git('show', `${baseline}:${file}`)));+ for (const manifest of versions) {+ if (!manifest.name) continue;+ const entries = packages.get(manifest.name) ?? [];+ entries.push({ directory: path.dirname(file), manifest });+ packages.set(manifest.name, entries);+ }+ }+ const directories = new Set(['apps/cli', 'apps/workbench']);+ const queue = [...packages]+ .filter(([, entries]) => entries.some(({ directory }) => directories.has(directory)))+ .map(([name]) => name);+ const visited = new Set();+ while (queue.length) {+ const name = queue.shift();+ if (visited.has(name)) continue;+ visited.add(name);+ for (const { directory, manifest } of packages.get(name) ?? []) {+ directories.add(directory);+ const dependencies = {+ ...manifest.dependencies,+ ...manifest.devDependencies,+ ...manifest.optionalDependencies,+ ...manifest.peerDependencies,+ };+ for (const dependency of Object.keys(dependencies)) {+ if (packages.has(dependency)) queue.push(dependency);+ }+ }+ }+ const scope = [+ ...directories,+ 'package.json',+ 'pnpm-lock.yaml',+ 'pnpm-workspace.yaml',+ '.npmrc',+ '.github/workflows/preview-cli.yml',+ '.github/actions/setup-env',+ 'scripts',+ ];+ const changed = git('diff', '--name-only', '-z', `${baseline}..HEAD`, '--', ...scope)+ .split('\0')+ .filter(Boolean);+ return {+ baseline,+ candidate: git('rev-parse', 'HEAD').trim(),+ packages: Object.fromEntries(+ [...visited]+ .sort()+ .map((name) => [name, [...new Set(packages.get(name).map(({ directory }) => directory))]]),+ ),+ paths: scope.sort(),+ changed,+ existingChanged: changed.filter((file) => existsSync(path.join(root, file))),+ dirty: git('status', '--short', '--', ...scope).trim(),+ note: 'Conservative manifest dependency closure across baseline and candidate, not proof of bundled reachability. Review imports, build scripts, deleted files and backend contracts before marking scope PASS.',+ };+}