Skip to content

Commit d0cac98

Browse files
saravmajesticclaude
andcommitted
fix: address review findings — non-global layouts, yarn on Windows, blocked-upgrade telemetry (#1305)
Automated review of #1306 raised six findings. Each was verified against the code before acting; five were valid and are fixed here, one is declined with a reason. - **npx caches, download caches and project-local installs were attributed to a package manager.** `PKG_SEGMENT_RE` matches any `node_modules/@altimateai/altimate-code*` segment, not only global roots, so `npx`, a devDependency install, or a bun/npm cache resolved to `npm`/`bun`. `upgrade()` reads that as "run `install -g`", and for patch releases it runs automatically at startup — creating a global install the user never had. The deleted probe loop returned "unknown" for these, so this was a regression. Cache layouts are now excluded during detection, and `preflight()` additionally confirms the running binary actually lives under the manager's global root, failing open when that root cannot be determined. - **yarn classic on Windows was misclassified as npm.** Its global directory is `%LOCALAPPDATA%\Yarn\config\global`, which neither the `.yarn` nor the `yarn/global` spelling matched — so an upgrade would have run `npm install -g` over a yarn install, producing exactly the orphaned second binary this change exists to prevent. - **Preflight-blocked upgrades emitted no telemetry and no log entry**, so the flagship permission case read as "no attempt" on dashboards — strictly worse than the previous behaviour, which at least ran the command and recorded an error. Blocked attempts are now logged and tracked with their classification. - **The curl preflight checked the wrong directory.** It used the running binary's own directory, but the install script always writes to `$HOME/.altimate/bin`, so a legacy `~/.opencode/bin` install could pass preflight while a different directory was upgraded. - **The Chocolatey elevation message contradicted the classified cause** — it was returned unconditionally, so a network failure was reported as an elevation problem alongside a conflicting "Likely cause" hint. It is now used only for permission failures. - **The npm remediation told Windows users to run `sudo`**, which does not exist there; those users are now pointed at an elevated shell. - The error message now names `opencode.log` rather than the log directory, which also holds trace jsonl and heap dumps. Declined: switching `fs.accessSync` to `FileSystem.FileSystem`. It is the documented preference, but threading that service through requires widening the layer's dependency type and every downstream composition (`defaultLayer`, `node`) — well outside the scope of this fix, and raw `fs` already has precedent in sibling modules (cli/welcome.ts). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
1 parent b9a769c commit d0cac98

2 files changed

Lines changed: 110 additions & 13 deletions

File tree

‎packages/opencode/src/installation/index.ts‎

Lines changed: 78 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { ChildProcess } from "effect/unstable/process"
99
import { AppProcess } from "@opencode-ai/core/process"
1010
import path from "path"
1111
import fs from "fs"
12+
import os from "os"
1213
import { EventV2 } from "@opencode-ai/core/event"
1314
import { makeRuntime } from "@opencode-ai/core/effect/runtime"
1415
import semver from "semver"
@@ -21,7 +22,9 @@ import { NpmConfig } from "@opencode-ai/core/npm-config"
2122
// unit test that imports resolveInstall(). Same lazy shape as getTelemetry() below.
2223
async function getLogDir(): Promise<string> {
2324
const { Global } = await import("@opencode-ai/core/global")
24-
return Global.Path.log
25+
// The file logger writes to opencode.log inside this directory; the directory itself also
26+
// holds trace jsonl and heap dumps, so naming the file saves the user a hunt.
27+
return path.join(Global.Path.log, "opencode.log")
2528
}
2629
// altimate_change end
2730

@@ -75,7 +78,11 @@ const PKG_SEGMENT_RE =
7578
// the wrong manager.
7679
const PNPM_SEGMENT_RE = /[\\/](?:\.pnpm|pnpm)[\\/]/i
7780
const BUN_SEGMENT_RE = /[\\/]\.bun[\\/]/i
78-
const YARN_SEGMENT_RE = /[\\/](?:\.yarn|yarn[\\/]global)[\\/]/i
81+
// yarn classic's global dir is `~/.yarn` / `.../yarn/global` on unix but
82+
// `%LOCALAPPDATA%\Yarn\config\global` on Windows — match any `yarn` path segment so the
83+
// Windows spelling is not silently attributed to npm (which would `npm install -g` over a
84+
// yarn install and create the orphaned second binary this change exists to prevent).
85+
const YARN_SEGMENT_RE = /[\\/]\.?yarn[\\/]/i
7986
// Homebrew bin entries are symlinks into Cellar, so realpath lands there. Match the
8087
// Cellar segment rather than the prefix: /usr/local is also a common npm prefix.
8188
const BREW_SEGMENT_RE = /[\\/]Cellar[\\/]altimate-code[\\/]/i
@@ -91,6 +98,15 @@ const CHOCO_SEGMENT_RE = /[\\/]chocolatey[\\/]/i
9198
// when the prefix is `~/.local`.
9299
const STANDALONE_SEGMENT_RE = /[\\/]\.(?:altimate|opencode)[\\/]bin[\\/]|[\\/]\.local[\\/]bin[\\/]/i
93100

101+
// An npx cache, a package-manager download cache, or a project-local node_modules all
102+
// contain a `node_modules/@altimateai/altimate-code*` segment but are NOT global installs.
103+
// Attributing them to a package manager would make `upgrade()` run `npm install -g` and
104+
// CREATE a global install the user never had — and for patch releases that happens
105+
// automatically at startup (see cli/upgrade.ts). The old probe loop returned "unknown"
106+
// for these, so they must keep degrading to notify-only.
107+
const PACKAGE_MANAGERS: Method[] = ["npm", "pnpm", "bun", "yarn"]
108+
const EPHEMERAL_SEGMENT_RE = /[\\/](?:_npx|_cacache)[\\/]|[\\/]install[\\/]cache[\\/]/i
109+
94110
export interface ResolvedInstall {
95111
readonly method: Method
96112
/** Directory the upgrade would mutate. Only set where we can name it without a subprocess. */
@@ -110,7 +126,7 @@ export function resolveInstall(
110126
// Never auto-upgrade a pinned path.
111127
if (env["ALTIMATE_CODE_BIN_PATH"]) return { method: "unknown" }
112128

113-
if (PKG_SEGMENT_RE.test(execPath)) {
129+
if (PKG_SEGMENT_RE.test(execPath) && !EPHEMERAL_SEGMENT_RE.test(execPath)) {
114130
if (PNPM_SEGMENT_RE.test(execPath)) return { method: "pnpm" }
115131
if (BUN_SEGMENT_RE.test(execPath)) return { method: "bun" }
116132
if (YARN_SEGMENT_RE.test(execPath)) return { method: "yarn" }
@@ -298,7 +314,13 @@ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient | AppProce
298314
})
299315

300316
const upgradeFailure = (method: Method, result?: { code: number; stdout: string; stderr: string }) => {
301-
if (method === "choco") return "not running from an elevated command shell"
317+
// altimate_change start — #1305: only claim elevation when the failure actually looks
318+
// like a permission problem. Returning it unconditionally contradicted the classified
319+
// "Likely cause:" hint appended by the caller (e.g. a network failure reported as an
320+
// elevation problem).
321+
if (method === "choco" && (!result || classifyFailure(result.stderr, result.stdout).code === "permission"))
322+
return "not running from an elevated command shell"
323+
// altimate_change end
302324
// altimate_change start — do not echo package-manager/install-script stderr; it can contain tokens or env
303325
if (result) return `Upgrade failed for ${method} (exit code ${result.code}).`
304326
// altimate_change end
@@ -336,8 +358,11 @@ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient | AppProce
336358
return [dir, bin].filter(Boolean)
337359
}
338360
case "curl": {
339-
const resolved = resolveInstall()
340-
return resolved.root ? [resolved.root] : []
361+
// The install script always writes to $HOME/.altimate/bin regardless of where the
362+
// running binary sits (`install`, INSTALL_DIR), so a legacy ~/.opencode/bin install
363+
// must have the ACTUAL target checked — not its own directory, which the upgrade
364+
// never touches.
365+
return [path.join(os.homedir(), ".altimate", "bin")]
341366
}
342367
// brew / scoop / choco own their own elevation and policy — do not second-guess them.
343368
default:
@@ -349,11 +374,14 @@ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient | AppProce
349374
const pkg = `@altimateai/altimate-code@${target}`
350375
switch (m) {
351376
case "npm":
352-
return (
353-
`Cannot write to the npm global prefix (${dir}). ` +
354-
`Run \`sudo npm install -g ${pkg}\`, or switch to a user-owned prefix ` +
355-
`with \`npm config set prefix ~/.npm-global\`.`
356-
)
377+
// Windows has no sudo — tell those users to use an elevated shell instead.
378+
return process.platform === "win32"
379+
? `Cannot write to the npm global prefix (${dir}). ` +
380+
`Re-run \`npm install -g ${pkg}\` from an elevated (Administrator) shell, ` +
381+
`or switch to a user-owned prefix with \`npm config set prefix\`.`
382+
: `Cannot write to the npm global prefix (${dir}). ` +
383+
`Run \`sudo npm install -g ${pkg}\`, or switch to a user-owned prefix ` +
384+
`with \`npm config set prefix ~/.npm-global\`.`
357385
case "pnpm":
358386
return (
359387
`Cannot write to the pnpm global directory (${dir}). ` +
@@ -376,19 +404,39 @@ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient | AppProce
376404
}
377405
}
378406

407+
/** A refusal carrying the classification code so the blocked attempt is still recorded
408+
* as that KIND of failure rather than vanishing from telemetry as "no attempt". */
409+
const preflightBlock = (code: string, message: string) => ({ code, message })
410+
379411
/** Returns an error message when the upgrade cannot possibly succeed, else undefined.
380412
*
381413
* Checking first means we never shell out to a command that is going to fail on
382414
* permissions — which is what produced the old, undiagnosable
383415
* "Upgrade failed for npm (exit code 243)." */
384416
const preflight = Effect.fnUntraced(function* (m: Method, target: string) {
385417
const dirs = yield* globalDirs(m)
418+
// A project-local node_modules (CLI as a devDependency) matches the package segment
419+
// but is not the global install, and `npm install -g` would create one the user never
420+
// had. Cache layouts are excluded in resolveInstall(); this catches the rest by
421+
// confirming the running binary actually lives under the manager's global root.
422+
// Fails OPEN when the root cannot be determined — never block on a missing answer.
423+
if (PACKAGE_MANAGERS.includes(m) && dirs.length > 0) {
424+
const exec = realExecPath().toLowerCase()
425+
const roots = dirs.map((d) => d.toLowerCase()).filter(Boolean)
426+
if (roots.length > 0 && !roots.some((r) => exec.startsWith(r))) {
427+
return preflightBlock("not-global",
428+
`The running binary is not the ${m} global install (${realExecPath()}). ` +
429+
`Upgrade it where it was installed from, or install globally with ` +
430+
`\`${m} install -g @altimateai/altimate-code@${target}\`.`,
431+
)
432+
}
433+
}
386434
for (const dir of dirs) {
387435
if (!dir) continue
388436
// A directory that does not exist yet is not a permission problem: the package
389437
// manager creates it. Only an EXISTING, unwritable directory is a hard stop.
390438
if (!fs.existsSync(dir)) continue
391-
if (!isWritable(dir)) return remediation(m, dir, target)
439+
if (!isWritable(dir)) return preflightBlock("permission", remediation(m, dir, target))
392440
}
393441
return undefined
394442
})
@@ -556,7 +604,24 @@ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient | AppProce
556604
upgrade: Effect.fn("Installation.upgrade")(function* (m: Method, target: string) {
557605
// altimate_change start — refuse before shelling out when the target is unwritable (#1305)
558606
const blocked = yield* preflight(m, target)
559-
if (blocked) return yield* new UpgradeFailedError({ stderr: blocked })
607+
if (blocked) {
608+
// Record it the same way a real failure is recorded. Returning early without this
609+
// made the flagship permission case read as "no attempt" on dashboards — strictly
610+
// worse than the old behaviour, which at least ran the command and logged an error.
611+
yield* Effect.logWarning("upgrade blocked", { method: m, target, reason: blocked.code })
612+
const T0 = yield* Effect.promise(() => getTelemetry())
613+
T0.track({
614+
type: "upgrade_attempted",
615+
timestamp: Date.now(),
616+
session_id: T0.getContext().sessionId || "cli",
617+
from_version: InstallationVersion,
618+
to_version: target,
619+
method: (["npm", "bun", "brew"].includes(m) ? m : "other") as "npm" | "bun" | "brew" | "other",
620+
status: "error",
621+
error: `${blocked.code}: preflight`,
622+
})
623+
return yield* new UpgradeFailedError({ stderr: blocked.message })
624+
}
560625
// altimate_change end
561626
let upgradeResult: { code: number; stdout: string; stderr: string } | undefined
562627
switch (m) {

‎packages/opencode/test/installation/resolve-install.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,38 @@ describe("resolveInstall", () => {
7777
expect(resolveInstall("/home/u/.altimate/bin/altimate", {}).root).toBe("/home/u/.altimate/bin")
7878
})
7979

80+
// Review findings on #1306 — layouts that contain a package segment but are NOT a
81+
// global install. Attributing them to a manager would make upgrade() run `install -g`
82+
// and CREATE a global install the user never had (automatically, for patch releases).
83+
test("an npx cache invocation is not attributed to npm", () => {
84+
expect(
85+
resolveInstall(
86+
"/home/u/.npm/_npx/a1b2c3/node_modules/@altimateai/altimate-code-linux-x64/bin/altimate-code",
87+
{},
88+
).method,
89+
).toBe("unknown")
90+
})
91+
92+
test("a package-manager download cache is not attributed to a manager", () => {
93+
expect(
94+
resolveInstall(
95+
"/home/u/.bun/install/cache/@altimateai/altimate-code-linux-x64/bin/altimate-code",
96+
{},
97+
).method,
98+
).toBe("unknown")
99+
})
100+
101+
test("yarn classic on Windows is yarn, not npm", () => {
102+
// %LOCALAPPDATA%\Yarn\config\global — the unix `.yarn` / `yarn/global` spellings do
103+
// not cover it, and falling through to npm would `npm install -g` over a yarn install.
104+
expect(
105+
resolveInstall(
106+
"C:\\Users\\u\\AppData\\Local\\Yarn\\config\\global\\node_modules\\@altimateai\\altimate-code-win32-x64\\bin\\altimate-code.exe",
107+
{},
108+
).method,
109+
).toBe("yarn")
110+
})
111+
80112
test("a standalone binary in ~/.local/bin is still a curl install (#820 back-compat)", () => {
81113
// Kept deliberately: it is a distro-resolved standalone location and is what
82114
// test/sanity/Dockerfile installs to. Safe because the node_modules match runs first —

0 commit comments

Comments
 (0)