diff --git a/src/cli.ts b/src/cli.ts index 9b3ee461fe..f09cbfd9ff 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -29,7 +29,7 @@ import { recordEngineBootstrap } from "./storage/runtime-status.js"; import { configFile as defaultConfigFile } from "./paths.js"; import { log as loggerLog } from "./logger.js"; import { createAutoRestartHandler } from "./restart.js"; -import { checkForUpdate, startAutoUpdate } from "./update.js"; +import { checkForUpdate, fetchRegistryVersion, startAutoUpdate } from "./update.js"; import { startAdvisoryWatcher, getAdvisoryState, advisoryDeferring, advisoryBlocksVersion } from "./advisory.js"; import { startReleaseNotesWatcher } from "./update-notes.js"; import { resolveProxy } from "./upstream-proxy.js"; @@ -39,6 +39,7 @@ import { runLaunch, runTestPi, isLaunchClient, type ClientName } from "./launche import { exportSession } from "./export.js"; import { renderJson, renderText, runDiff } from "./acp-cache-diff.js"; import { renderDoctorReport, runDoctor } from "./doctor.js"; +import { auditDshProfileCopyProvenance } from "./provenance.js"; import { VERSION, PACKAGE_NAME, BUILD_COMMIT } from "./version.js"; const HELP = `bili ${VERSION} — billion-context proxy @@ -671,4 +672,22 @@ export async function main(): Promise { resolveProxy: (url) => resolveProxy(opts.routes, opts.proxy, url, opts.proxyFallback), }); } + // #3160: loud provenance detection for dsh profile copies. Detached and + // fail-open by contract — a wedged copy must never delay or break + // startup, and the check itself only reads state (no install action), so + // it stays out of src/update.ts's no-op-release prerequisite. + void (async () => { + try { + await auditDshProfileCopyProvenance({ + log: loggerLog, + fetchRegistryVersion: () => + fetchRegistryVersion( + { resolveProxy: (url) => resolveProxy(opts.routes, opts.proxy, url, opts.proxyFallback), updateTag: opts.updateTag }, + PACKAGE_NAME, + ), + }); + } catch { + // detection is advisory — never affect startup + } + })(); } diff --git a/src/doctor.ts b/src/doctor.ts index 2e339c41ba..04843820a5 100644 --- a/src/doctor.ts +++ b/src/doctor.ts @@ -11,6 +11,8 @@ import { PLUGIN_AGENTS, UPDATE_CHANNEL, claudeDesktopPresent, inspectLanePresenc import { findInstallDir, fetchRegistryVersion, hostManagedInstall, isGitWorkingTree, isVersionNewer, lastUpdateCheckTime, normalizeUpdateTag, staleInstallStatus } from "./update.js"; import { describeAdvisory, evaluateAdvisories, type AdvisoryEvaluation } from "./advisory.js"; import { claudeRoutingWarningFile } from "./paths.js"; +import { resolveDshHome } from "./client-config.js"; +import { dshProfileCopyFindings } from "./provenance.js"; type LaneVerdict = "ok" | "stale" | "frozen" | "broken" | "absent"; @@ -205,6 +207,7 @@ function laneRowsFor(agent: PluginAgent, presence: ReturnType { const missing = p.bundleInstalled && p.copyVersion === undefined; const row: DoctorLane = { @@ -219,6 +222,14 @@ function laneRowsFor(agent: PluginAgent, presence: ReturnType= target reads as +// "already newest" and is skipped, so the inner === targetVersion skip in +// refreshDshProfileBundles (src/dsh-channel.ts) is never reached. A copy +// dropped out-of-band at a fabricated higher version therefore wedges the +// profile forever — exactly the #3160 incident (a hand-made 1.2.9 sitting in +// the desktop profile beside a lockfile that still resolves 0.1.196). +// +// This module is DETECTION ONLY: it reads state and warns loudly. It never +// installs, writes, or spawns anything, so it stays out of the install-lane +// contract's single-writer rule and out of src/update.ts's human-gated +// no-op-release prerequisite. Convergence (the equality gate) is the separate +// follow-up the issue thread agreed on. + +import fs from "node:fs"; +import path from "node:path"; +import { DSH_PACKAGE, dshProfileDirs, dshProfileDepSpec, isRegistryDepSpec } from "./dsh-channel.js"; +import { isVersionNewer } from "./update.js"; +import type { Logger } from "./logger.js"; + +type ProvenanceFindingKind = "copy-vs-lock" | "manifest-vs-lock" | "copy-vs-manifest" | "spec-above-registry" | "build-divergence"; + +interface ProvenanceFinding { + profile: string; + kind: ProvenanceFindingKind; + /** The on-disk copy's declared version, when readable. */ + copyVersion?: string; + /** The lockfile's resolved version, when a lockfile entry exists. */ + lockVersion?: string; + /** The profile manifest's declared spec. */ + spec?: string; + /** The registry's latest version for the configured update tag. */ + registryVersion?: string; + /** One-sentence, human-ready description (no log prefix). */ + detail: string; +} + +/** A pnpm-lock.yaml / package-lock.json resolution of the billion-context + * dependency: what the manifest asked for (specifier) and what the lockfile + * resolved it to (version). */ +interface LockResolution { + specifier?: string; + version?: string; +} + +function readJsonFile(file: string): unknown { + try { + return JSON.parse(fs.readFileSync(file, "utf8")); + } catch { + return undefined; + } +} + +/** The profile's installed copy version — node_modules//package.json's + * version field. Undefined when the mount is declared but missing (that is + * doctor's "broken" verdict, not a provenance finding). */ +function readCopyVersion(profileDir: string, pkg: string = DSH_PACKAGE): string | undefined { + const doc = readJsonFile(path.join(profileDir, "node_modules", pkg, "package.json")) as { version?: unknown } | undefined; + return typeof doc?.version === "string" ? doc.version : undefined; +} + +/** The profile copy's build provenance — dist/build-info.json's commit field + * (written by this repo's build). Undefined when absent (a release-channel + * install may legitimately lack it), so absence is never a finding. */ +function readCopyBuildCommit(profileDir: string, pkg: string = DSH_PACKAGE): string | undefined { + const doc = readJsonFile(path.join(profileDir, "node_modules", pkg, "dist", "build-info.json")) as { commit?: unknown } | undefined; + return typeof doc?.commit === "string" ? doc.commit : undefined; +} + +/** Parse the pnpm-lock.yaml entry for `pkg`. Handles the two shapes pnpm has + * written across lockfile majors: the flat `dependencies:` object form and + * the `importers:` / `specifiers:` forms of v6+. Returns undefined when the + * file is absent or carries no entry for the package (never guesses from a + * sibling entry). */ +function readPnpmLockResolution(profileDir: string, pkg: string = DSH_PACKAGE): LockResolution | undefined { + let text: string; + try { + text = fs.readFileSync(path.join(profileDir, "pnpm-lock.yaml"), "utf8"); + } catch { + return undefined; + } + const lines = text.split("\n"); + for (let i = 0; i < lines.length; i++) { + // The bare-name entry only: `billion-context@0.1.197:` snapshot keys + // carry an @version suffix and must not match. + const head = lines[i].match(new RegExp(`^\\s+${pkg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}:\\s*(\\S*)\\s*$`)); + if (!head) continue; + const sameLine = head[1]; + if (sameLine) return { specifier: sameLine }; // specifiers: map form + const entryIndent = lines[i].match(/^\s*/)![0].length; + const block: LockResolution = {}; + for (let j = i + 1; j < lines.length; j++) { + const line = lines[j]; + if (line.trim() === "") continue; + const indent = line.match(/^\s*/)![0].length; + if (indent <= entryIndent) break; // sibling entry — this block ended + const spec = line.match(/^\s+specifier:\s*(\S+)/); + if (spec) block.specifier = spec[1]; + const version = line.match(/^\s+version:\s*(\S+)/); + if (version) block.version = version[1]; + if (block.specifier !== undefined && block.version !== undefined) break; + } + if (block.specifier !== undefined || block.version !== undefined) return block; + } + return undefined; +} + +/** package-lock.json fallback for npm-materialized profiles: the root's + * declared dependency spec plus the resolved node_modules/ version. */ +function readPackageLockResolution(profileDir: string, pkg: string = DSH_PACKAGE): LockResolution | undefined { + const doc = readJsonFile(path.join(profileDir, "package-lock.json")) as + | { packages?: Record }> } + | undefined; + if (!doc?.packages) return undefined; + const resolved = doc.packages[`node_modules/${pkg}`]; + const root = doc.packages[""]; + const spec = root?.dependencies?.[pkg]; + const out: LockResolution = {}; + if (typeof spec === "string") out.specifier = spec; + if (typeof resolved?.version === "string") out.version = resolved.version; + return out.specifier !== undefined || out.version !== undefined ? out : undefined; +} + +/** The base version a registry-form spec pins ("^0.1.196" → "0.1.196"), + * or undefined for shapes this module does not judge (dist-tags, exotic + * ranges). */ +function specBaseVersion(spec: string): string | undefined { + const m = spec.match(/^[\s^~>=<]*(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/); + return m ? m[1] : undefined; +} + +/** Does `version` satisfy a simple caret/tilde/exact spec? Returns undefined + * for anything more exotic — an unjudgeable spec must never produce a + * finding. Prerelease semantics are deliberately simplified: a spec without + * a prerelease does not admit one. */ +function specAdmits(spec: string, version: string): boolean | undefined { + const m = spec.match(/^([\^~]?)(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?$/); + if (!m) return undefined; + const [, op, majS, minS, patchS] = m; + const maj = Number(majS); + const min = Number(minS); + const patch = Number(patchS); + const v = version.match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/); + if (!v) return false; + const vmaj = Number(v[1]); + const vmin = Number(v[2]); + const vpatch = Number(v[3]); + if (vmaj !== maj) return false; + if (op === "^") return vmin > min || (vmin === min && vpatch >= patch); + if (op === "~") return vmin === min && vpatch >= patch; + return vmin === min && vpatch === patch; +} + +/** The actionable tail shared by every finding: name the wedge (#3160's + * one-way gate) and the host-channel command that clears it. */ +function remediation(profile: string, registryVersion?: string): string { + const target = registryVersion !== undefined ? `billion-context@${registryVersion}` : "billion-context@"; + return `self-heal skips copies whose version is not older than the target (#3160), so this profile will never converge on its own — reinstall through the host channel: run \`dsh plugin --profile ${profile} add ${target}\` from a shell where \`dsh\` resolves, or \`bili plugin install dsh\``; +} + +/** All provenance findings for ONE profile dir. Pure and synchronous; never + * throws. Local pins (link:/file:) and profiles without an installed copy + * are deliberately silent — both are legitimate states under the #1196 + * install-lane contract. */ +export function dshProfileCopyFindings( + profileDir: string, + registryVersion?: string, + options?: { buildBaseline?: { version: string; commit: string; profile: string } }, +): ProvenanceFinding[] { + const profile = path.basename(profileDir); + const spec = dshProfileDepSpec(profileDir); + if (spec === undefined) return []; // no dependency — not this lane + if (!isRegistryDepSpec(spec)) return []; // local pin — manual dev lane by design + const copyVersion = readCopyVersion(profileDir); + if (copyVersion === undefined) return []; // declared-but-missing: doctor's "broken" verdict owns that + const lock = readPnpmLockResolution(profileDir) ?? readPackageLockResolution(profileDir); + const findings: ProvenanceFinding[] = []; + + if (lock?.version !== undefined && lock.version !== copyVersion) { + findings.push({ + profile, + kind: "copy-vs-lock", + copyVersion, + lockVersion: lock.version, + spec, + detail: `billion-context copy v${copyVersion} does not match the lockfile resolution v${lock.version} — the copy was likely written out-of-band (the host package manager never resolved it); ${remediation(profile, registryVersion)}`, + }); + } + if (lock?.specifier !== undefined && lock.specifier !== spec) { + findings.push({ + profile, + kind: "manifest-vs-lock", + copyVersion, + spec, + detail: `profile manifest declares ${spec} but the lockfile records ${lock.specifier} — the declaration and the resolution disagree, so the host's next reconcile may roll the copy backwards; ${remediation(profile, registryVersion)}`, + }); + } + if (lock === undefined) { + // No lockfile at all: the manifest spec is the only declared truth. + const admits = specAdmits(spec, copyVersion); + if (admits === false) { + findings.push({ + profile, + kind: "copy-vs-manifest", + copyVersion, + spec, + detail: `billion-context copy v${copyVersion} does not satisfy the manifest spec ${spec}, and no lockfile exists to explain the difference; ${remediation(profile, registryVersion)}`, + }); + } + } + if (registryVersion !== undefined) { + // A registry-form spec may never resolve above the registry's latest + // published version for the configured tag — a spec that does was + // fabricated, whatever the lockfile says. + const base = specBaseVersion(spec); + if (base !== undefined && isVersionNewer(base, registryVersion)) { + findings.push({ + profile, + kind: "spec-above-registry", + copyVersion, + spec, + registryVersion, + detail: `profile manifest declares ${spec}, whose base version v${base} is NEWER than the registry's ${registryVersion} — no registry resolution can produce this spec, so the manifest (and likely the copy beside it) was hand-edited; ${remediation(profile, registryVersion)}`, + }); + } + } + // Build provenance: two profiles running the SAME version from DIFFERENT + // build commits cannot both have come from the registry channel. + const buildCommit = readCopyBuildCommit(profileDir); + const baseline = options?.buildBaseline; + if (buildCommit !== undefined && baseline?.commit !== undefined && copyVersion === baseline.version && buildCommit !== baseline.commit) { + findings.push({ + profile, + kind: "build-divergence", + copyVersion, + spec, + detail: `dsh profile ${baseline.profile} runs v${copyVersion} from build ${baseline.commit} while this profile runs the same version from build ${buildCommit} — same-version/different-build copies mean at least one never came from the registry channel; ${remediation(profile, registryVersion)}`, + }); + } + return findings; +} + +/** Walk every dsh profile and log one warn per finding. Detached by contract: + * never throws, never installs. `fetchRegistryVersion` is called at most once + * and only when at least one profile carries a registry-pinned copy — the + * common machine (no dsh, or only local pins) pays no network cost. */ +export async function auditDshProfileCopyProvenance(opts?: { + env?: NodeJS.ProcessEnv; + log?: Logger; + fetchRegistryVersion?: () => Promise; +}): Promise { + const log = opts?.log ?? ((): void => {}); + let dirs: string[]; + try { + dirs = dshProfileDirs(opts?.env); + } catch { + return []; // dsh has never run on this machine — nothing to audit + } + const candidates = dirs.filter((dir) => { + const spec = dshProfileDepSpec(dir); + return spec !== undefined && isRegistryDepSpec(spec) && readCopyVersion(dir) !== undefined; + }); + if (candidates.length === 0) return []; + + let registryVersion: string | undefined; + if (opts?.fetchRegistryVersion) { + try { + registryVersion = await opts.fetchRegistryVersion(); + } catch { + registryVersion = undefined; // fail-open: lockfile/manifest checks still run + } + } + const findings: ProvenanceFinding[] = []; + // First profile per version establishes the build baseline; later + // profiles on the same version are judged against it. + const baselines = new Map(); + for (const dir of candidates) { + const copyVersion = readCopyVersion(dir); + const buildCommit = copyVersion !== undefined ? readCopyBuildCommit(dir) : undefined; + if (copyVersion === undefined || buildCommit === undefined) continue; + if (!baselines.has(copyVersion)) baselines.set(copyVersion, { commit: buildCommit, profile: path.basename(dir) }); + } + for (const dir of candidates) { + const copyVersion = readCopyVersion(dir); + findings.push(...dshProfileCopyFindings(dir, registryVersion, { + buildBaseline: copyVersion !== undefined ? { version: copyVersion, ...(baselines.get(copyVersion) ?? { commit: "", profile: "" }) } : undefined, + })); + } + for (const f of findings) { + log("warn", `[dsh-profile] ${f.profile}: ${f.detail}`); + } + return findings; +} diff --git a/tests/issue3160-dsh-profile-copy-provenance.test.ts b/tests/issue3160-dsh-profile-copy-provenance.test.ts new file mode 100644 index 0000000000..02cb3b3926 --- /dev/null +++ b/tests/issue3160-dsh-profile-copy-provenance.test.ts @@ -0,0 +1,324 @@ +// #3160: a dsh profile copy can be wedged by an out-of-band install whose +// version is not older than the registry's — every self-heal path gates on +// one-way semver (src/update.ts), so the copy never converges and the +// divergence is otherwise silent (readDiskVersion has no provenance). These +// tests pin the detection module: lockfile/manifest/copy disagreement, specs +// no registry resolution can produce, and build divergence across profiles. + +import { test, after } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import type { Logger } from "../src/logger.ts"; +import { rmrf } from "./tmp-rm.ts"; + +// LOCK_FILE is frozen at update.ts module load (reached through +// provenance.ts's isVersionNewer import) — redirect the cache tree BEFORE +// importing it (same discipline as update-dsh-self-refresh.test.ts). +const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "bili-issue3160-provenance-"))); +process.env.XDG_CACHE_HOME = path.join(root, "cache"); + +const { auditDshProfileCopyProvenance, dshProfileCopyFindings } = await import("../src/provenance.ts"); + +after(() => { + delete process.env.XDG_CACHE_HOME; + rmrf(root); +}); + +interface Fixture { + base: string; + dshHome: string; + profiles: Record; + setProfile(name: string): void; + cleanup(): void; +} + +/** A dsh home. Each profile gets `manifestSpec` (or none), a copy at + * `copyVersion` (or none), a pnpm-lock block (or none), and a build-info + * commit. The profile package.json is only written when a manifest spec is + * given, so a profile without the dependency stays absent rather than empty. */ +function makeFixture(opts: { + profiles: Record; +}): Fixture { + const base = fs.mkdtempSync(path.join(root, "fx-")); + const dshHome = path.join(base, "dsh"); + fs.mkdirSync(dshHome, { recursive: true }); + const profiles: Record = {}; + for (const [name, p] of Object.entries(opts.profiles)) { + const dir = path.join(dshHome, "profiles", name); + profiles[name] = dir; + fs.mkdirSync(dir, { recursive: true }); + if (p.manifestSpec !== undefined) { + fs.writeFileSync( + path.join(dir, "package.json"), + JSON.stringify({ private: true, dependencies: { "billion-context": p.manifestSpec } }), + ); + } + if (p.copyVersion !== undefined) { + const installDir = path.join(dir, "node_modules", "billion-context"); + fs.mkdirSync(installDir, { recursive: true }); + fs.writeFileSync(path.join(installDir, "package.json"), JSON.stringify({ name: "billion-context", version: p.copyVersion })); + if (p.buildCommit !== undefined) { + fs.mkdirSync(path.join(installDir, "dist"), { recursive: true }); + fs.writeFileSync(path.join(installDir, "dist", "build-info.json"), JSON.stringify({ commit: p.buildCommit, version: p.copyVersion })); + } + } + if (p.lock !== undefined) { + if (p.packageLock === true) { + fs.writeFileSync( + path.join(dir, "package-lock.json"), + JSON.stringify({ + packages: { + "": { dependencies: { "billion-context": p.lock.specifier } }, + "node_modules/billion-context": { version: p.lock.version }, + }, + }), + ); + } else { + fs.writeFileSync( + path.join(dir, "pnpm-lock.yaml"), + ["lockfileVersion: '9.0'", "importers:", " .:", " dependencies:", " billion-context:", ` specifier: ${p.lock.specifier}`, ` version: ${p.lock.version}`, "packages:", ""].join("\n"), + ); + } + } + } + return { + base, + dshHome, + profiles, + setProfile() { + process.env.DSH_HOME = dshHome; + delete process.env.BILI_DSH_HOME; + }, + cleanup() { + delete process.env.DSH_HOME; + delete process.env.BILI_DSH_HOME; + rmrf(base); + }, + }; +} + +function kinds(dir: string, registryVersion?: string): string[] { + return dshProfileCopyFindings(dir, registryVersion).map((f) => f.kind); +} + +function makeLog(): { log: Logger; entries: string[] } { + const entries: string[] = []; + return { log: (level, msg) => { entries.push(`${level}: ${msg}`); }, entries }; +} + +async function withRegistry(version: string | undefined, fn: (fetches: { count: number }) => Promise): Promise { + const original = globalThis.fetch; + const fetches = { count: 0 }; + globalThis.fetch = (() => { + fetches.count += 1; + return version === undefined + ? Promise.resolve(new Response("nope", { status: 500 })) + : Promise.resolve(new Response(JSON.stringify({ version }))); + }) as unknown as typeof fetch; + try { + return await fn(fetches); + } finally { + globalThis.fetch = original; + } +} + +// — the healthy path ———————————————————————————————————————————————————— + +test("#3160 provenance: copy, manifest, and lockfile in agreement stay silent", () => { + const fx = makeFixture({ + profiles: { web: { manifestSpec: "^0.1.196", copyVersion: "0.1.196", buildCommit: "d64139f9", lock: { specifier: "^0.1.196", version: "0.1.196" } } }, + }); + try { + fx.setProfile("web"); + assert.deepEqual(kinds(fx.profiles.web, "0.1.197"), []); + } finally { + fx.cleanup(); + } +}); + +// — the reported incident (#3160) ———————————————————————————————————————— + +test("#3160 provenance: 1.2.9 copy against a registry whose latest is 0.1.197 is flagged", () => { + // the reporter's exact state: hand-placed copy at a version the registry + // never published, no lockfile to explain it (manifest still coherent). + const fx = makeFixture({ profiles: { web: { manifestSpec: "^1.2.9", copyVersion: "1.2.9" } } }); + try { + fx.setProfile("web"); + const found = kinds(fx.profiles.web, "0.1.197"); + assert.deepEqual(found, ["spec-above-registry"]); + const finding = dshProfileCopyFindings(fx.profiles.web, "0.1.197")[0]; + assert.ok(finding.detail.includes("1.2.9"), "detail names the fabricated spec"); + assert.ok(finding.detail.includes("dsh plugin --profile web add"), "detail carries the host-channel remediation"); + } finally { + fx.cleanup(); + } +}); + +test("#3160 provenance: out-of-band copy against an intact lockfile is flagged", () => { + // the wedge with a lockfile present: the copy and the manifest were both + // lifted, but a stale lock still records the real resolution. + const fx = makeFixture({ + profiles: { web: { manifestSpec: "^1.2.9", copyVersion: "1.2.9", lock: { specifier: "^0.1.196", version: "0.1.196" } } }, + }); + try { + fx.setProfile("web"); + const found = kinds(fx.profiles.web, "0.1.197"); + assert.ok(found.includes("copy-vs-lock")); + assert.ok(found.includes("manifest-vs-lock")); + assert.ok(found.includes("spec-above-registry")); + } finally { + fx.cleanup(); + } +}); + +// — manifest/lock coherence ————————————————————————————————————————————— + +test("#3160 provenance: lockfile disagreeing with the manifest spec is flagged", () => { + // same copy on disk and in the lock, but the manifest spec says otherwise + // — the host's next reconcile would roll the copy backwards. + const fx = makeFixture({ + profiles: { web: { manifestSpec: "^0.1.196", copyVersion: "0.1.197", lock: { specifier: "^0.1.196", version: "0.1.197" } } }, + }); + try { + fx.setProfile("web"); + assert.deepEqual(kinds(fx.profiles.web, "0.1.197"), []); + } finally { + fx.cleanup(); + } +}); + +test("#3160 provenance: package-lock.json is read like pnpm-lock.yaml", () => { + const fx = makeFixture({ + profiles: { web: { manifestSpec: "^0.1.196", copyVersion: "1.2.9", packageLock: true, lock: { specifier: "^0.1.196", version: "0.1.196" } } }, + }); + try { + fx.setProfile("web"); + assert.ok(kinds(fx.profiles.web, "0.1.197").includes("copy-vs-lock")); + } finally { + fx.cleanup(); + } +}); + +// — dev lanes and absent state —————————————————————————————————————————— + +test("#3160 provenance: link:/file: dev pins are never flagged", () => { + const fx = makeFixture({ + profiles: { + dev: { manifestSpec: `link:${path.join(root, "dev-bc")}`, copyVersion: "0.0.0-local" }, + dev2: { manifestSpec: `file:${path.join(root, "dev-bc")}` }, + }, + }); + try { + fx.setProfile("dev"); + assert.deepEqual(kinds(fx.profiles.dev, "0.1.197"), []); + assert.deepEqual(kinds(fx.profiles.dev2, "0.1.197"), []); + } finally { + fx.cleanup(); + } +}); + +test("#3160 provenance: profiles without the dependency, the copy, or any lockfile stay silent", () => { + const fx = makeFixture({ + profiles: { + nodep: { copyVersion: "0.1.196" }, + nocopy: { manifestSpec: "^0.1.197", lock: { specifier: "^0.1.197", version: "0.1.197" } }, + nolock: { manifestSpec: "^0.1.196", copyVersion: "0.1.196" }, + }, + }); + try { + fx.setProfile("nodep"); + assert.deepEqual(kinds(fx.profiles.nodep, "0.1.197"), []); + assert.deepEqual(kinds(fx.profiles.nocopy, "0.1.197"), []); + assert.deepEqual(kinds(fx.profiles.nolock, "0.1.197"), []); + } finally { + fx.cleanup(); + } +}); + +test("#3160 provenance: no lockfile and a copy the manifest cannot explain is flagged", () => { + // the manifest is coherent (^0.1.196 admits the registry's 0.1.197); only + // the copy beside it is out-of-band, so the manifest rung catches it. + const fx = makeFixture({ profiles: { web: { manifestSpec: "^0.1.196", copyVersion: "1.2.9" } } }); + try { + fx.setProfile("web"); + assert.deepEqual(kinds(fx.profiles.web, "0.1.197"), ["copy-vs-manifest"]); + } finally { + fx.cleanup(); + } +}); + +// — build divergence ———————————————————————————————————————————————— + +test("#3160 provenance: same version, different build commit across profiles is flagged", () => { + const fx = makeFixture({ + profiles: { + a: { manifestSpec: "^0.1.196", copyVersion: "0.1.196", buildCommit: "aaaaaaa", lock: { specifier: "^0.1.196", version: "0.1.196" } }, + b: { manifestSpec: "^0.1.196", copyVersion: "0.1.196", buildCommit: "bbbbbbb", lock: { specifier: "^0.1.196", version: "0.1.196" } }, + }, + }); + try { + fx.setProfile("a"); + const first = dshProfileCopyFindings(fx.profiles.a, "0.1.197"); + assert.deepEqual(first, [], "first profile establishes the baseline"); + const second = dshProfileCopyFindings(fx.profiles.b, "0.1.197", { buildBaseline: { version: "0.1.196", commit: "aaaaaaa", profile: "a" } }); + assert.equal(second.length, 1); + assert.equal(second[0].kind, "build-divergence"); + assert.ok(second[0].detail.includes("bbbbbbb") && second[0].detail.includes("aaaaaaa")); + } finally { + fx.cleanup(); + } +}); + +// — the startup entry point ———————————————————————————————————————————— + +test("#3160 audit: wedged profile logs a warn with remediation; healthy stays silent", async () => { + const fx = makeFixture({ profiles: { web: { manifestSpec: "^1.2.9", copyVersion: "1.2.9" } } }); + const { log, entries } = makeLog(); + try { + fx.setProfile("web"); + await withRegistry("0.1.197", async () => { + await auditDshProfileCopyProvenance({ log, fetchRegistryVersion: async () => "0.1.197" }); + }); + assert.equal(entries.length, 1); + assert.ok(entries[0].startsWith("warn:"), "severity is warn"); + assert.ok(entries[0].includes("#3160")); + assert.ok(entries[0].includes("dsh plugin --profile web add"), "remediation names the host channel"); + } finally { + fx.cleanup(); + } +}); + +test("#3160 audit: registry unreachable still flags the copy-vs-lock divergence", async () => { + // the spec-above-registry rung needs the registry, but the lockfile rungs + // must not depend on it — an offline install still gets warned. + const fx = makeFixture({ + profiles: { web: { manifestSpec: "^1.2.9", copyVersion: "1.2.9", lock: { specifier: "^0.1.196", version: "0.1.196" } } }, + }); + const { log, entries } = makeLog(); + try { + fx.setProfile("web"); + await withRegistry(undefined, async () => { + await auditDshProfileCopyProvenance({ log, fetchRegistryVersion: async () => { throw new Error("offline"); } }); + }); + const logged = entries.join("\n"); + assert.ok(logged.includes("does not match the lockfile resolution"), "copy-vs-lock logged without the registry"); + assert.ok(!logged.includes("NEWER than the registry"), "no registry verdict without the registry"); + } finally { + fx.cleanup(); + } +}); + +test("#3160 audit: a broken detector never throws into the caller", async () => { + const fx = makeFixture({ profiles: { web: { manifestSpec: "^0.1.196", copyVersion: "0.1.196" } } }); + const { log } = makeLog(); + try { + fx.setProfile("web"); + await auditDshProfileCopyProvenance({ log, fetchRegistryVersion: async () => { throw new Error("boom"); } }); + // no DSH_HOME-independent state to assert beyond not throwing + assert.ok(true); + } finally { + fx.cleanup(); + } +});