diff --git a/CHANGELOG.md b/CHANGELOG.md index 18811395..a3135dec 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.21.7] — 2026-11-25 + +### Fixed + +- **A pharn-oss archive that `pharn` refuses now says which one, whose fault it is, and what to try.** When the downloaded archive failed a check (an entry the extractor does not admit, such as a symbolic link, or an install manifest whose files do not match their sha256s), `init`, `add`, `update` and `status` printed only the check, for example `tar entry has an unsupported type '2': …`. The message now names what was fetched (the release tag and its commit, or `main` and its commit), says the problem is in that pharn-oss archive and that nothing in your project was changed, keeps the original check as `Reason:`, says that no option skips the check (`update --force` and `--yes` included), and lists the next steps the CLI supports: `--ref main` on a release, `--ref latest` on `main`, upgrading `pharn`, and reporting it at . The spinner of `init`, `add` and `status` now stops with `pharn-oss archive refused` instead of a failure to fetch or reach. `PHARN_DEBUG=1` prints the original error. What is refused is unchanged. See [The pharn-oss archive was refused](docs/troubleshooting.md#the-pharn-oss-archive-was-refused). + ## [0.21.6] — 2026-11-25 ### Fixed @@ -529,7 +535,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.6...HEAD +[Unreleased]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.7...HEAD +[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 [0.21.4]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.3...v0.21.4 diff --git a/CLAUDE.md b/CLAUDE.md index 52fc671d..54d1a29e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -121,7 +121,8 @@ PHARN_DEBUG=1 npm run dev -- init # full error output for fetch/install failur - `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`). - `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`, +- Fetch boundary: `fetch-capped` (the one bounded GET), `release` (which commit), `repo` + `tar-extract`, `archive-refusal` + (the refused-archive message), `skills-version`, `min-cli-gate`, `upstream-manifest` (the upstream install manifest's one parser), `capability-index` (manifest → typed index), `upstream-models`. - Selection: `detect-archetype` + `archetype` (detection), `resolve-capabilities`, `merge-capabilities`, diff --git a/docs/contributing.md b/docs/contributing.md index 39616774..6f0fd736 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -130,7 +130,7 @@ pharn-cli/ index.ts CLI entry, command routing commands/ init, add, remove, update, list, status, uninstall 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, 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 + 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 tests/ vitest specs docs/ user + maintainer documentation @@ -230,6 +230,7 @@ Two rules that are easy to get wrong: | `models-update.test.ts` / `upstream-models.test.ts` | `update`'s rows for the `models` block; reading pharn-oss's block | | `confirm.test.ts` / `repo.test.ts` / `banner.test.ts` / `format.test.ts` | helpers; the codeload fetch boundary; banner; format | | `tar-extract.test.ts` | The ustar reader: selection (unlisted entries skipped), strip-1, prefix reassembly, every rejection at a listed path | +| `archive-refusal.test.ts` | The refused-archive message: which errors are noted, the ref named, and only `--ref` values the CLI accepts | | `index.test.ts` | argv dispatch: the per-command option allowlist, the arity gate, and their exit codes | | `project-lock.test.ts` + `-break` / `commands/lock.test.ts` | The single-writer lock: acquire/release, stale-break single-winner, and which commands take it | | `min-cli-gate.test.ts` / `semver.test.ts` | The `MIN_CLI` forward-compat gate and its version comparison | diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index f862fed9..338da3fd 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -26,17 +26,18 @@ ## 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) | -| `… 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) | ## Node version @@ -220,10 +221,44 @@ installs only the newest pharn-oss **GitHub release**, never the tip of `main`. A release whose tree carries another `SKILLS_VERSION` than its tag is refused too (`Release vX.Y.Z (…) ships SKILLS_VERSION …`). `pharn update --ref main` moves an install to `main`. +## The pharn-oss archive was refused + +```text +⚠ pharn-oss release v7.25.5 (commit 1755d6b8…) was refused: its published archive failed pharn's checks. + The problem is in that pharn-oss archive, not in your project; nothing in your project was changed. + Reason: tar entry has an unsupported type '2' at a path pharn installs (only a regular file is accepted there): + pharn-oss-1755d6b/.claude/commands/pharn-plan.md + No option skips this check: forcing an update or answering yes does not help. Next steps: + - install the tip of main instead: `pharn init --ref main` (`pharn update --ref main` for an existing install) + - upgrade pharn (`npm install -g @pharn-dev/pharn@latest`): a newer pharn may accept this archive + - or re-run once pharn-oss publishes a fixed release, and report this at https://github.com/pharn-dev/pharn-oss/issues +Re-run with PHARN_DEBUG=1 for full error output. +``` + +`init`, `add`, `update` and `status` exit 1 when the pharn-oss archive they downloaded fails a check: the +extractor unpacks only the files `pharn-install.json` lists (plus the few it reads itself), and one of those +that is not a regular file (a symbolic link, a hard link, a device) is refused; the tree must carry a valid `pharn-install.json` whose every file +matches its sha256 (a release must also ship the `SKILLS_VERSION` its tag names). The first line names what was +fetched: the release tag and its commit, or `main` and its commit (`commit not resolved` when GitHub did not +say). `Reason:` is the check that failed, as `pharn` found it. The download happens before any write, so +nothing in your project is changed and an existing install keeps working. + +No option gets past the check, and re-running the same release refuses the same bytes. What `pharn` offers: + +- on a release (the default, `--ref latest`): try the tip of `main` with `pharn init --ref main` (`pharn update +--ref main` for an existing install); +- on `main`: go back to verified releases with `--ref latest`, or re-run once `main` is fixed; +- either way: upgrade `pharn` (`npm install -g @pharn-dev/pharn@latest`), which helps only when a newer + `pharn` accepts what this one refused (not for a manifest path outside what `pharn` installs, [below](#a-pharn-oss-release-was-refused)), + and report the archive at the [pharn-oss issues](https://github.com/pharn-dev/pharn-oss/issues). + +`PHARN_DEBUG=1` prints the original error (for example `TarExtractError: …`) instead of the hint. + ## A pharn-oss release was refused ```text -⚠ pharn-oss's pharn-install.json files[N] would write pharn/floor/.eslintrc.json, outside the paths pharn +⚠ pharn-oss release vX.Y.Z (commit …) was refused: its published archive failed pharn's checks. … + Reason: pharn-oss's pharn-install.json files[N] would write pharn/floor/.eslintrc.json, outside the paths pharn installs; refusing this release. This is a problem in the pharn-oss release, not in your project: … ``` @@ -264,7 +299,8 @@ difference or a missing or malformed `pharnVersion` never warns ([support policy ## Install failed -"Failed to install capabilities", exit 1: a fetch failure, an archive `pharn` refused to extract, or a +"Failed to install capabilities", exit 1: a fetch failure, an archive `pharn` refused to extract ([The +pharn-oss archive was refused](#the-pharn-oss-archive-was-refused)), or a selected capability missing in the fetched repo (`Capability "" () is missing at / in the fetched repo.`; one whose `.md` is absent is refused earlier, at the index parse). What the extractor rejects is in `THREAT-MODEL.md` §2. `PHARN_DEBUG=1 npx @pharn-dev/pharn init` shows the full error. diff --git a/package-lock.json b/package-lock.json index 0af6d1c4..232b53f5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@pharn-dev/pharn", - "version": "0.21.6", + "version": "0.21.7", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@pharn-dev/pharn", - "version": "0.21.6", + "version": "0.21.7", "license": "Apache-2.0", "dependencies": { "@clack/prompts": "^1.8.1", diff --git a/package.json b/package.json index 2b998f2b..fea4285f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@pharn-dev/pharn", - "version": "0.21.6", + "version": "0.21.7", "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/add.ts b/src/commands/add.ts index e4fc7896..50d5aaec 100644 --- a/src/commands/add.ts +++ b/src/commands/add.ts @@ -27,6 +27,10 @@ import { writeRecords, } from '../lib/install-records.js'; import { fetchRepo } from '../lib/repo.js'; +import { + ARCHIVE_REFUSED_SPINNER, + archiveRefusalMessage, +} from '../lib/archive-refusal.js'; import { channelOf, resolveSource, @@ -175,7 +179,11 @@ async function runArchetypeAdd( repo = await fetchRepo(await resolveSource(channelOf(config))); s.stop(`Capabilities fetched from ${sourceLabel(repo.source)}`); } catch (err) { - s.stop('Failed to fetch capabilities'); + s.stop( + archiveRefusalMessage(err) === undefined + ? 'Failed to fetch capabilities' + : ARCHIVE_REFUSED_SPINNER, + ); // Unwinds through the lock's release; runAdd's catch labels it. throw err; } @@ -256,7 +264,11 @@ async function runAddPicker( repo = await fetchRepo(await resolveSource(channelOf(config))); s.stop(`Capabilities fetched from ${sourceLabel(repo.source)}`); } catch (err) { - s.stop('Failed to fetch capabilities'); + s.stop( + archiveRefusalMessage(err) === undefined + ? 'Failed to fetch capabilities' + : ARCHIVE_REFUSED_SPINNER, + ); throw err; } let outcome: PickerAddOutcome; @@ -315,7 +327,7 @@ function plural(n: number): string { // anything else is a failure, which earns the hint. function addError(err: unknown): CliError { if (err instanceof ProjectLockedError) return CliError.refusal(err.message); - return CliError.failure(err); + return CliError.failure(err, { message: archiveRefusalMessage(err) }); } // Resolve the arg against the fetched index and, if it uniquely names a diff --git a/src/commands/init.ts b/src/commands/init.ts index 16263a8e..8de19d68 100644 --- a/src/commands/init.ts +++ b/src/commands/init.ts @@ -15,6 +15,10 @@ import { minCliGate } from '../lib/min-cli-gate.js'; import { PHARN_VERSION } from '../version.js'; import { warnIfOlderCli } from '../lib/older-cli.js'; import { fetchRepo } from '../lib/repo.js'; +import { + ARCHIVE_REFUSED_SPINNER, + archiveRefusalMessage, +} from '../lib/archive-refusal.js'; import { UpstreamManifestError } from '../lib/upstream-manifest.js'; import { DEFAULT_INIT_REF, @@ -213,14 +217,19 @@ async function runInitArchetype(mode: RunMode): Promise { // `--ref main`. repo = await fetchRepo(await resolveSource(channel)); } catch (err) { - s.stop('Failed to fetch PHARN'); + s.stop( + archiveRefusalMessage(err) === undefined + ? 'Failed to fetch PHARN' + : ARCHIVE_REFUSED_SPINNER, + ); throw CliError.failure(err, { json, message: - err instanceof ReleaseResolveError || + archiveRefusalMessage(err) ?? + (err instanceof ReleaseResolveError || err instanceof UpstreamManifestError ? err.message - : `Could not reach ${REPO_URL}: ${errorMessage(err)}`, + : `Could not reach ${REPO_URL}: ${errorMessage(err)}`), }); } diff --git a/src/commands/status.ts b/src/commands/status.ts index 8250976b..6a55bf8e 100644 --- a/src/commands/status.ts +++ b/src/commands/status.ts @@ -3,6 +3,10 @@ import { intro, log, note, outro, spinner } from '@clack/prompts'; import pc from '../lib/color.js'; import { REPO } from '../lib/constants.js'; import { fetchRepo, type FetchedRepo } from '../lib/repo.js'; +import { + ARCHIVE_REFUSED_SPINNER, + archiveRefusalMessage, +} from '../lib/archive-refusal.js'; import { channelOf, resolveLatestReleaseVersion, @@ -132,8 +136,15 @@ export async function runStatus( repo = await fetchRepo(await resolveSource(channel)); s?.stop(`Compared against ${sourceLabel(repo.source)}`); } catch (err) { - s?.stop(`Failed to reach ${REPO}`); - throw CliError.failure(err, { json }); + s?.stop( + archiveRefusalMessage(err) === undefined + ? `Failed to reach ${REPO}` + : ARCHIVE_REFUSED_SPINNER, + ); + throw CliError.failure(err, { + json, + message: archiveRefusalMessage(err), + }); } try { input = cloneInput(repo, { node, config, channel, strict }, cwd); diff --git a/src/commands/update.ts b/src/commands/update.ts index 0fbb4963..ba2d79c6 100644 --- a/src/commands/update.ts +++ b/src/commands/update.ts @@ -58,6 +58,7 @@ import { import { buildRecords, writeRecords } from '../lib/install-records.js'; import { terminalSafe } from '../lib/terminal-safe.js'; import { fetchRepo, type FetchedRepo } from '../lib/repo.js'; +import { archiveRefusalMessage } from '../lib/archive-refusal.js'; import { channelOf, resolveSource, @@ -309,7 +310,7 @@ async function runArchetypeUpdate( repo = await fetchRepo(source); } catch (err) { pre.stop('Update failed'); - throw CliError.failure(err); + throw CliError.failure(err, { message: archiveRefusalMessage(err) }); } let outcome: UpdateOutcome; @@ -785,7 +786,10 @@ async function fetchAndPlan( repo = await fetchRepo(source); } catch (err) { ui.spin.stop('Planning failed'); - throw CliError.failure(err, { json: ui.json }); + throw CliError.failure(err, { + json: ui.json, + message: archiveRefusalMessage(err), + }); } try { return planFromClone(repo, config, cwd, force, channel, ui); diff --git a/src/lib/archive-refusal.ts b/src/lib/archive-refusal.ts new file mode 100644 index 00000000..189d1dcb --- /dev/null +++ b/src/lib/archive-refusal.ts @@ -0,0 +1,110 @@ +import { REPO_BRANCH, REPO_URL } from './constants.js'; +import type { InstallSource } from './release.js'; +import { TarExtractError } from './tar-extract.js'; +import { escapeUnsafe } from './terminal-safe.js'; +import { COMMIT_RE, ManifestValidationError } from './validate.js'; + +// --------------------------------------------------------------------------- +// The archive-refusal message. `fetchRepo` (lib/repo.ts) refuses a fetched +// pharn-oss archive in two places: the extractor (TarExtractError) and the +// tree checks after it (ManifestValidationError: the install manifest, its +// sha256s, a release's SKILLS_VERSION). Their own text names one entry and one +// rule and nothing else, so a user cannot tell that the published archive is +// at fault, that no flag gets past it, or what to try. +// +// fetchRepo throws the refusal UNCHANGED (its class is the contract callers and +// tests rely on) and notes here which ref it fetched. The command boundary +// asks `archiveRefusalMessage(err)` for the user-facing text: the ref fetched, +// the blame on the archive, the original reason, and only next steps this CLI +// supports (`--ref` takes `latest` or `main`). Every other error (network, +// release resolution) gets no note and keeps its own message. The raw error +// stays the CliError's cause, which `PHARN_DEBUG=1` prints. +// +// "Nothing in your project was changed" holds because every command fetches +// before its first project write (the lock aside, which its `finally` removes). +// --------------------------------------------------------------------------- + +// The refusals fetchRepo noted, keyed by the thrown object itself: nothing is +// added to the error, and an entry goes with it. +const refused = new WeakMap(); + +// The same address as upstream-manifest.ts's PHARN_OSS_ISSUES_URL, built from +// the shared constant so this module stays free of the manifest parser. +const ISSUES_URL = `https://${REPO_URL}/issues`; + +const UPGRADE_STEP = + '- upgrade pharn (`npm install -g @pharn-dev/pharn@latest`): a newer pharn may accept this archive'; + +/** Which ref was fetched, as the first words of the message. */ +function fetchedRef(source: InstallSource, sha: string | null): string { + if (source.kind === 'release') { + return `pharn-oss release ${source.tag} (commit ${source.sha})`; + } + return sha === null + ? `pharn-oss ${REPO_BRANCH} (refs/heads/${REPO_BRANCH}, commit not resolved)` + : `pharn-oss ${REPO_BRANCH} at commit ${sha}`; +} + +/** The next steps for the channel that was fetched: only what the CLI has. */ +function nextSteps(source: InstallSource): string[] { + if (source.kind === 'release') { + return [ + '- install the tip of main instead: `pharn init --ref main` (`pharn update --ref main` for an existing install)', + UPGRADE_STEP, + `- or re-run once pharn-oss publishes a fixed release, and report this at ${ISSUES_URL}`, + ]; + } + return [ + '- go back to verified releases: `pharn init --ref latest` (`pharn update --ref latest` for an existing install)', + UPGRADE_STEP, + `- or re-run later, once main is fixed, and report this at ${ISSUES_URL}`, + ]; +} + +/** + * The text for a refused archive. `reason` is the original refusal's message; + * any unsafe character left in it is escaped here (it can carry archive bytes). + */ +export function refusalText( + source: InstallSource, + sha: string | null, + reason: string, +): string { + return [ + `${fetchedRef(source, sha)} was refused: its published archive failed pharn's checks. ` + + 'The problem is in that pharn-oss archive, not in your project; nothing in your project was changed.', + `Reason: ${escapeUnsafe(reason)}`, + 'No option skips this check: forcing an update or answering yes does not help. Next steps:', + ...nextSteps(source), + ].join('\n'); +} + +/** + * Called by fetchRepo on its way out of a failed fetch: notes `err` with the + * ref when it is an archive refusal (TarExtractError or + * ManifestValidationError, exactly); anything else is left alone. A `main` + * SHA that is not a full commit id is GitHub's answer refused before any + * download (a ManifestValidationError too), not an archive: never noted, so + * the untrusted token never reaches the message. + */ +export function noteArchiveRefusal( + err: unknown, + source: InstallSource, + sha: string | null, +): void { + if (sha !== null && !COMMIT_RE.test(sha)) return; + if ( + err instanceof TarExtractError || + err instanceof ManifestValidationError + ) { + refused.set(err, refusalText(source, sha, err.message)); + } +} + +/** The spinner's stop line for a refused archive, so it does not say "failed to reach". */ +export const ARCHIVE_REFUSED_SPINNER = 'pharn-oss archive refused'; + +/** The user-facing text for `err` if fetchRepo noted it as refused, else undefined. */ +export function archiveRefusalMessage(err: unknown): string | undefined { + return typeof err === 'object' && err !== null ? refused.get(err) : undefined; +} diff --git a/src/lib/repo.ts b/src/lib/repo.ts index 61f6f122..e6b61240 100644 --- a/src/lib/repo.ts +++ b/src/lib/repo.ts @@ -1,6 +1,7 @@ import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { noteArchiveRefusal } from './archive-refusal.js'; import { CLAUDE_SETTINGS_FILE, MIN_CLI_FILE, @@ -137,8 +138,15 @@ export interface FetchedRepo { * cache. */ export async function fetchRepo(source: InstallSource): Promise { - if (source.kind === 'release') return fetchAt(source, source.sha); - return fetchAt(source, await fetchCommitSha()); + const sha = source.kind === 'release' ? source.sha : await fetchCommitSha(); + try { + return await fetchAt(source, sha); + } catch (err) { + // Re-thrown unchanged; a refused archive is noted with the ref, so the + // command can say which archive and what to try (lib/archive-refusal.ts). + noteArchiveRefusal(err, source, sha); + throw err; + } } // The download + extract half, at a resolved (or, for `main` only, null) SHA. diff --git a/tests/archive-refusal.test.ts b/tests/archive-refusal.test.ts new file mode 100644 index 00000000..dc9364ce --- /dev/null +++ b/tests/archive-refusal.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from 'vitest'; +import { + archiveRefusalMessage, + noteArchiveRefusal, + refusalText, +} from '../src/lib/archive-refusal.js'; +import { ReleaseResolveError } from '../src/lib/release.js'; +import type { InstallSource } from '../src/lib/release.js'; +import { TarExtractError } from '../src/lib/tar-extract.js'; +import { UpstreamManifestError } from '../src/lib/upstream-manifest.js'; +import { ManifestValidationError } from '../src/lib/validate.js'; + +const SHA = 'a'.repeat(40); +const RELEASE: InstallSource = { + kind: 'release', + tag: 'v7.25.5', + version: '7.25.5', + sha: SHA, +}; +const MAIN: InstallSource = { kind: 'main' }; + +describe('noteArchiveRefusal + archiveRefusalMessage', () => { + it.each([ + ['TarExtractError', new TarExtractError('tar entry has a bad type')], + ['ManifestValidationError', new ManifestValidationError('bad version')], + ['UpstreamManifestError', new UpstreamManifestError('bad manifest')], + ])('notes a %s with the ref and its own reason', (_, err) => { + noteArchiveRefusal(err, RELEASE, SHA); + const message = archiveRefusalMessage(err); + expect(message).toContain( + `pharn-oss release v7.25.5 (commit ${SHA}) was refused`, + ); + expect(message).toContain(`Reason: ${err.message}`); + }); + + it('leaves a network error and a release-resolution refusal unnoted', () => { + const network = new TypeError('fetch failed'); + const resolve = new ReleaseResolveError('no release'); + noteArchiveRefusal(network, MAIN, SHA); + noteArchiveRefusal(resolve, RELEASE, SHA); + expect(archiveRefusalMessage(network)).toBeUndefined(); + expect(archiveRefusalMessage(resolve)).toBeUndefined(); + }); + + it('leaves the refusal of a malformed main SHA unnoted: no archive was fetched', () => { + const err = new ManifestValidationError('commit SHA is invalid'); + noteArchiveRefusal(err, MAIN, 'not-a-sha\u001b[2J'); + expect(archiveRefusalMessage(err)).toBeUndefined(); + }); + + it('answers undefined for an error never noted, and for a non-object', () => { + expect(archiveRefusalMessage(new TarExtractError('x'))).toBeUndefined(); + expect(archiveRefusalMessage(undefined)).toBeUndefined(); + expect(archiveRefusalMessage('a string')).toBeUndefined(); + }); +}); + +describe('refusalText', () => { + it('names an unresolved main tip without a SHA', () => { + expect(refusalText(MAIN, null, 'r')).toContain( + 'pharn-oss main (refs/heads/main, commit not resolved) was refused', + ); + }); + + it('escapes an unsafe character left in the reason', () => { + const text = refusalText(MAIN, SHA, 'entry \u001b[31mred'); + expect(text).not.toContain('\u001b'); + expect(text).toContain('Reason: entry \\u001b[31mred'); + }); + + it('offers only --ref values the CLI accepts', () => { + for (const text of [ + refusalText(RELEASE, SHA, 'r'), + refusalText(MAIN, SHA, 'r'), + ]) { + const refs = [...text.matchAll(/--ref (\S+?)`/g)].map((m) => m[1]); + expect(refs.length).toBeGreaterThan(0); + for (const ref of refs) expect(['main', 'latest']).toContain(ref); + } + }); +}); diff --git a/tests/commands/add.test.ts b/tests/commands/add.test.ts index 9ab20cdc..4d54ca53 100644 --- a/tests/commands/add.test.ts +++ b/tests/commands/add.test.ts @@ -6,6 +6,7 @@ import { writeFileSync, } from 'node:fs'; import { join } from 'node:path'; +import { stripVTControlCharacters } from 'node:util'; import { afterEach, describe, expect, it, vi } from 'vitest'; import * as clack from '@clack/prompts'; import { CANCEL } from '../helpers.js'; @@ -945,3 +946,27 @@ describe('a release whose manifest names a path outside the outer bound', () => expect(snapshot()).toEqual(before); }); }); + +describe('add on a refused pharn-oss archive', () => { + it('names the release, stops the spinner as refused, and writes nothing', async () => { + await installFresh(); + serveTip(SHA_V1, '1.0.0', { links: { [A11Y]: '../../../.agents/a11y' } }); + const before = snapshot(); + expect(await run(() => runAdd('a11y'))).toBe(1); + expect(logs('error').join('\n')).toContain( + `pharn-oss release v1.0.0 (commit ${SHA_V1}) was refused`, + ); + const stops = vi + .mocked(clack.spinner) + .mock.results.flatMap((r) => + ( + r.value as { stop: { mock: { calls: unknown[][] } } } + ).stop.mock.calls.map((c) => + stripVTControlCharacters(String(c[0] ?? '')), + ), + ); + expect(stops).toContain('pharn-oss archive refused'); + expect(stops).not.toContain('Failed to fetch capabilities'); + expect(snapshot()).toEqual(before); + }); +}); diff --git a/tests/commands/init.test.ts b/tests/commands/init.test.ts index ced7c9a7..ecb5c680 100644 --- a/tests/commands/init.test.ts +++ b/tests/commands/init.test.ts @@ -2054,3 +2054,124 @@ describe('a release whose manifest names a path outside the outer bound', () => expect(snapshot()).toEqual(before); }); }); + +// --------------------------------------------------------------------------- +// A refused pharn-oss archive. The symlink sits at a path the manifest +// declares, so the extractor refuses it however narrowly it unpacks. The +// message names the ref, blames the archive, keeps the original reason and +// lists only steps the CLI has; the raw error is behind PHARN_DEBUG. +// --------------------------------------------------------------------------- + +describe('init on a refused pharn-oss archive', () => { + const LINKED = { [SECURITY]: '../../../.agents/skills/security' }; + const ISSUES = 'https://github.com/pharn-dev/pharn-oss/issues'; + + it('on the release channel: names the tag and commit, blames the archive, offers --ref main, and changes nothing', async () => { + const clones = watchClones(); + serveTip(SHA_V1, '1.0.0', { links: LINKED }); + const before = snapshot(); + expect(await run(() => runInit({ yes: true }))).toBe(1); + const shown = errors(); + expect(shown).toContain( + `pharn-oss release v1.0.0 (commit ${SHA_V1}) was refused: its published archive failed pharn's checks.`, + ); + expect(shown).toContain( + 'The problem is in that pharn-oss archive, not in your project; nothing in your project was changed.', + ); + expect(shown).toContain( + `Reason: tar entry has an unsupported type '2' at a path pharn installs (only a regular file is accepted there): pharn-oss-${SHA_V1.slice(0, 7)}/${SECURITY}`, + ); + expect(shown).toContain( + 'No option skips this check: forcing an update or answering yes does not help. Next steps:', + ); + expect(shown).toContain( + '- install the tip of main instead: `pharn init --ref main` (`pharn update --ref main` for an existing install)', + ); + expect(shown).toContain('`npm install -g @pharn-dev/pharn@latest`'); + expect(shown).toContain( + `re-run once pharn-oss publishes a fixed release, and report this at ${ISSUES}`, + ); + // A release has no `--ref latest` step to offer, and the network was reached. + expect(shown).not.toContain('--ref latest'); + expect(shown).not.toContain('Could not reach'); + expect(informed()).toContain('PHARN_DEBUG=1'); + // The spinner agrees: refused, not a failure to fetch. + const stops = vi + .mocked(clack.spinner) + .mock.results.flatMap((r) => + ( + r.value as { stop: { mock: { calls: unknown[][] } } } + ).stop.mock.calls.map((c) => + stripVTControlCharacters(String(c[0] ?? '')), + ), + ); + expect(stops).toContain('pharn-oss archive refused'); + expect(stops).not.toContain('Failed to fetch PHARN'); + // The sentence is true: no config, no .claude/, no lock, nothing at all. + expect(snapshot()).toEqual(before); + expect(exists('pharn.config.json')).toBe(false); + expect(exists('.claude')).toBe(false); + expect(exists('pharn/.lock')).toBe(false); + expect(clones()).toEqual([]); + }); + + it('on the main channel: names main and the commit, and offers --ref latest', async () => { + serveTip(SHA_V2, '1.0.0', { links: LINKED }); + const before = snapshot(); + expect(await run(() => runInit({ yes: true, ref: 'main' }))).toBe(1); + const shown = errors(); + expect(shown).toContain( + `pharn-oss main at commit ${SHA_V2} was refused: its published archive failed pharn's checks.`, + ); + expect(shown).toContain( + `Reason: tar entry has an unsupported type '2' at a path pharn installs (only a regular file is accepted there): pharn-oss-${SHA_V2.slice(0, 7)}/${SECURITY}`, + ); + expect(shown).toContain( + '- go back to verified releases: `pharn init --ref latest` (`pharn update --ref latest` for an existing install)', + ); + expect(shown).toContain( + `re-run later, once main is fixed, and report this at ${ISSUES}`, + ); + expect(shown).not.toContain('--ref main'); + expect(snapshot()).toEqual(before); + }); + + it('on the main channel with the commit unresolved: says so instead of a SHA', async () => { + failures.tip = 'throw'; + serveTip(SHA_V2, '1.0.0', { links: LINKED }); + expect(await run(() => runInit({ yes: true, ref: 'main' }))).toBe(1); + expect(errors()).toContain( + 'pharn-oss main (refs/heads/main, commit not resolved) was refused', + ); + }); + + it('a manifest sha256 mismatch is reported the same way, its own reason kept', async () => { + const tree = manifestTree('7.20.0'); + serveTip(SHA_V1, '7.20.0', { + tree: { ...tree, [SECURITY]: 'swapped after the manifest was made\n' }, + }); + const before = snapshot(); + expect(await run(() => runInit({ yes: true }))).toBe(1); + const shown = errors(); + expect(shown).toContain( + `pharn-oss release v7.20.0 (commit ${SHA_V1}) was refused`, + ); + expect(shown).toContain( + `Reason: pharn-oss's pharn-install.json declares a sha256 for ${SECURITY} that its bytes do not match`, + ); + expect(shown).toContain('`pharn init --ref main`'); + expect(snapshot()).toEqual(before); + }); + + it('under PHARN_DEBUG=1 the raw refusal is dumped to stderr instead of the hint', async () => { + vi.stubEnv('PHARN_DEBUG', '1'); + serveTip(SHA_V1, '1.0.0', { links: LINKED }); + expect(await run(() => runInit({ yes: true }))).toBe(1); + expect(errors()).toContain('pharn-oss release v1.0.0'); + expect(informed()).not.toContain('PHARN_DEBUG=1'); + const raw = stripVTControlCharacters(stderr().join('\n')); + expect(raw).toContain( + `TarExtractError: tar entry has an unsupported type '2' at a path pharn installs (only a regular file is accepted there): pharn-oss-${SHA_V1.slice(0, 7)}/${SECURITY}`, + ); + }); +}); diff --git a/tests/commands/status.test.ts b/tests/commands/status.test.ts index 09de82c8..96d97838 100644 --- a/tests/commands/status.test.ts +++ b/tests/commands/status.test.ts @@ -1,5 +1,6 @@ import { mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; import { hostname } from 'node:os'; +import { stripVTControlCharacters } from 'node:util'; import { afterEach, describe, expect, it, vi, type Mock } from 'vitest'; import * as clack from '@clack/prompts'; import { restoreNodeVersion, setNodeVersion } from '../helpers.js'; @@ -1215,3 +1216,36 @@ describe('a release whose manifest names a path outside the outer bound', () => expect(snapshot()).toEqual(before); }); }); + +describe('status on a refused pharn-oss archive', () => { + // Every spinner stop line, colour stripped. + const stops = (): string[] => + vi + .mocked(clack.spinner) + .mock.results.flatMap((r) => + (r.value as { stop: Mock }).stop.mock.calls.map((c) => + stripVTControlCharacters(String(c[0] ?? '')), + ), + ); + + it('stops the spinner with "pharn-oss archive refused", not "Failed to reach"', async () => { + await installFresh(); + serveTip(SHA_V2, '1.1.0', { + links: { [CONSTITUTION]: '../.agents/constitution' }, + }); + expect(await status()).toBe(1); + expect(stops()).toContain('pharn-oss archive refused'); + expect(stops().join('\n')).not.toContain('Failed to reach'); + expect(printed()).toContain( + `pharn-oss release v1.1.0 (commit ${SHA_V2}) was refused`, + ); + }); + + it('keeps "Failed to reach" for a download that failed', async () => { + await installFresh(); + failures.tarball = 'throw'; + expect(await status()).toBe(1); + expect(stops().join('\n')).toContain('Failed to reach'); + expect(stops()).not.toContain('pharn-oss archive refused'); + }); +}); diff --git a/tests/commands/update.test.ts b/tests/commands/update.test.ts index d2e9d51a..7e9c889e 100644 --- a/tests/commands/update.test.ts +++ b/tests/commands/update.test.ts @@ -3672,3 +3672,39 @@ describe('a release whose manifest names a path outside the outer bound', () => expect(clones()).toEqual([]); }); }); + +describe('update on a refused pharn-oss archive', () => { + it('names the release and commit, says the project was not changed, and writes nothing', async () => { + await installFresh(); + serveTip(SHA_V2, '1.1.0', { + links: { [SECURITY]: '../../../.agents/skills/security' }, + }); + const clones = watchClones(); + const before = snapshot(); + expect(await run(() => runUpdate({ yes: true }))).toBe(1); + const shown = printed(); + expect(shown).toContain( + `pharn-oss release v1.1.0 (commit ${SHA_V2}) was refused`, + ); + expect(shown).toContain('nothing in your project was changed'); + expect(shown).toContain( + `Reason: tar entry has an unsupported type '2' at a path pharn installs (only a regular file is accepted there): pharn-oss-${SHA_V2.slice(0, 7)}/${SECURITY}`, + ); + expect(shown).toContain('`pharn update --ref main`'); + expect(snapshot()).toEqual(before); + expect(exists('pharn/.lock')).toBe(false); + expect(clones()).toEqual([]); + }); + + it('a --dry-run on main names main and its commit', async () => { + await installFresh({ ref: 'main' }); + serveTip(SHA_V2, '1.1.0', { + links: { [SECURITY]: '../../../.agents/skills/security' }, + }); + expect(await run(() => runUpdate({ dryRun: true, ref: 'main' }))).toBe(1); + expect(printed()).toContain( + `pharn-oss main at commit ${SHA_V2} was refused`, + ); + expect(printed()).toContain('`pharn update --ref latest`'); + }); +}); diff --git a/tests/release-consistency.test.ts b/tests/release-consistency.test.ts index 4a8447b1..1926e9a4 100644 --- a/tests/release-consistency.test.ts +++ b/tests/release-consistency.test.ts @@ -96,6 +96,7 @@ const KNOWN_TAGS: readonly string[] = [ 'v0.21.3', 'v0.21.4', 'v0.21.5', + 'v0.21.6', ]; // 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 6f2d9c89..b68ef2ef 100644 --- a/tests/repo.test.ts +++ b/tests/repo.test.ts @@ -14,6 +14,7 @@ import { REPO, REPO_BRANCH } from '../src/lib/constants.js'; import { ManifestValidationError } from '../src/lib/validate.js'; import { UpstreamManifestError } from '../src/lib/upstream-manifest.js'; import { TarExtractError } from '../src/lib/tar-extract.js'; +import { archiveRefusalMessage } from '../src/lib/archive-refusal.js'; import { codeloadArchive } from './support/tar-fixture.js'; import { MANIFEST, @@ -856,3 +857,84 @@ describe('fetchRepo — only the listed paths are unpacked (CORE-386)', () => { ).resolves.toMatchObject({ skillsVersion: '7.20.0' }); }); }); + +// fetchRepo re-throws a refused archive UNCHANGED (its class is the contract) +// and notes the ref it fetched, which the command boundary turns into the +// user-facing message (lib/archive-refusal.ts). +describe('fetchRepo — a refused archive keeps its error and is noted with the ref', () => { + const linked = { [SECURITY]: '../../../.agents/skills/security' }; + + beforeEach(() => { + sandbox = mkdtempSync(join(tmpdir(), 'pharn-repo-sandbox-')); + process.env.TMPDIR = sandbox; + process.env.TEMP = sandbox; + process.env.TMP = sandbox; + }); + + 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('a symlink on the release channel: a TarExtractError, noted with the tag and commit', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => + tarResponse(codeloadArchive(VALID_SHA, manifestTree('7.20.0'), linked)), + ), + ); + const err = await fetchRepo({ + kind: 'release', + tag: 'v7.20.0', + version: '7.20.0', + sha: VALID_SHA, + }).catch((e: unknown) => e); + expect(err).toBeInstanceOf(TarExtractError); + expect(archiveRefusalMessage(err)).toContain( + `pharn-oss release v7.20.0 (commit ${VALID_SHA}) was refused`, + ); + expect(archiveRefusalMessage(err)).toContain( + `Reason: ${(err as Error).message}`, + ); + expect(leftoverTempDirs()).toEqual([]); + }); + + it('a symlink on main: noted with the resolved commit', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => + url === RESOLVE_URL + ? new Response(`${VALID_SHA}\n`) + : tarResponse( + codeloadArchive(VALID_SHA, manifestTree('7.20.0'), linked), + ), + ), + ); + const err = await fetchRepo({ kind: 'main' }).catch((e: unknown) => e); + expect(err).toBeInstanceOf(TarExtractError); + expect(archiveRefusalMessage(err)).toContain( + `pharn-oss main at commit ${VALID_SHA} was refused`, + ); + }); + + it('a download failure is not an archive refusal: thrown as is, not noted', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + throw new TypeError('fetch failed'); + }), + ); + const err = await fetchRepo({ + kind: 'release', + tag: 'v7.20.0', + version: '7.20.0', + sha: VALID_SHA, + }).catch((e: unknown) => e); + expect(err).toBeInstanceOf(TypeError); + expect(archiveRefusalMessage(err)).toBeUndefined(); + }); +}); diff --git a/tests/support/harness.ts b/tests/support/harness.ts index 6c3b2039..c6c6ed38 100644 --- a/tests/support/harness.ts +++ b/tests/support/harness.ts @@ -161,24 +161,34 @@ export const upstream: { // false: serve the tree as is, with no pharn-install.json — a pharn-oss // older than 7.21.0, which every command refuses. seal: boolean; + // Tree paths served as symbolic links to these targets (tar-fixture.ts), + // still declared by the manifest built from the tree. + links: Record; } = { sha: SHA_V1, version: '1.0.0', tree: upstreamTree('1.0.0'), published: true, seal: true, + links: {}, }; export function serveTip( sha: string, version: string, - opts: { published?: boolean; tree?: Tree; seal?: boolean } = {}, + opts: { + published?: boolean; + tree?: Tree; + seal?: boolean; + links?: Record; + } = {}, ): void { upstream.sha = sha; upstream.version = version; upstream.tree = opts.tree ?? upstreamTree(version); upstream.published = opts.published ?? true; upstream.seal = opts.seal ?? true; + upstream.links = opts.links ?? {}; } // The bytes the tarball carries: the tree plus a manifest that declares it, @@ -229,7 +239,9 @@ export const fetchStub = vi.fn(async (input: unknown): Promise => { // An unresolved tip (`failures.tip`) floats the branch: the same bytes. if (url === tarballUrl(upstream.sha) || url === tarballUrl(FLOATING_REF)) { return new Response( - new Uint8Array(codeloadArchive(upstream.sha, servedTree())), + new Uint8Array( + codeloadArchive(upstream.sha, servedTree(), upstream.links), + ), ); } throw new Error(`unexpected fetch: ${url}`); diff --git a/tests/support/tar-fixture.ts b/tests/support/tar-fixture.ts index a41d982b..888cad64 100644 --- a/tests/support/tar-fixture.ts +++ b/tests/support/tar-fixture.ts @@ -10,7 +10,12 @@ import { gzipSync } from 'node:zlib'; const BLOCK = 512; -function header(name: string, type: string, size: number): Buffer { +function header( + name: string, + type: string, + size: number, + linkname = '', +): Buffer { const block = Buffer.alloc(BLOCK); block.write(name, 0, 100, 'latin1'); block.write('000644 \0', 100, 8, 'latin1'); @@ -20,6 +25,7 @@ function header(name: string, type: string, size: number): Buffer { block.write('00000000000 ', 136, 12, 'latin1'); block.write(' ', 148, 8, 'latin1'); block.write(type, 156, 1, 'latin1'); + block.write(linkname, 157, 100, 'latin1'); block.write('ustar\0', 257, 6, 'latin1'); block.write('00', 263, 2, 'latin1'); let sum = 0; @@ -50,10 +56,16 @@ export function githubArchive(sha: string): Buffer { * before its first file, as codeload's archives carry them. Names go into the * 100-byte ustar name field with no prefix split, so a path plus the 18-byte * `pharn-oss-/` root must stay under 100 bytes — refused, not truncated. + * + * `links` maps a path of `files` to a target: that entry is written as a + * symbolic link (typeflag '2') instead of its content, the way codeload ships + * a tracked git symlink. Its place in the tree (and so in a manifest built + * from the tree) is kept. */ export function codeloadArchive( sha: string, files: Readonly>, + links: Readonly> = {}, ): 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 @@ -62,10 +74,10 @@ export function codeloadArchive( Object.keys(files) .sort() .map((rel) => [rel, files[rel]]), - )}`; + )}\0${JSON.stringify(Object.entries(links).sort())}`; const hit = archiveCache.get(key); if (hit) return hit; - const archive = buildArchive(sha, files); + const archive = buildArchive(sha, files, links); archiveCache.set(key, archive); return archive; } @@ -75,6 +87,7 @@ const archiveCache = new Map(); function buildArchive( sha: string, files: Readonly>, + links: Readonly>, ): Buffer { const root = `pharn-oss-${sha.slice(0, 7)}`; const parts = [ @@ -95,7 +108,12 @@ function buildArchive( if (Buffer.byteLength(name) >= 100) { throw new Error(`tar fixture: ${name} does not fit the ustar name field`); } - parts.push(entry(name, '0', files[rel])); + const target = links[rel]; + parts.push( + target === undefined + ? entry(name, '0', files[rel]) + : header(name, '2', 0, target), + ); } parts.push(Buffer.alloc(BLOCK * 2)); return gzipSync(Buffer.concat(parts));