diff --git a/.dev/features/core-387-verify-archive/GRILL.md b/.dev/features/core-387-verify-archive/GRILL.md new file mode 100644 index 00000000..3b589892 --- /dev/null +++ b/.dev/features/core-387-verify-archive/GRILL.md @@ -0,0 +1,45 @@ +# GRILL — core-387-verify-archive + +Advisory: `/pharn-dev-grill` gates nothing. Spec hash recomputed as `bca940a5…3c4e`, equal to the plan's. Registered +grillers: 0 (`count-grillers.mjs`), so only the built-in axes were applied. + +```yaml +- type: FINDING + rule_id: P0 + severity: important + file: 'PLAN.md:Guarantee audit' + problem: '"A pass means an install would accept these bytes" holds only for the checks the command shares with install; the MIN_CLI comparison and the project-side steps are not run.' + evidence: 'Docs must list the differences (MIN_CLI is checked for validity only and refused where install would warn; there is no version comparison, no archetype selection and no destination checks) so CI readers do not over-read a pass.' +- type: FINDING + rule_id: P2 + severity: important + file: 'PLAN.md:Decisions 7' + problem: 'The user path reaches three messages (the input error, the refusal prefix, the summary); each must be escaped at its own interpolation, not as a whole line.' + evidence: 'CLAUDE.md "One unsafe-character set": value by value. Test it with a control character in the file name.' +- type: FINDING + rule_id: P1 + severity: important + file: 'PLAN.md:Files (tests)' + problem: 'A non-gzip input and an empty input take different routes (the input check for empty, and TarExtractError "could not decompress the fetched archive" for garbage); the second says "fetched" for a local file.' + evidence: 'Test both. The "fetched" wording lives in tar-extract.ts (a 386 file); it is left alone and accepted as the extractor message, prefixed by "Archive refused:".' +- type: FINDING + rule_id: P5 + severity: minor + file: 'PLAN.md:Decisions 1' + problem: 'The rootless check is "pass 1 wrote no pharn-install.json", which also fires for a rooted archive without a manifest (pre-7.21.0) and for a deeper prefix such as a/b/.' + evidence: 'Word the message to cover both: "holds no pharn-install.json under a single top-level directory", naming the --prefix line and the 7.21.0 floor. A membership test with an honest message, not a guess about which cause it is.' +- type: FINDING + rule_id: P1 + severity: minor + file: 'PLAN.md:GATE 1 amendments 1' + problem: 'The unknown-capability warning path and the malformed-MIN_CLI refusal need cases of their own.' + evidence: 'Add a manifest edit with an unknown applies token (passes, warns on stderr) and MIN_CLI "not-a-version" (refused, reason named).' +- type: FINDING + rule_id: P7 + severity: minor + file: 'PLAN.md:Files (tar-fixture)' + problem: 'Extending the shared tar fixture changes a file every command suite uses.' + evidence: 'Keep the opts argument optional and part of the memo key, so existing callers produce identical bytes.' +``` + +Verdict: proceed (advisory). All six are folded into the build. diff --git a/.dev/features/core-387-verify-archive/PLAN.md b/.dev/features/core-387-verify-archive/PLAN.md new file mode 100644 index 00000000..1b4eb946 --- /dev/null +++ b/.dev/features/core-387-verify-archive/PLAN.md @@ -0,0 +1,164 @@ +# PLAN — core-387-verify-archive (Linear CORE-387, epic CORE-380) + +- spec_content_hash: bca940a5ad247c120e6d8a3acba119d0d8df51dca275964d0e54c48d729d3c4e # fix #4 +- increment: a new read-only command `pharn verify-archive [--expect-version X.Y.Z]` that runs the + install path's own `extractPharnArchive` (both passes, manifest validation, every listed file's sha256) over a LOCAL + archive, with no network, no project, no lock, into one private temp dir it always removes; exit 0 with a short + summary, exit 1 naming the entry and rule. +- base: `origin/feat/core-386-unpack-listed-paths-only` @ ecd7422f (CORE-386, PR #448; stacked, merged forward with + `git merge`, never rebased). Branch `feat/core-387-verify-archive`. +- layer(s): CLI source (`src/commands/verify-archive.ts` new, `src/lib/cli-args.ts`, `src/index.ts`, + `src/lib/repo.ts`, `src/lib/skills-version.ts`), tests, docs. No trusted doc changes; no protected file. +- version: 0.22.0 (minor: a new command) + a CHANGELOG `[0.22.0]` section. +- constitution_refs: [P0, P2, P3, P4, P5, P7] + +## Why + +pharn-oss v7.25.3–v7.25.5 shipped archives no pharn could install, and nothing in pharn-oss CI could tell before the +tag. CORE-386 made the extractor take a buffer (`extractPharnArchive(archive, dir, checkTree?)`) precisely so a local +file can go through the exact walk a download does. This increment exposes it as a command pharn-oss CI can run on a +`git archive` of the commit about to be tagged. + +## Decisions + +1. **Root directory: REQUIRED (no rootless mode). The documented pharn-oss CI command is** + `git archive --prefix=pharn-oss/ --format=tar.gz -o pharn-oss.tar.gz HEAD`. + Why: the 386 extractor's selection key strips everything up to the first `/` (codeload's `pharn-oss-/`), and + its path rules require one shared root. A plain `git archive HEAD` has top-level entries (`pharn-install.json` + has no `/`, so it is never selected, and `.claude/settings.json` keys as `settings.json`). Accepting that would + need a second path-selection branch in the security-sensitive extractor that the install path never takes, so a + pass would no longer prove "the install would accept these bytes" — the point of the command. `--prefix` makes + the local archive codeload-shaped (pax global header, one root dir, same tar writer: codeload is `git archive`), + so the exact install walk runs. The install path's rules are untouched. + A rootless archive (or any archive without a manifest under one root) fails with a verify-specific message that + names the `--prefix` command, instead of the install path's "older than 7.21.0" text: the command's `checkTree` + (which `extractPharnArchive` runs after pass 1, before the manifest parse) checks that pass 1 wrote + `pharn-install.json`. The Done-when line "a git archive --format=tar.gz HEAD of pharn-oss main" is satisfied by + that line plus `--prefix=pharn-oss/`; the docs and the PR say so plainly. +2. **Option `--expect-version `** (verify-archive only, value option, repeated → refused by the existing + rule). VERSION_RE-validated in `parseCliArgs` (bad value → `Invalid value for --expect-version …`, exit 1, before + anything runs). When given, the tree's SKILLS_VERSION must equal it — the release check `fetchAt` runs for a + release, at the same point (after pass 1, before the manifest parse). No leading `v` is accepted (strict; docs show + `${TAG#v}`). +3. **Shared helper, not a copy:** `skills-version.ts` gains `assertSkillsVersion(repoDir, expected, refusal)` + (reads with `readSkillsVersion`, throws `ManifestValidationError(refusal(found))` on a mismatch). `fetchAt` + calls it with its current message (byte-identical), the command with its own. +4. **No `--json`** (P7): pharn-oss CI gates on the exit code; the one-line summary and the stderr reason are enough. + Recorded as a possible follow-up, not built. +5. **Temp dir lifecycle lives in `repo.ts`** (`verifyLocalArchive(archive, checkTree)`): `mkdtemp` is banned outside + repo.ts/tar-extract.ts by the clone-producer eslint rule, and repo.ts owns the exit/fatal-signal cleanup registry + (`liveClones` + `installCleanupHandlers`). It creates `pharn-verify-*`, registers it, calls + `extractPharnArchive`, and removes + deregisters it in a `finally` (pass and fail). The tree is never returned. +6. **Input read:** `readBoundedFile(path, MAX_ARCHIVE_BYTES)` (bounded-read.ts unchanged: `O_NONBLOCK`, fstat + regular-file, cap, read-to-EOF-under-cap). `MAX_ARCHIVE_BYTES` (32 MiB, the download cap) is exported from + repo.ts. A symlinked input file is followed (the user's own file), as for the config. +7. **Output and errors** (all through `CliError`, exit 1; the path printed via `escapeUnsafe`, and `logError`'s + strip on top): + - missing/unreadable/not-a-file/too-large/empty input → `CliError.error` (a precondition the user fixes; one line): + `Cannot verify : it does not exist.` / `… is not a regular file` / `… is larger than 32 MiB`. + - archive refusal (`TarExtractError`, `ManifestValidationError` incl. `UpstreamManifestError`, and the + expect-version mismatch) → `CliError.failure(err, { message: 'Archive refused: ' })`, so + PHARN_DEBUG=1 dumps the original error as every fetching command does; without it, the one PHARN_DEBUG hint. + - anything else (an fs error writing the temp tree) → `CliError.failure(err)` likewise. + - pass → clack `intro('pharn verify-archive')`, `log.success(': files listed in pharn-install.json, all +present and matching their sha256; SKILLS_VERSION ')` (+ `, as expected` with the option), `outro` dim + "Nothing was installed; the temporary directory was removed." Ref-free (no tag/sha claims). +8. **No Node-floor gate, no MIN_CLI gate, no lock, no proxy notice**: nothing is installed and nothing fetched. + +## Files + +- `src/commands/verify-archive.ts` — NEW: `runVerifyArchive({ file, expectVersion })`: bounded read, the checkTree + (manifest present → else the `--prefix` refusal; then `assertSkillsVersion` when asked), `verifyLocalArchive`, + summary/errors. Imports only lib/ (P3). +- `src/lib/repo.ts` — export `MAX_ARCHIVE_BYTES`; new exported `verifyLocalArchive(archive, checkTree)`; `fetchAt`'s + release check calls `assertSkillsVersion` (same message). +- `src/lib/skills-version.ts` — `assertSkillsVersion(repoDir, expected, refusal)`. +- `src/lib/cli-args.ts` — `verify-archive` in COMMANDS (`args: ''`, a summary and page text); + `expect-version` in OPTIONS (`uses: verify-archive`); `Invocation` variant; parse: the positional is required + (`verify-archive needs the path of a .tar.gz archive`, refused), VERSION_RE check. +- `src/index.ts` — dispatch case (dynamic import, as the others). +- `tests/commands/verify-archive.test.ts` — NEW, via `useHarness` + tar-fixture: pass on a good archive; pass with an + unlisted symlink, hard link and pax header (the v7.25.5 shape) and nothing of them left anywhere; fail naming the + entry for a listed file whose bytes differ from its sha256; a symlink at a listed path (`unsupported type '2'` + + path); no manifest (and the rootless archive) → the `--prefix` message; `--expect-version` match and mismatch; + input that is a directory, a FIFO (`execFileSync('mkfifo')`, the pattern tests/bounded-read.test.ts already uses; + POSIX-only, skipped on win32), oversize (sparse file via `truncateSync` over 32 MiB), empty, nonexistent; + path with a control character printed escaped; `fetchStub` never called in any case; the temp dir (TMPDIR pointed + at a watched dir via `watchClones`) empty after pass and after fail; PHARN_DEBUG=1 prints the original error. +- `tests/support/tar-fixture.ts` — `codeloadArchive` gains an optional third `opts` (`extra` raw entries spliced after + the root dir, `replace` raw entries for a listed path, `rootless: true`), memo key includes opts; existing callers + unchanged. +- `tests/cli-args.test.ts` — new cases: the command parses with its positional; missing positional refused; extra + positional refused; `--expect-version` valid / invalid / repeated / on another command refused; help text bodies + updated where they assert the full usage (no title renamed or removed). +- `tests/index.test.ts` — dispatch case for verify-archive (mock + loaded chunk), added, none renamed. +- `tests/skills-version.test.ts` — `assertSkillsVersion` match/mismatch/missing. +- `tests/repo.test.ts` — `verifyLocalArchive`: removes its dir on pass and on refusal; never fetches. +- `tests/release-consistency.test.ts` — added at the merge of the 386 branch (0.21.6): `v0.21.6` joins KNOWN_TAGS, so the `[0.22.0]` link can compare from it. 0.21.6 is tagged when #448 merges, before this PR can. +- `tests/dist-smoke.test.ts` — the bundle runs `verify-archive` on a fixture archive (exit 0) and on a missing file + (exit 1), and `--help` lists it (body of the existing help case if it enumerates commands). +- `docs/commands/verify-archive.md` — NEW, matching the other command pages: usage, options, behavior, exit codes, + messages, and "For pharn-oss CI" with the exact lines: + `git archive --prefix=pharn-oss/ --format=tar.gz -o "$RUNNER_TEMP/pharn-oss.tar.gz" HEAD` and + `npx --yes @pharn-dev/pharn@0.22.0 verify-archive "$RUNNER_TEMP/pharn-oss.tar.gz" --expect-version "$(cat SKILLS_VERSION)"`. +- `docs/README.md` — the command list gains verify-archive. +- `README.md` — the command list gains verify-archive. +- `docs/troubleshooting.md` — exit-code table row + "verify-archive says the archive has no root directory". +- `docs/architecture.md` — one short flow entry for verify-archive. +- `docs/contributing.md` — module tree line + test-map row. +- `AGENTS.md` — the CLAUDE.md mirror, same edits. +- `CLAUDE.md` — command list, module map (`commands/verify-archive`), test-suite list (minimal). +- `package-lock.json` — 0.22.0. +- `package.json` — 0.22.0 (`npm version --no-git-tag-version 0.22.0`). +- `CHANGELOG.md` — `## [0.22.0]` with an `Added` entry (the 386 `[Unreleased]`/0.21.6 section untouched). +- `.dev/features/core-387-verify-archive/SHIP.md` — stage artifact (each stage scopes its own artifacts). + +## Evals / tests (P1) + +The command suite above is the eval: each refusal asserted by exit code 1 and the named entry/rule on stderr; each +pass by exit code null/0 and the summary; the no-network property by `fetchStub` call count 0; the cleanup property +by an empty watched TMPDIR. + +## Guarantee audit (P0) + +- "verify-archive runs the same checks as an install" → floor: it calls the one `extractPharnArchive` (no copy); + differences named: no MIN_CLI gate, no capability-index parse, no Node floor (docs say so). +- "no network" → test (fetch stub never called); structurally the command imports no fetch module. +- "no write outside one temp dir, always removed" → `finally` in `verifyLocalArchive` + the exit/fatal-signal + registry; tested on pass and fail. SIGKILL residual: same as fetchRepo's (named, LIMITS-level, unchanged). +- "bounded input read, no FIFO hang" → `readBoundedFile` (existing floor, existing tests). +- "a pass on a `--prefix` git archive means codeload's archive of that commit passes" → advisory: same tar writer + (git archive), but codeload could differ (e.g. export-subst); the v7.25.5 live check covers the real codeload shape. + +## Trust audit (P2) + +The archive and its path are untrusted. The path is escaped (`escapeUnsafe`) where printed; archive-derived text +reaches messages only through the extractor's/manifest's own escaping plus `logError`'s strip. Nothing from the +archive is executed; the tree is deleted before the command returns. + +## Risks + +- FIFO test: resolved — tests already create FIFOs with `execFileSync('mkfifo')` (bounded-read, detect-archetype). +- Help-text assertions in cli-args / dist-smoke tests change bodies (never titles; TI01/TI02). +- 386 branch moving: merged forward before commit and before the PR. +- Large sparse oversize file on tmpfs: `truncateSync` makes it sparse, cheap. + +## Open questions (HALT) + +None blocking; GATE 1 is the lead's. + +## GATE 1 amendments (lead decision under the user's delegation, 2026-11-25) + +Approved as written, plus: + +1. **The install's other two pure reads run too.** In the checkTree after pass 1, `readMinCli(dir)` (the reader the + min-cli gate uses) checks MIN_CLI's validity only: absent passes, and a present-but-malformed or unreadable file is + a refusal naming its reason. This is stricter than install, which warns, on purpose: for a release a broken + handshake is a packaging bug. No comparison is made against this CLI's version. After the extract, + `manifestCapabilityIndex(manifest)` (the pure function behind `parseCapabilityIndex`) builds the capability index. + Capabilities it reports as `unknown` are printed with the shared `unknownCapabilitiesWarning` and the command still + passes, because install installs past them (it skips them with a warning). The summary gives the capability count + and MIN_CLI. Neither read touches the network or a prompt. +2. **The docs' CI section** shows a SKILLS_VERSION form for PR/push jobs and a tag form for release jobs + (`--expect-version "${TAG#v}"`), and says the archive must be built from the same commit that will be tagged. +3. **The PR body** carries the exact pharn-oss CI snippet, for CORE-384. diff --git a/.dev/features/core-387-verify-archive/REGRESSION.md b/.dev/features/core-387-verify-archive/REGRESSION.md new file mode 100644 index 00000000..73c38776 --- /dev/null +++ b/.dev/features/core-387-verify-archive/REGRESSION.md @@ -0,0 +1,29 @@ +# REGRESSION — core-387-verify-archive + +- Base: `f9fa96b0ac`, which is origin/main after #448 (CORE-386) merged. Its tree is identical to the 386 branch tip + `ab300d9b`. The baseline ran there in a detached worktree. The branch was cut from 386 and then merged forward + to main (no rebase). +- Inside: the 26 paths in `regression-report.json`. `check-regress.mjs scope` reported `escaped` empty, so nothing + escaped the plan's declared files. `tests/release-consistency.test.ts` was declared in the plan when the 386 + branch merged in. +- Outside gates: + - the 53 stdlib `*.test.mjs` / `*.test.cjs` files, run with `node --test`; + - `node .dev/floor/validate.mjs .`; + - the full vitest suite (through heavy.sh, `--maxWorkers=2`; at HEAD with `--coverage` and `CI=1`). + +| Gate | base | head | +| -------- | ---- | ---- | +| tests | 1 | 1 | +| validate | 0 | 0 | +| vitest | 0 | 0 | + +`regressions[]`: none. + +`pre_existing[]`: `tests`. It is red at the base too, from `.codex/hooks/set-writes-scope.test.cjs`, which this +change does not touch. + +At HEAD, vitest ran 3,722 tests (1 skipped) against 3,680 at the base. Coverage: 98.59 / 95.77 / 99.08 / 99.07 +(statements / branches / functions / lines). The new and changed source files are fully covered. + +REGRESSIONS: none, meaning no breakage outside the feature that these gates can detect (verdict `no-regressions`, +from `check-regress.mjs`). This certifies only the base→head comparison of these gates. diff --git a/.dev/features/core-387-verify-archive/REVIEW.md b/.dev/features/core-387-verify-archive/REVIEW.md new file mode 100644 index 00000000..c09f1259 --- /dev/null +++ b/.dev/features/core-387-verify-archive/REVIEW.md @@ -0,0 +1,47 @@ +# REVIEW — core-387-verify-archive + +Floor first: `node .dev/floor/validate.mjs .` is GREEN, and `verify-report.json` is `PASS`. Everything below is +advisory. The review applied the four lenses (P0 guarantees, P2 trust, P3 one axis, P7 scope) to the diff against +origin/main. + +```yaml +- type: FINDING + rule_id: P0 + severity: minor + file: 'src/commands/verify-archive.ts:runVerifyArchive (rootless hint)' + problem: 'The rootless hint is chosen by matching the start of the extractor''s message ("tar entry has no path below the archive root"), so a rewording in tar-extract.ts would silently drop the hint.' + evidence: 'Only the hint is lost, never the refusal or the exit code, and the rootless case in tests/commands/verify-archive.test.ts asserts both texts, so a rewording turns the suite red. A typed error code on TarExtractError would be cleaner, but it belongs in a tar-extract change, not here.' +- type: FINDING + rule_id: P0 + severity: minor + file: 'docs/commands/verify-archive.md:Where it differs from an install' + problem: 'A pass is "an install accepts these bytes" only for the shared steps.' + evidence: 'The differences are listed: MIN_CLI is refused where install warns, there is no version comparison, and no project or destination checks run. The guarantee audit in PLAN.md labels the git-archive-vs-codeload equivalence advisory, and live run (c) covers the real codeload shape.' +- type: FINDING + rule_id: P2 + severity: minor + file: 'src/commands/verify-archive.ts' + problem: 'Every user-path interpolation must be escaped.' + evidence: 'The path and the basename are escaped once (escapeUnsafe) and only those values are printed; logError strips on top. A test with ESC in both a missing path and a refused archive name asserts that no raw ESC reaches the output.' +- type: FINDING + rule_id: P2 + severity: minor + file: 'src/lib/skills-version.ts:readSkillsVersion (reused)' + problem: 'For a local archive, a missing SKILLS_VERSION reads "is missing in the fetched repo", which is the wrong word for a local file.' + evidence: 'Cosmetic. It is prefixed by "Archive refused:", and changing the shared message would touch every install path. Left as is.' +- type: FINDING + rule_id: P3 + severity: info + file: 'src/commands/verify-archive.ts' + problem: 'Checked for command->command and step imports.' + evidence: "Imports only lib/. Temp-dir lifecycle stays in repo.ts (the clone-producer eslint rule passes), the release check is shared through assertSkillsVersion, and fetchAt's message is byte-identical." +- type: FINDING + rule_id: P7 + severity: info + file: 'src/lib/cli-args.ts' + problem: 'No --json, as decided at GATE 1.' + evidence: 'CI gates on the exit code; --json is refused for verify-archive by the existing per-command option table.' +``` + +There are no blocking findings. The tests file `tests/release-consistency.test.ts` gains `v0.21.6` in KNOWN_TAGS: +that tag now exists (#448 was released), and the `[0.22.0]` link compares from it. diff --git a/.dev/features/core-387-verify-archive/SHIP.md b/.dev/features/core-387-verify-archive/SHIP.md new file mode 100644 index 00000000..3dc61bb2 --- /dev/null +++ b/.dev/features/core-387-verify-archive/SHIP.md @@ -0,0 +1,25 @@ +# SHIP — core-387-verify-archive (Linear CORE-387, epic CORE-380) + +Stages, in order: `/pharn-dev-plan` → GATE 1 → `/pharn-dev-grill` → `/pharn-dev-build` → `/pharn-dev-regress` → +`/pharn-dev-verify` → `/pharn-dev-review` → GATE 2. + +- **GATE 1**, plan acceptance: approved by the epic lead as a **model decision made under the user's delegation**, + not a human approval. The lead added three things, recorded in PLAN.md "GATE 1 amendments": + - the MIN_CLI validity check and the capability-index build; + - the tag form in the CI docs; + - the CI snippet in the PR body. +- `/pharn-dev-grill`: advisory, 6 findings, all folded into the build ([GRILL.md](GRILL.md)). +- `/pharn-dev-build`: `node .dev/floor/validate.mjs .` exit **0**. +- `/pharn-dev-regress`: `regression-report.json` `.verdict` = **`no-regressions`**. Base `f9fa96b0ac` (origin/main + after #448), `pre_existing: ["tests"]` ([REGRESSION.md](REGRESSION.md)). +- `/pharn-dev-verify`: `verify-report.json` `.verdict` = **`PASS`**. The gates were test, validate, lint, + format:check, lint:md, typecheck and build. The live Done-when runs are in [VERIFY.md](VERIFY.md). +- `/pharn-dev-review`: [REVIEW.md](REVIEW.md), advisory, no blocking findings. +- **GATE 2**, the post-review decision: per the lead's standing instruction (a model decision under the user's + delegation), the PR is opened. It is never merged here; the merge belongs to the lead. + +Base history: the branch was cut from `feat/core-386-unpack-listed-paths-only` and merged forward. After #448 +merged, origin/main was merged in, never rebased. + +Chain ran; the named floor verdicts are as shown. This is NOT a judgment that the increment is good or wise; that is +the human's call at the post-review gate. diff --git a/.dev/features/core-387-verify-archive/VERIFY.md b/.dev/features/core-387-verify-archive/VERIFY.md new file mode 100644 index 00000000..9b5ade8b --- /dev/null +++ b/.dev/features/core-387-verify-archive/VERIFY.md @@ -0,0 +1,33 @@ +# VERIFY — core-387-verify-archive + +At HEAD (the feature merged forward onto origin/main `f9fa96b0`): every floor gate exited 0, and +`check-verify.mjs` returned `PASS`. + +| Gate | exit | +| ------------ | ---- | +| test | 0 | +| validate | 0 | +| lint | 0 | +| format:check | 0 | +| lint:md | 0 | +| typecheck | 0 | +| build | 0 | + +There are no committed eval pairs, so no `structural:*` gate ran. Registered verifiers: 0 (`count-verifiers.mjs`), +so no advisory annotations. + +## Live Done-when (bundle `node dist/index.js`, outside the gates) + +`$S` is the session scratchpad (`…/scratchpad/live`). + +| Case | Archive | Result | +| ---- | -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | +| (a) | `git -C pharn-oss archive --prefix=pharn-oss/ --format=tar.gz` of `origin/main` (a2cacaef), with `--expect-version 7.25.5` | exit 0, "616 files … 35 capabilities; SKILLS_VERSION 7.25.5, as expected; MIN_CLI 0.14.0." | +| (b) | (a) extracted, `pharn/CONSTITUTION.md` altered, repacked with ustar `tar` | exit 1, "declares a sha256 for pharn/CONSTITUTION.md that its bytes do not match" | +| (c) | the real codeload `refs/tags/v7.25.5` tarball, with `--expect-version 7.25.5` | exit 0, the same summary | +| (c') | (c) with `--expect-version 7.25.6` | exit 1, "it ships SKILLS_VERSION 7.25.5, not 7.25.6 (--expect-version)" | +| (d) | plain `git archive --format=tar.gz` of `origin/main` (no prefix) | exit 1, "tar entry has no path below the archive root: MIN_CLI. … Re-create it with `git archive --prefix=pharn-oss/ …`" | + +No `pharn-verify-*` directory was left in `$TMPDIR` after these runs. + +VERIFY: PASS on the floor gates. This verdict covers only those gates and the live runs listed here. diff --git a/.dev/features/core-387-verify-archive/regression-report.json b/.dev/features/core-387-verify-archive/regression-report.json new file mode 100644 index 00000000..f67b6449 --- /dev/null +++ b/.dev/features/core-387-verify-archive/regression-report.json @@ -0,0 +1,48 @@ +{ + "base": "f9fa96b0ac", + "inside": [ + ".dev/features/core-387-verify-archive/GRILL.md", + ".dev/features/core-387-verify-archive/PLAN.md", + "AGENTS.md", + "CHANGELOG.md", + "CLAUDE.md", + "README.md", + "docs/README.md", + "docs/architecture.md", + "docs/commands/verify-archive.md", + "docs/contributing.md", + "docs/troubleshooting.md", + "package-lock.json", + "package.json", + "src/commands/verify-archive.ts", + "src/index.ts", + "src/lib/cli-args.ts", + "src/lib/repo.ts", + "src/lib/skills-version.ts", + "tests/cli-args.test.ts", + "tests/commands/verify-archive.test.ts", + "tests/dist-smoke.test.ts", + "tests/index.test.ts", + "tests/release-consistency.test.ts", + "tests/repo.test.ts", + "tests/skills-version.test.ts", + "tests/support/tar-fixture.ts" + ], + "outside_gates": { + "tests": { + "base": 1, + "head": 1 + }, + "validate": { + "base": 0, + "head": 0 + }, + "vitest": { + "base": 0, + "head": 0 + } + }, + "regressions": [], + "pre_existing": ["tests"], + "verdict": "no-regressions" +} diff --git a/.dev/features/core-387-verify-archive/verify-report.json b/.dev/features/core-387-verify-archive/verify-report.json new file mode 100644 index 00000000..c7729620 --- /dev/null +++ b/.dev/features/core-387-verify-archive/verify-report.json @@ -0,0 +1,14 @@ +{ + "feature": "core-387-verify-archive", + "gates": { + "build": 0, + "format:check": 0, + "lint": 0, + "lint:md": 0, + "test": 0, + "typecheck": 0, + "validate": 0 + }, + "verdict": "PASS", + "failing_gates": [] +} diff --git a/AGENTS.md b/AGENTS.md index fd93b89f..d21c0d6f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,7 +9,8 @@ Guidance for Codex in this repository. Flows: [`docs/architecture.md`](docs/arch (by default the newest verified release; `--ref main` takes the tip of `main`), copies the selected capabilities (grillers and lenses) and the fixed product surfaces into `.Codex/` and `pharn/`, and writes pharn.config.json and pharn.records.json in that project. It is published on npm as `@pharn-dev/pharn` with one bin, `pharn`. Every command is -archetype-only: a pre-archetype (module) config is refused with "re-run `pharn init`". It targets Codex today. +archetype-only: a pre-archetype (module) config is refused with "re-run `pharn init`". `verify-archive` reads no project: +it runs the install checks over a local pharn-oss archive, for pharn-oss CI. It targets Codex today. ## Commands @@ -100,7 +101,7 @@ PHARN_DEBUG=1 npm run dev -- init # full error output for fetch/install failur own archive, extracted-size and entry caps. - **The project lock.** `init`/`add`/`update`/`remove`/`uninstall` take `pharn/.lock` before reading the config, hold it across every prompt and plan once; edits made meanwhile are caught at write time (hash, fingerprint, walk). Dry - runs and readers (`list`, `status`) never take it. + runs and readers (`list`, `status`, `verify-archive`) never take it. - **Bounded local reads.** pharn.config.json, pharn.records.json and the lock are read through `readBoundedFile` (regular file, size cap, `O_NONBLOCK`), so a FIFO or a huge file never hangs or floods a command. - **Config schema is additive within the support window** (P7): new keys are optional, and a legacy field loads @@ -115,7 +116,7 @@ PHARN_DEBUG=1 npm run dev -- init # full error output for fetch/install failur ## Module map - `src/index.ts`: dispatch only. `lib/cli-args.ts`: the command/option tables, help text and the argv parse (`init` default). -- `commands/`: one verb each (`init`, `add`, `remove`/`rm`, `update`, `list`, `status`, `uninstall`). +- `commands/`: one verb each (`init`, `add`, `remove`/`rm`, `update`, `list`, `status`, `uninstall`, `verify-archive`). - `steps/`: init stages (`node-prereq`, `prereqs`, `archetype-summary`, `overwrite-check`, `install-archetype`), `add-picker`. - Fetch boundary: `fetch-capped` (the one bounded GET), `release` (which commit), `repo` + `tar-extract`, `skills-version`, `min-cli-gate`, `upstream-manifest` (the upstream install manifest's one parser), `capability-index` (manifest → @@ -137,7 +138,7 @@ PHARN_DEBUG=1 npm run dev -- init # full error output for fetch/install failur ## Testing - Vitest, node env. Lib tests are `tests/*.test.ts`; command suites are `tests/commands/` (`init`, `init-dry-run`, `add`, - `remove`, `update`, `update-dry-run`, `status`, `list`, `uninstall`, `lock`, `clone-cleanup`, `older-cli`). Update the test first. + `remove`, `update`, `update-dry-run`, `status`, `list`, `uninstall`, `verify-archive`, `lock`, `clone-cleanup`, `older-cli`). Update the test first. - A command suite runs the real `run()` on a temp project via `tests/support/harness.ts`. Only two boundaries are replaced: global `fetch`, which serves a real codeload tarball (`tests/support/tar-fixture.ts`), and `@clack/prompts` (`tests/support/clack-stub.ts`), where an unscripted prompt throws. diff --git a/CHANGELOG.md b/CHANGELOG.md index a3135dec..4c11c96c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,12 @@ Releases 0.4.0 and older are in [CHANGELOG-ARCHIVE.md](CHANGELOG-ARCHIVE.md). ## [Unreleased] +## [0.22.0] — 2026-11-25 + +### Added + +- **`pharn verify-archive ` checks a local pharn-oss `.tar.gz` the way an install checks a download, with no network.** It is for pharn-oss CI, which can now find out that a commit would install before it tags that commit as a release. It runs the install's own steps on the file: both extraction passes, the `pharn-install.json` validation, the sha256 of every listed file and the capability index. With `--expect-version X.Y.Z`, the archive's `SKILLS_VERSION` must also equal that version, as a release install requires of its tag. A `MIN_CLI` that is present but not a valid version fails the check, where an install would warn and carry on. The command needs no project and takes no lock. It reads the file only if it is a regular file of at most 32 MiB, and it removes its one temporary directory whether the check passes or fails. It exits 0 with a one-line summary, or 1 with the reason, which names the entry and the rule. The archive must have one top-level directory, as GitHub's do, so build it with `git archive --prefix=pharn-oss/ --format=tar.gz -o pharn-oss.tar.gz HEAD`. See [`docs/commands/verify-archive.md`](docs/commands/verify-archive.md) for the pharn-oss CI lines. + ## [0.21.7] — 2026-11-25 ### Fixed @@ -535,7 +541,8 @@ _Never released: 0.9.0 followed on the same day, so `0.8.0` was neither tagged n matcher that silently stopped matching, or a comparator read in the wrong direction, would otherwise leave every assertion green. -[Unreleased]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.7...HEAD +[Unreleased]: https://github.com/pharn-dev/pharn-cli/compare/v0.22.0...HEAD +[0.22.0]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.7...v0.22.0 [0.21.7]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.6...v0.21.7 [0.21.6]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.5...v0.21.6 [0.21.5]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.4...v0.21.5 diff --git a/CLAUDE.md b/CLAUDE.md index 54d1a29e..065ef597 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,7 +9,8 @@ Guidance for Claude Code in this repository. Flows: [`docs/architecture.md`](doc (by default the newest verified release; `--ref main` takes the tip of `main`), copies the selected capabilities (grillers and lenses) and the fixed product surfaces into `.claude/` and `pharn/`, and writes pharn.config.json and pharn.records.json in that project. It is published on npm as `@pharn-dev/pharn` with one bin, `pharn`. Every command is -archetype-only: a pre-archetype (module) config is refused with "re-run `pharn init`". It targets Claude Code today. +archetype-only: a pre-archetype (module) config is refused with "re-run `pharn init`". `verify-archive` reads no project: +it runs the install checks over a local pharn-oss archive, for pharn-oss CI. It targets Claude Code today. ## Commands @@ -104,7 +105,7 @@ PHARN_DEBUG=1 npm run dev -- init # full error output for fetch/install failur own archive, headers-scanned, decompressed-bytes-scanned and bytes-written caps. - **The project lock.** `init`/`add`/`update`/`remove`/`uninstall` take `pharn/.lock` before reading the config, hold it across every prompt and plan once; edits made meanwhile are caught at write time (hash, fingerprint, walk). Dry - runs and readers (`list`, `status`) never take it. + runs and readers (`list`, `status`, `verify-archive`) never take it. - **Bounded local reads.** pharn.config.json, pharn.records.json and the lock are read through `readBoundedFile` (regular file, size cap, `O_NONBLOCK`), so a FIFO or a huge file never hangs or floods a command. - **Config schema is additive within the support window** (P7): new keys are optional, and a legacy field loads @@ -119,7 +120,7 @@ PHARN_DEBUG=1 npm run dev -- init # full error output for fetch/install failur ## Module map - `src/index.ts`: dispatch only. `lib/cli-args.ts`: the command/option tables, help text and the argv parse (`init` default). -- `commands/`: one verb each (`init`, `add`, `remove`/`rm`, `update`, `list`, `status`, `uninstall`). +- `commands/`: one verb each (`init`, `add`, `remove`/`rm`, `update`, `list`, `status`, `uninstall`, `verify-archive`). - `steps/`: init stages (`node-prereq`, `prereqs`, `archetype-summary`, `overwrite-check`, `install-archetype`), `add-picker`. - Fetch boundary: `fetch-capped` (the one bounded GET), `release` (which commit), `repo` + `tar-extract`, `archive-refusal` (the refused-archive message), `skills-version`, @@ -145,7 +146,7 @@ PHARN_DEBUG=1 npm run dev -- init # full error output for fetch/install failur ## Testing - Vitest, node env. Lib tests are `tests/*.test.ts`; command suites are `tests/commands/` (`init`, `init-dry-run`, `add`, - `remove`, `update`, `update-dry-run`, `update-interrupted`, `status`, `list`, `uninstall`, `lock`, `clone-cleanup`, `older-cli`). Update the test first. + `remove`, `update`, `update-dry-run`, `update-interrupted`, `status`, `list`, `uninstall`, `verify-archive`, `lock`, `clone-cleanup`, `older-cli`). Update the test first. - A command suite runs the real `run()` on a temp project via `tests/support/harness.ts`. Only two boundaries are replaced: global `fetch`, which serves a real codeload tarball (`tests/support/tar-fixture.ts`), and `@clack/prompts` (`tests/support/clack-stub.ts`), where an unscripted prompt throws. diff --git a/README.md b/README.md index b7bcefb8..89297dd5 100644 --- a/README.md +++ b/README.md @@ -138,17 +138,18 @@ commits a green result to a new local branch (never pushed or merged), leaving t ## CLI commands -| Command | Description | -| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `pharn init` | Detect archetypes and install matching capabilities. This is also the default when no command is given. `--dry-run` prints what it would install and writes nothing (add `--json` for one machine-readable object); `--yes`/`-y` installs without prompts, but only when no file would be overwritten. | -| `pharn add [capability]` | Add one capability manually, for example `a11y` or `lens:n-plus-one`. With no argument, opens an interactive picker. | -| `pharn remove [capability]` | Remove one installed capability. With no argument, opens an interactive picker. | -| `pharn update` | Re-fetch and apply the latest PHARN content using drift-safe per-file decisions. `--force` overwrites files you changed; `--yes`/`-y` skips the confirmation prompt; `--dry-run` prints what it would do and writes nothing (add `--json` for the plan as one machine-readable object, and `--compact` to leave the unchanged files out of it). | -| `pharn list` | Show installed archetypes and capabilities. Use `--json` for machine-readable output. | -| `pharn status` | Read-only version and drift report. Use `--strict` to make drift fail CI, `--no-drift` to skip byte comparison, or `--json` for one machine-readable report. | -| `pharn uninstall` | Remove PHARN: deletes only the files `pharn` recorded and you did not change, then `pharn.records.json` and `pharn.config.json` (backed up first). Never touches `pharn/.backup/` or a `.claude/settings.json` it did not create. `--yes`/`-y` skips the confirmation prompt. | -| `pharn --help` | Show every command, option and environment variable. `pharn --help` shows one command and only the options it takes. | -| `pharn --version` | Show the installed CLI version. | +| Command | Description | +| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `pharn init` | Detect archetypes and install matching capabilities. This is also the default when no command is given. `--dry-run` prints what it would install and writes nothing (add `--json` for one machine-readable object); `--yes`/`-y` installs without prompts, but only when no file would be overwritten. | +| `pharn add [capability]` | Add one capability manually, for example `a11y` or `lens:n-plus-one`. With no argument, opens an interactive picker. | +| `pharn remove [capability]` | Remove one installed capability. With no argument, opens an interactive picker. | +| `pharn update` | Re-fetch and apply the latest PHARN content using drift-safe per-file decisions. `--force` overwrites files you changed; `--yes`/`-y` skips the confirmation prompt; `--dry-run` prints what it would do and writes nothing (add `--json` for the plan as one machine-readable object, and `--compact` to leave the unchanged files out of it). | +| `pharn list` | Show installed archetypes and capabilities. Use `--json` for machine-readable output. | +| `pharn status` | Read-only version and drift report. Use `--strict` to make drift fail CI, `--no-drift` to skip byte comparison, or `--json` for one machine-readable report. | +| `pharn uninstall` | Remove PHARN: deletes only the files `pharn` recorded and you did not change, then `pharn.records.json` and `pharn.config.json` (backed up first). Never touches `pharn/.backup/` or a `.claude/settings.json` it did not create. `--yes`/`-y` skips the confirmation prompt. | +| `pharn verify-archive ` | Check a local pharn-oss `.tar.gz` the way an install checks a download, with no network (for pharn-oss CI; [details](docs/commands/verify-archive.md)). `--expect-version X.Y.Z` also checks `SKILLS_VERSION`. | +| `pharn --help` | Show every command, option and environment variable. `pharn --help` shows one command and only the options it takes. | +| `pharn --version` | Show the installed CLI version. | `init` also takes `--archetype ` (for example `--archetype ssr,backend`) to install for those archetypes instead of the detected ones; the choice is recorded, so `update` keeps it. `init --ref main` diff --git a/docs/README.md b/docs/README.md index 9dc592f0..67b3412b 100644 --- a/docs/README.md +++ b/docs/README.md @@ -19,6 +19,7 @@ The CLI version (`pharn --version`) and the content version it installs (`skills - [update](commands/update.md) — re-fetch installed capabilities at the latest skills version - [list](commands/list.md) — list installed archetypes + capabilities - [status](commands/status.md) — read-only version + local-drift check; `--strict` exits 1 on an outdated install, a modified, missing or unreadable file, a surface upstream no longer ships, or an unwired hook ([the full list](commands/status.md#strict-conditions)), and neither `status` nor `list` is ever blocked by another `pharn` run's lock +- [verify-archive](commands/verify-archive.md) — check a local pharn-oss `.tar.gz` as an install would, with no network (for pharn-oss CI) ## Reference diff --git a/docs/architecture.md b/docs/architecture.md index c00dbac1..c4b7936b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -253,6 +253,18 @@ prompt was open (a file now byte-identical to upstream is not a change), then ap capability is handled by the one planner. "Up to date" is a plan that changes nothing (`changesNothing`); only the ahead-of-source guard returns before the download. +## `verify-archive` (`commands/verify-archive.ts`) + +The fetch boundary without the fetch, for pharn-oss CI. The command reads the file through `readBoundedFile` +(a regular file of at most `MAX_ARCHIVE_BYTES`, the download cap) and hands the bytes to `verifyLocalArchive` +(`lib/repo.ts`). That function makes a private `pharn-verify-*` temp dir, registers it with the same exit and +fatal-signal backstop as a clone, and runs `extractPharnArchive`, the function `fetchAt` calls after a +download. Its `checkTree`, run after the first pass, requires `pharn-install.json`: the archive must have one +root directory (`git archive --prefix=pharn-oss/`). With `--expect-version` it checks SKILLS_VERSION through +the release check's `assertSkillsVersion`, then refuses a present but unusable `MIN_CLI`. After the extraction +it builds the capability index with `manifestCapabilityIndex`. The temp dir is removed in a `finally`, and the +tree is never returned. No network, no project, no lock. + ## Root footprint - The lock is `pharn/.lock` and backups go to `pharn/.backup//` in every layout. diff --git a/docs/commands/verify-archive.md b/docs/commands/verify-archive.md new file mode 100644 index 00000000..d903a9dc --- /dev/null +++ b/docs/commands/verify-archive.md @@ -0,0 +1,120 @@ +# pharn verify-archive + +Check a **local** pharn-oss `.tar.gz` the way `pharn init` and `pharn update` check a download, without +installing anything. It exists so that pharn-oss CI can find out that a commit would install before +that commit is tagged as a release. It makes **no network request**, needs no project and takes no lock. +Its only write is one temporary directory, which it removes whether the check passes or fails. + +```bash +pharn verify-archive pharn-oss.tar.gz # does an install accept these bytes? +pharn verify-archive pharn-oss.tar.gz --expect-version 7.25.6 # ...and is SKILLS_VERSION 7.25.6? +``` + +## The archive must have one top-level directory + +`pharn` reads archives shaped like GitHub's codeload tarballs: a pax global header, then everything under +one root directory (`pharn-oss-/`). A plain `git archive HEAD` puts its entries at the top level. The +extractor refuses a file it reads that has no directory above it (`tar entry has no path below the archive +root`), and the check fails with a message that names the fix. Build the archive with a prefix: + +```bash +git archive --prefix=pharn-oss/ --format=tar.gz -o pharn-oss.tar.gz HEAD +``` + +The prefix is required on purpose. The install path removes the first path component and requires every +installed entry to share it. A mode that accepted a rootless archive would run a selection the install +path never runs, so a pass would no longer mean that an install accepts the bytes. codeload builds its +tarballs with `git archive` too, so a prefixed local archive goes through the same checks a download does. + +## What it checks + +It runs the extractor and manifest checks an install runs, in the same order: + +1. It reads the file only if it is a regular file of at most **32 MiB** (the download cap). It never + blocks on a FIFO. A symlink to a file is followed. +2. **First pass:** it unpacks only the four files `pharn` reads itself (`pharn-install.json`, + `SKILLS_VERSION`, `MIN_CLI`, `.claude/settings.json`). It skips every other entry without writing it, + whatever its type, so a symlink outside the install list is not a failure. +3. **Tree checks:** + - `pharn-install.json` must be present (see above). + - With `--expect-version`, `SKILLS_VERSION` must equal the given version. This is the check an install + makes against a release tag. + - `MIN_CLI`, if present, must be a valid version. +4. **The manifest** is validated by the install's one parser: schema, layout, capabilities, file paths + and destinations. +5. **Second pass:** it unpacks only the paths the manifest lists. Each must be a regular file with a safe + path, appear once, and not follow a pax or GNU long-name header. +6. **Every listed file's sha256** must match the manifest. A listed file that is missing or altered fails + the check. +7. **The capability index** is built from the manifest, as an install builds it. If a capability's + `applies` holds a token this `pharn` does not know, an install skips that capability with a warning. + `verify-archive` prints the same warning on stderr and still passes. + +### Where it differs from an install + +- An install warns about an unusable `MIN_CLI` and carries on. `verify-archive` **fails**, because a + release whose `MIN_CLI` no `pharn` can read has a packaging bug. +- It does not compare `MIN_CLI` with its own version. +- It does not detect archetypes, select capabilities or look at any project, so the destination checks + (symlinks, records, overwrites) are not run. + +## Output and exit codes + +On a pass it exits **0** and prints one line naming the file, the number of files `pharn-install.json` +lists, the capability count, `SKILLS_VERSION` and `MIN_CLI`, for example: + +```text +pharn-oss.tar.gz: 616 files listed in pharn-install.json, all present and matching their sha256; 35 capabilities; SKILLS_VERSION 7.25.5, as expected; MIN_CLI 0.14.0. +``` + +It exits **1** in these cases: + +| Case | Message (stderr) | +| ------------------------------------------------------- | ----------------------------------------------------------------------------------------- | +| The path does not exist | `Cannot verify : it does not exist.` | +| It is a directory, a FIFO or another non-file | `Cannot verify : it is not a regular file.` | +| It is larger than 32 MiB | `Cannot verify : it is larger than 32 MiB.` | +| It is empty | `Cannot verify : it is empty.` | +| The archive is refused (an entry, the manifest, a hash) | `⚠ Archive refused: `, plus the `PHARN_DEBUG` hint | +| No root directory (a plain `git archive`) | `⚠ Archive refused: tar entry has no path below the archive root: …`, then the fix | +| No `pharn-install.json` under one root directory | `⚠ Archive refused: it holds no pharn-install.json under a single top-level …` | +| `--expect-version` differs | `⚠ Archive refused: it ships SKILLS_VERSION , not (--expect-…)` | + +`PHARN_DEBUG=1` prints the original error with its stack, as it does for every other command. Paths are +printed with control characters escaped. + +## Options + +- `--expect-version `: also require the archive's `SKILLS_VERSION` to equal this version, as a + release install does against its tag. Give it as `X.Y.Z`: a leading `v` is refused. A repeated value is + refused too. + +`verify-archive` takes no other option. `--json` and every other command's options are refused with +``Unsupported option for `verify-archive` `` (exit **1**), and so is a second path. + +## For pharn-oss CI + +Build the archive from **the same commit that will be tagged**: what passes is that commit's bytes. Pin +the `pharn` version, so the check does not change under you when a new `pharn` ships. + +On a pull request or a push, check the commit against its own `SKILLS_VERSION`: + +```bash +git archive --prefix=pharn-oss/ --format=tar.gz -o "$RUNNER_TEMP/pharn-oss.tar.gz" HEAD +npx --yes @pharn-dev/pharn@0.22.0 verify-archive "$RUNNER_TEMP/pharn-oss.tar.gz" --expect-version "$(cat SKILLS_VERSION)" +``` + +In a release job, before the tag is pushed, check the commit against the tag you are about to create +(`TAG=v7.25.6`, for example): + +```bash +git archive --prefix=pharn-oss/ --format=tar.gz -o "$RUNNER_TEMP/pharn-oss.tar.gz" HEAD +npx --yes @pharn-dev/pharn@0.22.0 verify-archive "$RUNNER_TEMP/pharn-oss.tar.gz" --expect-version "${TAG#v}" +``` + +`pharn` needs Node 24.2.0 or newer. + +## Related + +- [init](init.md) and [update](update.md), which run the same checks on a download +- [Troubleshooting](../troubleshooting.md#verify-archive-says-the-archive-has-no-top-level-directory) diff --git a/docs/contributing.md b/docs/contributing.md index 6f0fd736..ee7d7dcc 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -128,7 +128,7 @@ The v0.20.0 rows, the `modules` row of v0.21.0 and the `flat` and root-footprint pharn-cli/ src/ index.ts CLI entry, command routing - commands/ init, add, remove, update, list, status, uninstall + commands/ init, add, remove, update, list, status, uninstall, verify-archive steps/ init stages (prereqs, node-prereq, overwrite-check, archetype-summary, install-archetype), add-picker lib/ install-capabilities, install-manifest, capability-index, resolve-capabilities, detect-archetype, node-floor, release, archetype, layout, repo, tar-extract, archive-refusal, diff, skills-version, min-cli-gate, semver, older-cli, pharn-config, model-config(-format), models-update, upstream-models, install-records, update-decision, update-render, apply-update, merge-capabilities, dest-drift, backup, atomic-write, project-lock, proxy-env(-format), symlink-guard, capability-address, capability-groups, capability-picker, unknown-capabilities, cli-error, report-error, hash, validate, constants, banner, format types.ts Archetype / CapabilityEntry / Selection / PharnConfig @@ -217,6 +217,7 @@ Two rules that are easy to get wrong: | `commands/uninstall.test.ts` / `uninstall-plan.test.ts` | `runUninstall` end to end (refusals, confirm, lock, resumable failure); which recorded files may be deleted | | `orphans.test.ts` | Which recorded files are orphaned (install roots, dropped/frozen excluded); the `ORPHANED` note | | `commands/list.test.ts` / `commands/status.test.ts` | Read-only inventory + version/drift audit | +| `commands/verify-archive.test.ts` | `verify-archive` end to end: a pass (incl. unlisted symlinks), each refusal naming its entry, `--expect-version`, the input-path checks, no fetch, the temp dir removed | | `diff.test.ts` | `diffInstalledCapabilities` expected-set derivation + content compare, incl. a real `git -c core.autocrlf=true` checkout | | `hash.test.ts` | The content hash: the CRLF→LF fold for text and the 8000-byte NUL sniff | | `layout.test.ts` | `detectLayout` (refuses a `flat` clone) / `layoutPaths` | diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 338da3fd..4fc6dc5b 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -22,22 +22,24 @@ | `add` refused on a skills-version mismatch | 1 | | `update --force` aborted because a backup could not be written | 1 | | `uninstall` refused, or stopped part-way (see [`uninstall`](commands/uninstall.md)) | 1 | +| `verify-archive` refused the archive, or could not read the file (see [`verify-archive`](commands/verify-archive.md)) | 1 | | Interrupted by Ctrl-C (`SIGINT`) or `SIGTERM` (a `timeout`, `docker stop`); the project may be partial | 130 or 143 | ## Common problems -| Symptom | See | -| ------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | -| `update` listed files under `SKIPPED` or `held` | [`pharn update` skipped my files](#pharn-update-skipped-my-files) | -| `Another pharn process is writing to this project` | [Another pharn process is running](#another-pharn-process-is-running) | -| `No pharn.config.json found. Run pharn init first.` | [`add` / `update` say to run init first](#add--update-say-to-run-init-first) | -| `Could not resolve the latest verified … release` | [No verified release could be resolved](#no-verified-release-could-be-resolved) | -| `Failed to fetch`, a timeout, or a proxy notice | [Capabilities could not be fetched](#capabilities-could-not-be-fetched) | -| `pharn-oss release … was refused` / `pharn-oss main … was refused` | [The pharn-oss archive was refused](#the-pharn-oss-archive-was-refused) | -| `… outside the paths pharn installs; refusing this release` | [A pharn-oss release was refused](#a-pharn-oss-release-was-refused) | -| The wrong archetypes were detected | [Detection picked the wrong archetype](#detection-picked-the-wrong-archetype) | -| `Unknown option` / ``Unsupported option for `` `` | [Unsupported option for this command](#unsupported-option-for-this-command) | -| Your Prettier check fails on PHARN's files | [My Prettier check fails on PHARN's files](#my-prettier-check-fails-on-pharns-files) | +| Symptom | See | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | +| `update` listed files under `SKIPPED` or `held` | [`pharn update` skipped my files](#pharn-update-skipped-my-files) | +| `Another pharn process is writing to this project` | [Another pharn process is running](#another-pharn-process-is-running) | +| `No pharn.config.json found. Run pharn init first.` | [`add` / `update` say to run init first](#add--update-say-to-run-init-first) | +| `Could not resolve the latest verified … release` | [No verified release could be resolved](#no-verified-release-could-be-resolved) | +| `Failed to fetch`, a timeout, or a proxy notice | [Capabilities could not be fetched](#capabilities-could-not-be-fetched) | +| `pharn-oss release … was refused` / `pharn-oss main … was refused` | [The pharn-oss archive was refused](#the-pharn-oss-archive-was-refused) | +| `… outside the paths pharn installs; refusing this release` | [A pharn-oss release was refused](#a-pharn-oss-release-was-refused) | +| The wrong archetypes were detected | [Detection picked the wrong archetype](#detection-picked-the-wrong-archetype) | +| `Unknown option` / ``Unsupported option for `` `` | [Unsupported option for this command](#unsupported-option-for-this-command) | +| Your Prettier check fails on PHARN's files | [My Prettier check fails on PHARN's files](#my-prettier-check-fails-on-pharns-files) | +| `verify-archive`: `tar entry has no path below the archive root` or `holds no pharn-install.json` | [verify-archive says the archive has no top-level directory](#verify-archive-says-the-archive-has-no-top-level-directory) | ## Node version @@ -472,6 +474,20 @@ hunt for a typo): takes no value (`Option takes no value: "--json=false"`), `--ref` and `--archetype` may each be given once (`Repeated option: "--ref"`), and `--no-drift` is the only negated option (`--no-dry-run`, `--no-yes` and `--no-ref` are `Unknown option`). +## verify-archive says the archive has no top-level directory + +`pharn verify-archive` reads archives shaped like GitHub's, with every entry under one root directory. A +plain `git archive HEAD` has none, so the check fails with `tar entry has no path below the archive root` +and names the fix. Build the archive with a prefix: + +```bash +git archive --prefix=pharn-oss/ --format=tar.gz -o pharn-oss.tar.gz HEAD +``` + +An archive under a deeper prefix (`a/b/`), or a pharn-oss older than 7.21.0, which ships no +`pharn-install.json`, fails with `holds no pharn-install.json under a single top-level directory`. See +[`verify-archive`](commands/verify-archive.md#the-archive-must-have-one-top-level-directory). + ## Removing PHARN by hand [`pharn uninstall`](commands/uninstall.md) removes PHARN whenever `pharn.records.json` is usable. Without diff --git a/package-lock.json b/package-lock.json index 232b53f5..2b0b8d01 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@pharn-dev/pharn", - "version": "0.21.7", + "version": "0.22.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@pharn-dev/pharn", - "version": "0.21.7", + "version": "0.22.0", "license": "Apache-2.0", "dependencies": { "@clack/prompts": "^1.8.1", diff --git a/package.json b/package.json index fea4285f..aab72d36 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@pharn-dev/pharn", - "version": "0.21.7", + "version": "0.22.0", "description": "Install and update PHARN in any git project. PHARN gets features shipped right with Claude Code, with spec, plan and checks kept in Git.", "keywords": [ "claude-code", diff --git a/src/commands/verify-archive.ts b/src/commands/verify-archive.ts new file mode 100644 index 00000000..57cabedf --- /dev/null +++ b/src/commands/verify-archive.ts @@ -0,0 +1,151 @@ +import { existsSync } from 'node:fs'; +import { basename } from 'node:path'; +import { intro, log, outro } from '@clack/prompts'; +import pc from '../lib/color.js'; +import { readBoundedFile } from '../lib/bounded-read.js'; +import { CliError } from '../lib/cli-error.js'; +import { MIN_CLI_FILE, SKILLS_VERSION_FILE } from '../lib/constants.js'; +import { MAX_ARCHIVE_BYTES, verifyLocalArchive } from '../lib/repo.js'; +import { + assertSkillsVersion, + readMinCli, + readSkillsVersion, +} from '../lib/skills-version.js'; +import { TarExtractError } from '../lib/tar-extract.js'; +import { escapeUnsafe } from '../lib/terminal-safe.js'; +import { unknownCapabilitiesWarning } from '../lib/unknown-capabilities.js'; +import { + MANIFEST_FILE, + manifestCapabilityIndex, +} from '../lib/upstream-manifest.js'; +import type { UpstreamManifest } from '../lib/upstream-manifest.js'; +import { ManifestValidationError, safeJoin } from '../lib/validate.js'; + +// `pharn verify-archive `: the install path's own checks over a +// LOCAL pharn-oss archive, so pharn-oss CI can prove a commit installs before +// it is tagged. The same `extractPharnArchive` a download goes through (both +// passes, the manifest's one parser, every listed sha256), plus the two pure +// reads an install makes of the tree: MIN_CLI (validity only) and the +// capability index. No network, no project, no lock; the only write is the +// temp tree `verifyLocalArchive` (lib/repo.ts) creates and always removes. + +export interface VerifyArchiveOptions { + file: string; + expectVersion: string | undefined; +} + +/** What the checks found, read while the tree still exists. */ +interface Found { + skillsVersion: string; + minCli: string | null; +} + +// The pinned CI line, named in the rootless refusal and the docs. +const ARCHIVE_COMMAND = + 'git archive --prefix=pharn-oss/ --format=tar.gz -o pharn-oss.tar.gz HEAD'; +const ROOTLESS = 'tar entry has no path below the archive root'; +const ROOTLESS_HINT = `pharn reads archives shaped like GitHub's, with one top-level directory (as \`git archive --prefix=\` writes); a plain \`git archive\` has none. Re-create it with \`${ARCHIVE_COMMAND}\`.`; + +export async function runVerifyArchive( + opts: VerifyArchiveOptions, +): Promise { + // The path is user input: escaped value by value wherever it is printed. + const shown = escapeUnsafe(opts.file); + const name = escapeUnsafe(basename(opts.file)); + const archive = readArchive(opts.file, shown); + + intro('pharn verify-archive'); + const found: Found = { skillsVersion: '', minCli: null }; + let manifest: UpstreamManifest; + try { + manifest = await verifyLocalArchive(archive, (tree) => { + checkTree(tree, opts.expectVersion, found); + }); + } catch (err) { + if ( + err instanceof TarExtractError || + err instanceof ManifestValidationError + ) { + // A plain `git archive` puts SKILLS_VERSION and the manifest at the top + // level, and the extractor refuses a selected path with no root above + // it. That refusal is named by its message (the extractor's own text, + // pinned by the rootless case in this command's suite). + const hint = + err instanceof TarExtractError && err.message.startsWith(ROOTLESS) + ? `. ${ROOTLESS_HINT}` + : ''; + throw CliError.failure(err, { + message: `Archive ${name} refused: ${err.message}${hint}`, + }); + } + throw CliError.failure(err); + } + + // The index an install builds from the manifest. A capability whose + // `applies` this CLI cannot read is skipped by an install with a warning, + // so it warns here and still passes. + const index = manifestCapabilityIndex(manifest); + const skipped = unknownCapabilitiesWarning(index.unknown); + if (skipped) log.warn(skipped); + + const version = + opts.expectVersion === undefined + ? `${SKILLS_VERSION_FILE} ${found.skillsVersion}` + : `${SKILLS_VERSION_FILE} ${found.skillsVersion}, as expected`; + const minCli = found.minCli === null ? 'none' : found.minCli; + log.success( + `${name}: ${manifest.files.length} files listed in ${MANIFEST_FILE}, all present and matching their sha256; ${index.capabilities.length} capabilities; ${version}; ${MIN_CLI_FILE} ${minCli}.`, + ); + outro(pc.dim('Nothing was installed; the temporary directory was removed.')); +} + +/** The archive's bytes, bounded: a regular file within the download cap. */ +function readArchive(file: string, shown: string): Buffer { + const read = readBoundedFile(file, MAX_ARCHIVE_BYTES); + if (read.kind === 'absent') { + throw CliError.error(`Cannot verify ${shown}: it does not exist.`); + } + if (read.kind === 'unusable') { + throw CliError.error(`Cannot verify ${shown}: it ${read.reason}.`); + } + if (read.bytes.length === 0) { + throw CliError.error(`Cannot verify ${shown}: it is empty.`); + } + return read.bytes; +} + +/** + * Run after the first pass, which wrote only the files the CLI reads itself: + * the manifest must be there (else the archive has no single top-level + * directory, or predates the manifest), then the optional version check, then + * MIN_CLI's validity. + */ +function checkTree( + tree: string, + expectVersion: string | undefined, + found: Found, +): void { + if (!existsSync(safeJoin(tree, MANIFEST_FILE))) { + throw new ManifestValidationError( + `it holds no ${MANIFEST_FILE} under a single top-level directory. ${ROOTLESS_HINT} A pharn-oss older than 7.21.0 ships no ${MANIFEST_FILE} at all.`, + ); + } + if (expectVersion !== undefined) { + assertSkillsVersion( + tree, + expectVersion, + (v) => + `it ships ${SKILLS_VERSION_FILE} ${escapeUnsafe(v)}, not ${expectVersion} (--expect-version).`, + ); + } + found.skillsVersion = readSkillsVersion(tree); + // Stricter than an install, which warns and carries on: for a release, a + // MIN_CLI no pharn can read is a packaging bug. + const minCli = readMinCli(tree); + if (minCli.warning !== null) { + throw new ManifestValidationError( + `its ${MIN_CLI_FILE} is present but unusable; an install would warn: ${minCli.warning}`, + ); + } + found.minCli = minCli.version; +} diff --git a/src/index.ts b/src/index.ts index 36a86c43..e0267dcb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -64,6 +64,11 @@ export async function main( await runUninstall(invocation.options); return; } + case 'verify-archive': { + const { runVerifyArchive } = await import('./commands/verify-archive.js'); + await runVerifyArchive(invocation.options); + return; + } } } diff --git a/src/lib/cli-args.ts b/src/lib/cli-args.ts index 7ae0990d..fcf48ef4 100644 --- a/src/lib/cli-args.ts +++ b/src/lib/cli-args.ts @@ -9,13 +9,21 @@ import { parseArgs } from 'node:util'; import { REF_CHOICES, type RefChoice } from './release.js'; import { parseArchetypeList } from './archetype.js'; import { escapeUnsafe } from './terminal-safe.js'; +import { VERSION_RE } from './validate.js'; import type { Archetype } from '../types.js'; import { PHARN_VERSION } from '../version.js'; const INTRO = `Pharn - Installs and updates PHARN (a workflow for shipping features right with Claude Code) in your git project. npx @pharn-dev/pharn init detects your project's archetype and installs the applicable PHARN capabilities; pharn add installs another capability later; pharn update bumps to the latest skills version.`; type CommandName = - 'init' | 'add' | 'remove' | 'update' | 'list' | 'status' | 'uninstall'; + | 'init' + | 'add' + | 'remove' + | 'update' + | 'list' + | 'status' + | 'uninstall' + | 'verify-archive'; interface CommandSpec { name: CommandName; @@ -54,6 +62,12 @@ const COMMANDS: readonly CommandSpec[] = [ name: 'uninstall', summary: 'Remove the PHARN files pharn wrote and you did not change', }, + { + name: 'verify-archive', + args: '', + summary: 'Check a local pharn-oss .tar.gz as an install would (no network)', + page: 'Check a local pharn-oss .tar.gz as an install would: unpack the listed files into a temporary directory, validate pharn-install.json and every listed sha256, then remove the directory. No network, no project. Build the archive with `git archive --prefix=pharn-oss/ --format=tar.gz -o pharn-oss.tar.gz HEAD`.', + }, ]; interface OptionSpec { @@ -201,6 +215,20 @@ const OPTIONS: readonly OptionSpec[] = [ }, ], }, + { + key: 'expect-version', + long: '--expect-version ', + value: true, + uses: [ + { + commands: ['verify-archive'], + text: [ + "also require the archive's SKILLS_VERSION to equal this", + 'version (X.Y.Z, no leading v), as the release check does', + ], + }, + ], + }, { key: 'help', short: 'h', @@ -347,7 +375,11 @@ export type Invocation = command: 'status'; options: { strict: boolean; drift: boolean; json: boolean }; } - | { command: 'uninstall'; options: { yes: boolean } }; + | { command: 'uninstall'; options: { yes: boolean } } + | { + command: 'verify-archive'; + options: { file: string; expectVersion: string | undefined }; + }; export type ParsedArgs = // One stderr line; the caller adds USAGE_POINTER and exits 1. @@ -484,6 +516,14 @@ export function parseCliArgs(args: readonly string[]): ParsedArgs { ); } + const expectVersion = valueOf('expect-version'); + if (expectVersion !== undefined && !VERSION_RE.test(expectVersion)) { + return refuse( + 'Invalid value for --expect-version (expected a version such as "7.25.5", with no leading "v")', + [expectVersion], + ); + } + if (has('version')) return { kind: 'print', text: PHARN_VERSION }; if (has('help')) { // A bare `pharn --help` and an unknown command get the full text. @@ -546,6 +586,21 @@ export function parseCliArgs(args: readonly string[]): ParsedArgs { }); case 'uninstall': return run({ command: 'uninstall', options: { yes: has('yes') } }); + case 'verify-archive': { + const file = positionals[1]; + // Empty is as missing: `""` names no file. + if (file === undefined || file === '') { + return { + kind: 'refuse', + message: + 'Missing argument: `verify-archive` needs the path of a .tar.gz archive', + }; + } + return run({ + command: 'verify-archive', + options: { file, expectVersion }, + }); + } } } diff --git a/src/lib/repo.ts b/src/lib/repo.ts index e6b61240..b2bc542d 100644 --- a/src/lib/repo.ts +++ b/src/lib/repo.ts @@ -14,7 +14,7 @@ import { fetchCapped } from './fetch-capped.js'; import type { CappedResponse, FetchCappedError } from './fetch-capped.js'; import { MAX_SHA_BYTES } from './release.js'; import type { InstallSource } from './release.js'; -import { readSkillsVersion } from './skills-version.js'; +import { assertSkillsVersion } from './skills-version.js'; import { extractTarGz } from './tar-extract.js'; import { MANIFEST_FILE, @@ -22,11 +22,7 @@ import { verifyUpstreamManifest, } from './upstream-manifest.js'; import type { UpstreamManifest } from './upstream-manifest.js'; -import { - assertSafeString, - COMMIT_RE, - ManifestValidationError, -} from './validate.js'; +import { assertSafeString, COMMIT_RE } from './validate.js'; const API = 'https://api.github.com'; const CODELOAD = 'https://codeload.github.com'; @@ -39,7 +35,7 @@ const CLONE_TIMEOUT_MS = 60_000; // own size bounds nothing: headers walked and decompressed bytes walked bound a // compression bomb's work (both far above pharn-oss v7.25.5's 4,939 entries and // 43 MB), and the written-byte cap bounds what reaches disk. -const MAX_ARCHIVE_BYTES = 32 * 1024 * 1024; +export const MAX_ARCHIVE_BYTES = 32 * 1024 * 1024; const MAX_HEADERS = 200_000; const MAX_SCANNED_BYTES = 1024 * 1024 * 1024; const MAX_WRITTEN_BYTES = 128 * 1024 * 1024; @@ -170,12 +166,12 @@ async function fetchAt( // version compare would lie. Refused inside this try, so the tree is // removed. if (source.kind !== 'release') return; - const found = readSkillsVersion(tree); - if (found !== source.version) { - throw new ManifestValidationError( + assertSkillsVersion( + tree, + source.version, + (found) => `Release ${source.tag} (${source.sha}) ships ${SKILLS_VERSION_FILE} ${found}, not ${source.version}; refusing to install a release whose content does not match its tag.`, - ); - } + ); }); } catch (err) { // Extraction is not transactional, so a partially-written tree must never @@ -234,6 +230,28 @@ export async function extractPharnArchive( return manifest; } +/** + * Run `extractPharnArchive` over a LOCAL archive's bytes (`pharn + * verify-archive`) in a private temp dir that is always removed, on a pass and + * on a refusal alike, and registered with the exit/fatal-signal backstop + * meanwhile. The tree is never returned: `checkTree` (run after the first + * pass, as the release check is) is the only reader. No network. + */ +export async function verifyLocalArchive( + archive: Buffer, + checkTree: (dir: string) => void, +): Promise { + installCleanupHandlers(); + const dir = mkdtempSync(join(tmpdir(), 'pharn-verify-')); + liveClones.add(dir); + try { + return await extractPharnArchive(archive, dir, checkTree); + } finally { + liveClones.delete(dir); + rmSync(dir, { recursive: true, force: true }); + } +} + /** * Download the repo tarball at `ref` into memory, bounded on both time and * size (`fetchCapped`; the decompressed size is bounded by the extract). diff --git a/src/lib/skills-version.ts b/src/lib/skills-version.ts index 7294f9a0..2fea7039 100644 --- a/src/lib/skills-version.ts +++ b/src/lib/skills-version.ts @@ -47,6 +47,21 @@ export function readSkillsVersion(repoDir: string): string { ); } +/** + * Refuse a tree whose SKILLS_VERSION is not `expected`: the release check + * (`fetchAt`, lib/repo.ts) and `verify-archive --expect-version` share it. + * `refusal` words the message from the version found, so each caller keeps + * its own wording; a missing or malformed file throws `readSkillsVersion`'s. + */ +export function assertSkillsVersion( + repoDir: string, + expected: string, + refusal: (found: string) => string, +): void { + const found = readSkillsVersion(repoDir); + if (found !== expected) throw new ManifestValidationError(refusal(found)); +} + // --------------------------------------------------------------------------- // MIN_CLI — the OPTIONAL forward-compatibility handshake, beside SKILLS_VERSION. // diff --git a/tests/cli-args.test.ts b/tests/cli-args.test.ts index b942cecb..d4c8234d 100644 --- a/tests/cli-args.test.ts +++ b/tests/cli-args.test.ts @@ -668,3 +668,85 @@ describe('parseCliArgs: --version and --help', () => { }, ); }); + +describe('parseCliArgs: verify-archive', () => { + it.each<[string[], Invocation]>([ + [ + ['verify-archive', 'x.tar.gz'], + { + command: 'verify-archive', + options: { file: 'x.tar.gz', expectVersion: undefined }, + }, + ], + [ + ['verify-archive', 'x.tar.gz', '--expect-version', '7.25.5'], + { + command: 'verify-archive', + options: { file: 'x.tar.gz', expectVersion: '7.25.5' }, + }, + ], + [ + ['verify-archive', '--expect-version=7.25.5', 'x.tar.gz'], + { + command: 'verify-archive', + options: { file: 'x.tar.gz', expectVersion: '7.25.5' }, + }, + ], + ])('%j parses to its file and expected version', (args, expected) => { + expect(invocation(args)).toEqual(expected); + }); + + const MISSING = + 'Missing argument: `verify-archive` needs the path of a .tar.gz archive'; + const INVALID = + 'Invalid value for --expect-version (expected a version such as "7.25.5", with no leading "v")'; + it.each<[string[], string]>([ + [['verify-archive'], MISSING], + [['verify-archive', ''], MISSING], + [ + ['verify-archive', 'a.tar.gz', 'b.tar.gz'], + 'Unexpected argument: "b.tar.gz"', + ], + [ + ['verify-archive', 'a.tar.gz', '--expect-version', 'v7.25.5'], + `${INVALID}: "v7.25.5"`, + ], + [['verify-archive', 'a.tar.gz', '--expect-version'], `${INVALID}: ""`], + [ + [ + 'verify-archive', + 'a.tar.gz', + '--expect-version', + '1.0.0', + '--expect-version', + '1.0.1', + ], + 'Repeated option: "--expect-version"', + ], + [ + ['verify-archive', 'a.tar.gz', '--json'], + 'Unsupported option for `verify-archive`: "--json"', + ], + [ + ['status', '--expect-version', '1.0.0'], + 'Unsupported option for `status`: "--expect-version"', + ], + [ + ['init', '--expect-version=1.0.0'], + 'Unsupported option for `init`: "--expect-version=1.0.0"', + ], + ])('%j is refused', (args, message) => { + expect(refusal(args)).toBe(message); + }); + + it('is listed in the full help, and its page names the option and the git archive line', () => { + expect(printed(['--help'])).toMatch( + /^ {2}verify-archive +Check a local pharn-oss \.tar\.gz/m, + ); + const page = printed(['verify-archive', '--help']); + expect(page).toContain('pharn verify-archive [options]'); + expect(page).toContain('--expect-version '); + expect(page).toContain('git archive --prefix=pharn-oss/'); + expect(page).not.toContain('--json'); + }); +}); diff --git a/tests/commands/verify-archive.test.ts b/tests/commands/verify-archive.test.ts new file mode 100644 index 00000000..b6b01be5 --- /dev/null +++ b/tests/commands/verify-archive.test.ts @@ -0,0 +1,299 @@ +import { execFileSync } from 'node:child_process'; +import { + mkdirSync, + readdirSync, + symlinkSync, + truncateSync, + writeFileSync, +} from 'node:fs'; +import { join } from 'node:path'; +import { describe, expect, it, vi } from 'vitest'; +import { + A11Y, + fetchStub, + logs, + MANIFEST, + manifestTree, + proj, + run, + SECURITY, + SHA_V1, + stderr, + stdout, + useHarness, + watchClones, + withManifest, + upstreamTree, + type Tree, +} from '../support/harness.js'; +import { + codeloadArchive, + type ArchiveOptions, +} from '../support/tar-fixture.js'; +import { runVerifyArchive } from '../../src/commands/verify-archive.js'; +import { PHARN_DEBUG_HINT } from '../../src/lib/report-error.js'; + +vi.mock('@clack/prompts', async () => + (await import('../support/clack-stub.js')).clackStub(), +); + +useHarness(); + +// `verify-archive` runs the install path's own extractor and manifest checks +// over a LOCAL archive. Every case asserts that nothing was fetched and, where +// a tree was made, that the temp directory is gone afterwards. + +const VERSION = '7.25.5'; + +/** Write a gzipped codeload-shaped archive of `tree` beside the project. */ +function archiveFile( + tree: Tree, + opts: ArchiveOptions = {}, + name = 'pharn-oss.tar.gz', +): string { + const path = join(proj(), '..', name); + writeFileSync(path, codeloadArchive(SHA_V1, tree, {}, opts)); + return path; +} + +async function verify( + file: string, + expectVersion?: string, +): Promise { + return run(() => runVerifyArchive({ file, expectVersion })); +} + +const errors = (): string => logs('error').join('\n'); + +// What v7.25.5 committed outside its manifest, and more an archive may carry. +const UNLISTED = [ + { path: '.claude/skills/pharn-cli', type: '2' }, + { path: '.dev/hard', type: '1' }, + { path: 'PaxHeaders/long', type: 'x', data: '30 path=pharn-oss/x/y/z.md\n' }, + { path: '.dev/notes.md', type: '0', data: 'unlisted\n' }, +]; + +describe('pharn verify-archive — a good archive passes', () => { + it('exits 0 with the file name, listed-file count and SKILLS_VERSION, fetching nothing', async () => { + const left = watchClones(); + const tree = manifestTree(VERSION); + const listed = (JSON.parse(tree[MANIFEST]!) as { files: unknown[] }).files + .length; + expect(await verify(archiveFile(tree))).toBeNull(); + const [summary] = logs('success'); + expect(summary).toContain('pharn-oss.tar.gz'); + expect(summary).toContain(`${listed} files listed in ${MANIFEST}`); + expect(summary).toContain(`SKILLS_VERSION ${VERSION}`); + expect(summary).toContain('MIN_CLI none'); + expect(fetchStub).not.toHaveBeenCalled(); + expect(left()).toEqual([]); + expect(stdout()).toEqual([]); + }); + + it('passes past an unlisted symlink, hard link and pax header (the v7.25.5 shape), leaving nothing behind', async () => { + const left = watchClones(); + expect( + await verify(archiveFile(manifestTree(VERSION), { extra: UNLISTED })), + ).toBeNull(); + expect(logs('success')).toHaveLength(1); + expect(fetchStub).not.toHaveBeenCalled(); + expect(left()).toEqual([]); + }); + + it('--expect-version that matches passes and says so', async () => { + expect( + await verify(archiveFile(manifestTree(VERSION)), VERSION), + ).toBeNull(); + expect(logs('success')[0]).toContain( + `SKILLS_VERSION ${VERSION}, as expected`, + ); + }); + + it('names a valid MIN_CLI in the summary', async () => { + const tree = withManifest({ + ...upstreamTree(VERSION), + MIN_CLI: '0.14.0\n', + }); + expect(await verify(archiveFile(tree))).toBeNull(); + expect(logs('success')[0]).toContain('MIN_CLI 0.14.0'); + }); + + it('warns about a capability an install would skip, and still passes', async () => { + const tree = manifestTree(VERSION, (m) => { + const cap = m.capabilities.find((c) => c.name === 'a11y')!; + cap.applies = ['mobile']; + }); + expect(await verify(archiveFile(tree))).toBeNull(); + expect(logs('warn').join('\n')).toMatch(/SKIPPED/); + expect(logs('warn').join('\n')).toContain('a11y'); + expect(logs('success')).toHaveLength(1); + }); +}); + +describe('pharn verify-archive — a broken archive is refused, naming the entry and rule', () => { + it('a listed file whose bytes differ from its sha256', async () => { + const left = watchClones(); + const tree = manifestTree(VERSION); + tree[A11Y] = 'altered after the manifest was built\n'; + expect(await verify(archiveFile(tree))).toBe(1); + expect(errors()).toContain('Archive pharn-oss.tar.gz refused:'); + expect(errors()).toContain(A11Y); + expect(errors()).toMatch(/sha256/); + expect(logs('success')).toEqual([]); + expect(fetchStub).not.toHaveBeenCalled(); + expect(left()).toEqual([]); + }); + + it('a symlink at a listed path', async () => { + const left = watchClones(); + const file = archiveFile(manifestTree(VERSION), { + replace: { [SECURITY]: [{ path: SECURITY, type: '2' }] }, + }); + expect(await verify(file)).toBe(1); + expect(errors()).toMatch(/unsupported type '2'/); + expect(errors()).toContain(SECURITY); + expect(left()).toEqual([]); + }); + + it('an archive without pharn-install.json names the --prefix command', async () => { + const left = watchClones(); + const tree = upstreamTree(VERSION); + expect(await verify(archiveFile(tree))).toBe(1); + expect(errors()).toContain(`holds no ${MANIFEST}`); + expect(errors()).toContain('git archive --prefix=pharn-oss/'); + expect(left()).toEqual([]); + }); + + it('a rootless archive (a plain `git archive`) gets the same --prefix message', async () => { + expect( + await verify(archiveFile(manifestTree(VERSION), { rootless: true })), + ).toBe(1); + // The extractor's own refusal (a selected path with no root above it), + // which the command recognises by its text and extends with the fix. + expect(errors()).toContain('tar entry has no path below the archive root'); + expect(errors()).toContain('one top-level directory'); + expect(errors()).toContain('git archive --prefix=pharn-oss/'); + expect(fetchStub).not.toHaveBeenCalled(); + }); + + it('an archive under a deeper prefix (a/b/) is told it has no manifest under one root', async () => { + const tree = manifestTree(VERSION); + const deep = Object.fromEntries( + Object.entries(tree).map(([rel, body]) => [`deep/${rel}`, body]), + ); + expect(await verify(archiveFile(deep))).toBe(1); + expect(errors()).toContain(`holds no ${MANIFEST}`); + expect(errors()).toContain('git archive --prefix=pharn-oss/'); + }); + + it('--expect-version that differs names both versions', async () => { + const left = watchClones(); + expect(await verify(archiveFile(manifestTree(VERSION)), '7.25.6')).toBe(1); + expect(errors()).toContain( + `ships SKILLS_VERSION ${VERSION}, not 7.25.6 (--expect-version)`, + ); + expect(left()).toEqual([]); + }); + + it('a malformed MIN_CLI', async () => { + const tree = withManifest({ + ...upstreamTree(VERSION), + MIN_CLI: 'not-a-version\n', + }); + expect(await verify(archiveFile(tree))).toBe(1); + expect(errors()).toContain('MIN_CLI is present but unusable'); + expect(errors()).toContain('not a valid version'); + }); + + it('a file that is not gzip', async () => { + const path = join(proj(), '..', 'junk.tar.gz'); + writeFileSync(path, 'not an archive at all\n'); + expect(await verify(path)).toBe(1); + expect(errors()).toContain('Archive junk.tar.gz refused:'); + expect(errors()).toMatch(/decompress/); + }); + + it('prints the PHARN_DEBUG hint, and the original error under PHARN_DEBUG=1', async () => { + const tree = manifestTree(VERSION); + tree[A11Y] = 'altered\n'; + const file = archiveFile(tree); + expect(await verify(file)).toBe(1); + expect(logs('info')).toContain(PHARN_DEBUG_HINT); + + vi.stubEnv('PHARN_DEBUG', '1'); + vi.mocked((await import('@clack/prompts')).log.info).mockClear(); + expect(await verify(file)).toBe(1); + expect(logs('info')).not.toContain(PHARN_DEBUG_HINT); + expect(stderr().join('\n')).toMatch(/UpstreamManifestError|sha256/); + }); +}); + +describe('pharn verify-archive — the input path', () => { + it('a path that does not exist', async () => { + expect(await verify(join(proj(), 'missing.tar.gz'))).toBe(1); + expect(errors()).toContain('missing.tar.gz: it does not exist.'); + expect(fetchStub).not.toHaveBeenCalled(); + }); + + it('a directory', async () => { + const dir = join(proj(), 'dir.tar.gz'); + mkdirSync(dir); + expect(await verify(dir)).toBe(1); + expect(errors()).toContain('is not a regular file'); + }); + + // POSIX-only, as tests/bounded-read.test.ts's FIFO case: the gates run on + // ubuntu only. + it('a FIFO is refused without waiting on it', async () => { + const fifo = join(proj(), 'pipe.tar.gz'); + execFileSync('mkfifo', [fifo]); + expect(await verify(fifo)).toBe(1); + expect(errors()).toContain('is not a regular file'); + }); + + it('a failure that is not a refusal (no temp dir can be made) is reported with the PHARN_DEBUG hint', async () => { + const file = archiveFile(manifestTree(VERSION)); + vi.stubEnv('TMPDIR', join(proj(), 'no-such-dir')); + expect(await verify(file)).toBe(1); + expect(errors()).not.toContain('refused'); + expect(errors()).toMatch(/ENOENT/); + expect(logs('info')).toContain(PHARN_DEBUG_HINT); + }); + + it('a file over the 32 MiB download cap', async () => { + const big = join(proj(), 'big.tar.gz'); + writeFileSync(big, ''); + truncateSync(big, 32 * 1024 * 1024 + 1); + expect(await verify(big)).toBe(1); + expect(errors()).toContain('is larger than 32 MiB'); + }); + + it('an empty file', async () => { + const empty = join(proj(), 'empty.tar.gz'); + writeFileSync(empty, ''); + expect(await verify(empty)).toBe(1); + expect(errors()).toContain('empty.tar.gz: it is empty.'); + }); + + it('follows a symlinked archive file (the user’s own)', async () => { + const link = join(proj(), 'link.tar.gz'); + symlinkSync(archiveFile(manifestTree(VERSION)), link); + expect(await verify(link)).toBeNull(); + expect(logs('success')[0]).toContain('link.tar.gz'); + }); + + it('escapes a control character in the path wherever it is printed', async () => { + expect(await verify(join(proj(), 'evil\u001b[31m.tar.gz'))).toBe(1); + expect(errors()).not.toContain('\u001b'); + expect(errors()).toContain('evil'); + + const tree = manifestTree(VERSION); + tree[A11Y] = 'altered\n'; + const file = archiveFile(tree, {}, 'bad\u001b[2J.tar.gz'); + expect(await verify(file)).toBe(1); + expect(errors()).not.toContain('\u001b'); + expect( + readdirSync(join(proj(), '..')).some((n) => n.startsWith('bad')), + ).toBe(true); + }); +}); diff --git a/tests/dist-smoke.test.ts b/tests/dist-smoke.test.ts index b1cb6ced..7102e9f3 100644 --- a/tests/dist-smoke.test.ts +++ b/tests/dist-smoke.test.ts @@ -8,11 +8,14 @@ import { realpathSync, rmSync, symlinkSync, + writeFileSync, } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { codeloadArchive } from './support/tar-fixture.js'; +import { upstreamTree, withManifest } from './support/harness.js'; // Executes the SHIPPED artifact — the esbuild bundle — inside the required // `Test` gate, which runs `test:coverage` and never `npm run build`. Every other @@ -116,7 +119,7 @@ function loadedModules(stderr: string): string[] { // A command's chunk is named after its source file (`status-.js`). const COMMAND_CHUNK = - /\/dist\/(init|add|remove|update|list|status|uninstall)-[A-Z0-9]+\.js$/; + /\/dist\/(init|add|remove|update|list|status|uninstall|verify-archive)-[A-Z0-9]+\.js$/; // Each test spawns a fresh node process; the per-test budget is the spawn's. describe('the built bundle (dist/index.js)', { timeout: 30_000 }, () => { @@ -164,6 +167,23 @@ describe('the built bundle (dist/index.js)', { timeout: 30_000 }, () => { } }); + it('verify-archive passes a good local archive (exit 0) and refuses a missing file (exit 1)', () => { + const file = join(tmp, 'pharn-oss.tar.gz'); + writeFileSync( + file, + codeloadArchive('a'.repeat(40), withManifest(upstreamTree('7.25.5'))), + ); + const ok = pharn(['verify-archive', file, '--expect-version', '7.25.5']); + expect(ok.status).toBe(0); + expect(ok.stdout).toContain('pharn-oss.tar.gz:'); + expect(ok.stdout).toContain('SKILLS_VERSION 7.25.5, as expected'); + + const missing = pharn(['verify-archive', join(tmp, 'nope.tar.gz')]); + expect(missing.status).toBe(1); + expect(missing.stderr).toContain('nope.tar.gz: it does not exist.'); + expect(missing.stderr).not.toMatch(STACK_FRAME); + }); + it('status with no pharn.config.json exits 1 with the "run init" message, no stack trace', () => { const r = pharn(['status']); expect(r.status).toBe(1); diff --git a/tests/index.test.ts b/tests/index.test.ts index e780da61..5b13c66a 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -17,6 +17,7 @@ const runUpdate = vi.fn(async (_opts: unknown) => undefined); const runList = vi.fn(async (_opts: unknown) => undefined); const runStatus = vi.fn(async (_opts: unknown) => undefined); const runUninstall = vi.fn(async (_opts: unknown) => undefined); +const runVerifyArchive = vi.fn(async (_opts: unknown) => undefined); // Each command module's factory runs when, and only when, main() imports it: // `loaded` names the command modules loaded since it was last emptied. const loaded = vi.hoisted((): string[] => []); @@ -39,6 +40,10 @@ vi.mock( '../src/commands/uninstall.js', () => (loaded.push('uninstall'), { runUninstall }), ); +vi.mock( + '../src/commands/verify-archive.js', + () => (loaded.push('verify-archive'), { runVerifyArchive }), +); const COMMANDS = { init: runInit, @@ -48,6 +53,7 @@ const COMMANDS = { list: runList, status: runStatus, uninstall: runUninstall, + 'verify-archive': runVerifyArchive, }; function setArgv(...args: string[]): void { @@ -113,6 +119,7 @@ describe('main (argv dispatch)', () => { [['list', '--json']], [['status', '--strict', '--no-drift']], [['uninstall', '-y']], + [['verify-archive', 'a.tar.gz', '--expect-version', '7.25.5']], ])('hands %j to its command as one parsed options object', async (args) => { await run(...args); const parsed = parseCliArgs(args); diff --git a/tests/release-consistency.test.ts b/tests/release-consistency.test.ts index 1926e9a4..bb3cb42d 100644 --- a/tests/release-consistency.test.ts +++ b/tests/release-consistency.test.ts @@ -97,6 +97,7 @@ const KNOWN_TAGS: readonly string[] = [ 'v0.21.4', 'v0.21.5', 'v0.21.6', + 'v0.21.7', ]; // Sections with no tag at all, and so no link: 0.8.0 was bumped and superseded // by 0.9.0 on the same day, never tagged or published; 0.2.0 / 0.1.0 predate diff --git a/tests/repo.test.ts b/tests/repo.test.ts index b68ef2ef..129fc212 100644 --- a/tests/repo.test.ts +++ b/tests/repo.test.ts @@ -24,8 +24,13 @@ import { withManifest, } from './support/harness.js'; -const { CLONE_READ_FILES, extractPharnArchive, fetchRepo, fetchCommitSha } = - await import('../src/lib/repo.js'); +const { + CLONE_READ_FILES, + extractPharnArchive, + fetchRepo, + fetchCommitSha, + verifyLocalArchive, +} = await import('../src/lib/repo.js'); // A real 40-char lowercase-hex commit SHA (the SHA-1 of the empty blob) — the // form fetchRepo validates against COMMIT_RE before it fetches or records it. @@ -938,3 +943,69 @@ describe('fetchRepo — a refused archive keeps its error and is noted with the expect(archiveRefusalMessage(err)).toBeUndefined(); }); }); + +// CORE-387: `pharn verify-archive`'s half in repo.ts — the same extraction in +// a private temp dir that is removed on a pass and on a refusal alike. +describe('verifyLocalArchive (CORE-387)', () => { + beforeEach(() => { + sandbox = mkdtempSync(join(tmpdir(), 'pharn-repo-sandbox-')); + process.env.TMPDIR = sandbox; + process.env.TEMP = sandbox; + process.env.TMP = sandbox; + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + throw new Error('no network in this test'); + }), + ); + }); + + afterEach(() => { + for (const [key, value] of Object.entries(realTmp)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + rmSync(sandbox, { recursive: true, force: true }); + vi.unstubAllGlobals(); + }); + + it('returns the manifest and removes its temp dir; checkTree sees the tree after the first pass', async () => { + const tree = manifestTree('7.20.0'); + const seen: string[] = []; + const manifest = await verifyLocalArchive( + codeloadArchive(VALID_SHA, tree), + (dir) => { + seen.push(dir); + expect(existsSync(join(dir, MANIFEST))).toBe(true); + expect(existsSync(join(dir, SECURITY))).toBe(false); + }, + ); + expect(manifest.skillsVersion).toBe('7.20.0'); + expect(seen).toHaveLength(1); + expect(seen[0]!.startsWith(join(sandbox, 'pharn-verify-'))).toBe(true); + expect(leftoverTempDirs()).toEqual([]); + expect(fetch).not.toHaveBeenCalled(); + }); + + it('removes its temp dir when the archive is refused, and rethrows the refusal', async () => { + const tree = manifestTree('7.20.0'); + tree[SECURITY] = 'altered\n'; + const err = await verifyLocalArchive( + codeloadArchive(VALID_SHA, tree), + () => undefined, + ).catch((e: unknown) => e); + expect(err).toBeInstanceOf(UpstreamManifestError); + expect(leftoverTempDirs()).toEqual([]); + }); + + it('removes its temp dir when checkTree throws', async () => { + const err = await verifyLocalArchive( + codeloadArchive(VALID_SHA, manifestTree('7.20.0')), + () => { + throw new ManifestValidationError('stop'); + }, + ).catch((e: unknown) => e); + expect((err as Error).message).toBe('stop'); + expect(leftoverTempDirs()).toEqual([]); + }); +}); diff --git a/tests/skills-version.test.ts b/tests/skills-version.test.ts index 00e9e786..d53cb189 100644 --- a/tests/skills-version.test.ts +++ b/tests/skills-version.test.ts @@ -3,6 +3,7 @@ import { join } from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { useTmpDir } from './helpers.js'; import { + assertSkillsVersion, fetchRemoteSkillsVersion, readMinCli, readSkillsVersion, @@ -24,6 +25,31 @@ function fakeResponse(body: string, status = 200): Response { }); } +describe('assertSkillsVersion (the release check and verify-archive)', () => { + const tmp = useTmpDir(); + const words = (found: string): string => `found ${found}`; + + it('passes when SKILLS_VERSION equals the expected version', () => { + writeFileSync(join(tmp.path(), 'SKILLS_VERSION'), '7.25.5\n'); + expect(() => + assertSkillsVersion(tmp.path(), '7.25.5', words), + ).not.toThrow(); + }); + + it('throws the caller-worded refusal on a mismatch', () => { + writeFileSync(join(tmp.path(), 'SKILLS_VERSION'), '7.25.4\n'); + expect(() => assertSkillsVersion(tmp.path(), '7.25.5', words)).toThrow( + new ManifestValidationError('found 7.25.4'), + ); + }); + + it("throws readSkillsVersion's refusal when the file is missing", () => { + expect(() => assertSkillsVersion(tmp.path(), '7.25.5', words)).toThrow( + /SKILLS_VERSION is missing/, + ); + }); +}); + describe('readSkillsVersion', () => { const tmp = useTmpDir(); diff --git a/tests/support/tar-fixture.ts b/tests/support/tar-fixture.ts index 888cad64..1cdbe84d 100644 --- a/tests/support/tar-fixture.ts +++ b/tests/support/tar-fixture.ts @@ -62,10 +62,27 @@ export function githubArchive(sha: string): Buffer { * a tracked git symlink. Its place in the tree (and so in a manifest built * from the tree) is kept. */ +/** A raw archive entry: a root-relative path, a ustar typeflag, its payload. */ +export interface RawEntry { + path: string; + type: string; + data?: string; +} + +export interface ArchiveOptions { + /** Entries spliced in right after the root directory (a symlink, a pax header). */ + extra?: readonly RawEntry[]; + /** A tree path's own entry swapped for these raw entries. */ + replace?: Readonly>; + /** No root directory: entries at the top level, as a plain `git archive`. */ + rootless?: boolean; +} + export function codeloadArchive( sha: string, files: Readonly>, links: Readonly> = {}, + opts: ArchiveOptions = {}, ): Buffer { // Memoized per (sha, tree): the command suites serve the same upstream state // to every command of a test and to many tests, and gzip is the bulk of a @@ -74,10 +91,10 @@ export function codeloadArchive( Object.keys(files) .sort() .map((rel) => [rel, files[rel]]), - )}\0${JSON.stringify(Object.entries(links).sort())}`; + )}\0${JSON.stringify(Object.entries(links).sort())}\0${JSON.stringify(opts)}`; const hit = archiveCache.get(key); if (hit) return hit; - const archive = buildArchive(sha, files, links); + const archive = buildArchive(sha, files, links, opts); archiveCache.set(key, archive); return archive; } @@ -88,32 +105,38 @@ function buildArchive( sha: string, files: Readonly>, links: Readonly>, + opts: ArchiveOptions, ): Buffer { - const root = `pharn-oss-${sha.slice(0, 7)}`; + const root = opts.rootless ? '' : `pharn-oss-${sha.slice(0, 7)}/`; + const named = (rel: string): string => { + const name = `${root}${rel}`; + if (Buffer.byteLength(name) >= 100) { + throw new Error(`tar fixture: ${name} does not fit the ustar name field`); + } + return name; + }; + const raw = (e: RawEntry): Buffer => entry(named(e.path), e.type, e.data); const parts = [ entry('pax_global_header', 'g', `52 comment=${sha}\n`), - entry(`${root}/`, '5'), + ...(opts.rootless ? [] : [entry(root, '5')]), + ...(opts.extra ?? []).map(raw), ]; const dirs = new Set(); for (const rel of Object.keys(files).sort()) { const segments = rel.split('/'); for (let i = 1; i < segments.length; i++) { - const dir = `${root}/${segments.slice(0, i).join('/')}/`; + const dir = `${root}${segments.slice(0, i).join('/')}/`; if (!dirs.has(dir)) { dirs.add(dir); parts.push(entry(dir, '5')); } } - const name = `${root}/${rel}`; - if (Buffer.byteLength(name) >= 100) { - throw new Error(`tar fixture: ${name} does not fit the ustar name field`); - } + const swapped = opts.replace?.[rel]; const target = links[rel]; - parts.push( - target === undefined - ? entry(name, '0', files[rel]) - : header(name, '2', 0, target), - ); + if (swapped) parts.push(...swapped.map(raw)); + else if (target === undefined) + parts.push(entry(named(rel), '0', files[rel])); + else parts.push(header(named(rel), '2', 0, target)); } parts.push(Buffer.alloc(BLOCK * 2)); return gzipSync(Buffer.concat(parts));