CodeNomad/scripts/test-opencode-legacy-replacement-native.mjs
Pascal André b6bea60dd6
Some checks are pending
Publish help / build (push) Waiting to run
Publish help / deploy (push) Blocked by required conditions
build(runtime): separate bundled npm pinning from Node maintenance (#1330)
## Mechanism first, no npm release change

Introduce `.npm-version` at the npm release already supplied by the
pinned Node archive. Both desktop hosts package that exact registry
release. This PR does not adopt npm 12: after it merges, maintenance
will be dispatched to test creation of an independent candidate PR.

## Implementation

- Download the exact npm registry tarball and verify its canonical
metadata, package/version, sha512 integrity, bundled dependencies and
engines against each host's Node. Reuse the platform tar extractor; no
handwritten archive parser. The registry supplies both metadata and
archive, so this checks registry content consistency, not an independent
publisher signature.
- Preserve Tauri's Node binary and existing per-platform npm layout, and
Electron's npm-only resources. Smoke and verification check the npm pin.
- Scope lifecycle script permission to the exact `@opencode/cli` release
for direct installs and native upgrade. No blanket script permission or
user npmrc edits.
- Daily maintenance audits the pinned npm and candidate and proposes
`.npm-version` changes only when declared engines accept both runtimes.
A major is explicitly unqualified and needs maintainer review; engines
acceptance is not behavioral validation. No automatic merge or release.
- Partial proposals remain visible errors naming the existing branch,
with reconciliation instructions; no forced overwrite/deletion. A
candidate-audit failure blocks only the npm proposal; pinned audit and
metadata failures remain failures.
- Documentation references pins rather than copied versions. GitHub
token-created proposal validation requires approving the workflow runs,
or closing/reopening with a maintainer account; no new credentials
added.

## Validation

- Unit/packaging/maintenance/Tauri script suites: 47 pass. Server update
tests: 70 pass, 1 platform skip. Typecheck passes.
- Windows Electron45 package and Tauri release binary build/smoke pass.
- Real install, upgrade and legacy-replacement fixtures pass on both
Windows layouts with current npm11 and a temporary, uncommitted npm12
candidate.
- Ubuntu: both layouts prepare/verify; first-install fixture passes with
both npm releases.
- The candidate removes the two high audit entries, but their
applicability to CodeNomad's prebuilt OpenCode installation is low; 32
moderate entries remain. The proposal requires release-note review and
native-fixture qualification rather than equating a lower audit count
with safety.

macOS candidate behavior still needs CI qualification. No pin to npm12,
application release, registry publishing or daemon restart is part of
this PR.
2026-11-07 06:44:09 +01:00

73 lines
5.3 KiB
JavaScript

// Run with: node --import tsx scripts/test-opencode-legacy-replacement-native.mjs
// Real npm and published packages in an isolated home/prefix/cache. Never touches
// the user's npm prefix, PATH, OpenCode installation or shared daemon.
import assert from "node:assert/strict"
import { execFile } from "node:child_process"
import { existsSync } from "node:fs"
import { mkdtemp, mkdir, writeFile } from "node:fs/promises"
import { promisify } from "node:util"
import os from "node:os"
import path from "node:path"
import { installSharedOpenCode, npmCommandDirectory, npmExecutable, resolveDefaultInstallation, sharedInstallationPlan } from "../packages/server/src/opencode-update/shared-installation.ts"
import { legacyNativeImages, legacyNpmPackageRoot } from "../packages/server/src/opencode-update/legacy-installation.ts"
import { executeNpm } from "../packages/server/src/opencode-update/npm-runtime.ts"
import { fixtureRuntime } from "./opencode-fixture-runtime.mjs"
import { RECOMMENDED_OPENCODE_VERSION } from "../packages/server/src/opencode/runtime-support.ts"
const LEGACY_VERSION = process.env.CODENOMAD_FIXTURE_LEGACY_VERSION || "1.18.10"
const root = await mkdtemp(path.join(os.tmpdir(), "codenomad-legacy-replacement-"))
const selected = await fixtureRuntime(root)
const { node, npm } = selected
const prefix = path.join(root, "npm prefix")
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) =>
!/^(OPENCODE_|CODENOMAD_|CLI_|XDG_|npm_|PATH$|NODE_|ELECTRON_|WEBVIEW2_)/i.test(key)))
Object.assign(env, {
HOME: root, USERPROFILE: root, APPDATA: path.join(root, "AppData"), LOCALAPPDATA: path.join(root, "LocalAppData"),
XDG_CONFIG_HOME: path.join(root, "config"), XDG_DATA_HOME: path.join(root, "data"), XDG_STATE_HOME: path.join(root, "state"),
XDG_CACHE_HOME: path.join(root, "cache"), npm_config_prefix: prefix, npm_config_cache: path.join(root, "npm-cache"),
npm_config_userconfig: path.join(root, "npmrc"),
// The user's PC: the npm prefix holding OpenCode 1.x is on PATH.
...selected.env, PATH: [npmCommandDirectory(prefix), selected.path].join(path.delimiter),
})
for (const key of ["APPDATA", "LOCALAPPDATA", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_CACHE_HOME"]) await mkdir(env[key], { recursive: true })
const run = (args) => executeNpm(node, [npm, ...args], env, process.platform, prefix, async (file, args, env, options) => {
await promisify(execFile)(file, args, { ...options, env, timeout: 300_000, maxBuffer: 4 * 1024 * 1024, windowsHide: true })
})
const options = { home: root, env, node, npm, registerPath: async () => {} }
const result = { root, legacyVersion: LEGACY_VERSION, target: RECOMMENDED_OPENCODE_VERSION }
try {
// A user's 1.x installation ran its postinstall: allow exactly it (npm 12+ blocks it).
await run(["install", "--global", "--prefix", prefix, "--no-audit", "--no-fund", "--registry", "https://registry.npmjs.org",
`--allow-scripts=opencode-ai@${LEGACY_VERSION}`, `opencode-ai@${LEGACY_VERSION}`])
const plan = sharedInstallationPlan(options)
assert.equal(plan.prefix, prefix)
assert.equal(plan.legacy?.version, LEGACY_VERSION, "the published 1.x shim is recognized from its manifest and target")
result.legacyCommand = plan.legacy.command
// Fact check: npm refuses to link @opencode/cli's `opencode` bin over the 1.x shim.
const collision = await run(["install", "--global", "--prefix", prefix, "--no-audit", "--no-fund", "--registry", "https://registry.npmjs.org",
`@opencode/cli@${RECOMMENDED_OPENCODE_VERSION}`]).then(() => undefined, error => `${error.stderr ?? error.message}`)
assert.ok(collision && /EEXIST/.test(collision), "plain npm installation collides with the 1.x shim")
result.collision = collision.split(/\r?\n/).find(line => /EEXIST/.test(line))
assert.equal(sharedInstallationPlan(options).legacy?.version, LEGACY_VERSION, "the failed plain install left 1.x in place")
await assert.rejects(installSharedOpenCode(RECOMMENDED_OPENCODE_VERSION, options), /explicit confirmation/)
assert.ok(existsSync(legacyNpmPackageRoot(prefix, process.platform)))
result.nativeImages = legacyNativeImages(legacyNpmPackageRoot(prefix, process.platform)).map(image => path.relative(prefix, image))
assert.ok(result.nativeImages.some(image => /\.exe$|[\\/]\.opencode$/.test(image)), "the package's native executable is preflighted")
const consent = { path: plan.legacy.command, version: LEGACY_VERSION }
await assert.rejects(installSharedOpenCode(RECOMMENDED_OPENCODE_VERSION, { ...options, replaceLegacy: { ...consent, version: "1.0.0" } }), /explicit confirmation/)
assert.equal(await installSharedOpenCode(RECOMMENDED_OPENCODE_VERSION, { ...options, replaceLegacy: consent }), npmExecutable(prefix))
assert.equal(existsSync(legacyNpmPackageRoot(prefix, process.platform)), false)
assert.deepEqual(sharedInstallationPlan(options), { prefix })
const resolved = resolveDefaultInstallation(options)
assert.equal(resolved.source, "path")
const version = (await promisify(execFile)(npmExecutable(prefix), ["--version"], { cwd: root, env, timeout: 60_000, windowsHide: true })).stdout.trim()
assert.equal(version.replace(/^opencode2? v?/, ""), RECOMMENDED_OPENCODE_VERSION)
result.resolved = resolved
result.success = true
} finally {
await writeFile(path.join(root, "result.json"), JSON.stringify(result, null, 2))
console.log(JSON.stringify(result, null, 2))
}