Skip to content

Commit b9a769c

Browse files
saravmajesticclaude
andcommitted
fix: correct .local/bin regression and revert collateral reformat (#1305)
Self-review and CI turned up three problems with the previous commit. 1. The `.local/bin` claim was wrong, and removing the branch was a regression. The commit message and PR said `.local/bin` misclassified npm installs made with `npm config set prefix ~/.local`. It does not. With that prefix, packages land in `~/.local/lib/node_modules/...` and only the shim sits in `~/.local/bin`; since execPath is the spawned platform binary, it never contains `.local/bin` for a package-manager install, so the branch could not misfire that way. Removing it deleted correct back-compat from #820 (distro-resolved standalone installs), which test/sanity/Dockerfile also relies on, and broke four tests that said so explicitly. Restored — but AFTER the node_modules match, which is what makes it safe and is the real improvement over the original ordering. Both layouts now resolve correctly, with a test asserting exactly that. 2. Running prettier over the whole file reformatted code this change never touched (`upgradeCurl`, `upgradePowershell`, `defaultLayer`), because the committed file predates the repo's printWidth of 120. That broke two source-shape tests and tripped Marker Guard, which reads reformatted upstream lines as unmarked custom code. Formatting is not CI-enforced here, so it bought nothing. Rebuilt the file from the pristine version with only the intended edits re-applied. 3. `import { Global }` pulled in a module-load side effect: core/global.ts runs a top-level `await Promise.all([...mkdir...])`, creating seven directories merely by loading the module, and dragged that into every unit test importing resolveInstall(). Replaced with a lazy import matching the existing getTelemetry() pattern. Also converted the #820 detection tests from source-text assertions to behavioural ones now that resolveInstall() is pure, and documented that `access(W_OK)` reflects the read-only attribute rather than the ACL on Windows, so the preflight degrades to a no-op there instead of falsely blocking. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
1 parent e98ba6d commit b9a769c

4 files changed

Lines changed: 156 additions & 88 deletions

File tree

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

Lines changed: 112 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,22 @@ 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 { Global } from "@opencode-ai/core/global"
1312
import { EventV2 } from "@opencode-ai/core/event"
1413
import { makeRuntime } from "@opencode-ai/core/effect/runtime"
1514
import semver from "semver"
1615
import { InstallationChannel, InstallationVersion } from "@opencode-ai/core/installation/version"
1716
import { NpmConfig } from "@opencode-ai/core/npm-config"
1817

18+
// altimate_change start — lazy log-dir lookup (#1305). @opencode-ai/core/global runs a
19+
// top-level `await Promise.all([...mkdir...])`, so a static import would create seven
20+
// directories merely by loading this module — and would drag that side effect into every
21+
// unit test that imports resolveInstall(). Same lazy shape as getTelemetry() below.
22+
async function getLogDir(): Promise<string> {
23+
const { Global } = await import("@opencode-ai/core/global")
24+
return Global.Path.log
25+
}
26+
// altimate_change end
27+
1928
// altimate_change start — telemetry (lazy import to avoid circular dep with Telemetry → Installation)
2029
let _telemetryCache: (typeof import("../telemetry"))["Telemetry"] | undefined
2130
async function getTelemetry() {
@@ -40,13 +49,15 @@ const UPGRADE_FETCH_TIMEOUT_MS = 15_000
4049
// altimate_change end
4150

4251
// altimate_change start — deterministic install resolution (#1305)
43-
// Detection used to guess two ways, and both were unsound: a substring test on
44-
// process.execPath (`.local/bin` is a generic user bin dir, so an npm install with
45-
// `npm config set prefix ~/.local` was classified "curl" and upgraded via
46-
// `curl | bash`, orphaning the npm copy), and a probe loop asking each package
47-
// manager "do you have this package?" — which answers a different question than
48-
// "did THIS running binary come from you", so it picked arbitrarily whenever more
49-
// than one install existed.
52+
// Detection used to fall back to a probe loop that asked each package manager "do you
53+
// have this package?" (`npm list -g`, `brew list`, ...) and returned the first that said
54+
// yes. That answers a different question than "did THIS running binary come from you",
55+
// so once a user had more than one install — e.g. a standalone binary plus an npm copy,
56+
// which is common — the answer was effectively arbitrary and upgrades were routed at an
57+
// install the user was not running.
58+
//
59+
// The directory checks that ran before the probe loop were sound and are preserved
60+
// below; only the probe loop is replaced.
5061
//
5162
// The running binary's own path is the ground truth. The npm `bin/altimate` shim is
5263
// a Node script that spawnSync()s the PLATFORM package's binary, so inside the CLI
@@ -70,10 +81,15 @@ const YARN_SEGMENT_RE = /[\\/](?:\.yarn|yarn[\\/]global)[\\/]/i
7081
const BREW_SEGMENT_RE = /[\\/]Cellar[\\/]altimate-code[\\/]/i
7182
const SCOOP_SEGMENT_RE = /[\\/]scoop[\\/]apps[\\/]/i
7283
const CHOCO_SEGMENT_RE = /[\\/]chocolatey[\\/]/i
73-
// The standalone (curl / install.ps1 / `install --binary`) layout. `.opencode/bin` is
74-
// the pre-v0.7.1 directory name, kept for users who have not re-installed since.
75-
// NOTE: `.local/bin` is deliberately NOT here — see the comment above.
76-
const STANDALONE_SEGMENT_RE = /[\\/]\.(?:altimate|opencode)[\\/]bin[\\/]/i
84+
// The standalone (curl / install.ps1 / `install --binary`) layouts. `.opencode/bin` is
85+
// the pre-v0.7.1 directory name and `.local/bin` a distro-resolved location; both are
86+
// kept for back-compat (#820) and `.local/bin` is also what test/sanity/Dockerfile uses.
87+
//
88+
// These are checked AFTER the node_modules match above, which is what makes them safe:
89+
// a package-manager install's execPath is the spawned platform binary deep under
90+
// `<prefix>/lib/node_modules/...`, so it can never collide with `<prefix>/bin` here even
91+
// when the prefix is `~/.local`.
92+
const STANDALONE_SEGMENT_RE = /[\\/]\.(?:altimate|opencode)[\\/]bin[\\/]|[\\/]\.local[\\/]bin[\\/]/i
7793

7894
export interface ResolvedInstall {
7995
readonly method: Method
@@ -117,6 +133,10 @@ function realExecPath(): string {
117133
}
118134
}
119135

136+
/** NOTE: on Windows, `access(W_OK)` reflects the read-only ATTRIBUTE rather than the ACL,
137+
* so a directory the user genuinely cannot write can still report writable. That makes the
138+
* preflight a no-op there rather than a false block — we fall through to the old behaviour
139+
* (shell out, fail, report) instead of wrongly refusing an upgrade that would have worked. */
120140
function isWritable(dir: string): boolean {
121141
try {
122142
fs.accessSync(dir, fs.constants.W_OK)
@@ -285,7 +305,7 @@ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient | AppProce
285305
return `Upgrade failed for ${method}.`
286306
}
287307

288-
// altimate_change start — writability preflight (#1305)
308+
// altimate_change start — writability preflight (#1305)
289309
/** Directories a global install of `m` would mutate. Empty = nothing cheap to check. */
290310
const globalDirs = Effect.fnUntraced(function* (m: Method) {
291311
switch (m) {
@@ -329,13 +349,26 @@ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient | AppProce
329349
const pkg = `@altimateai/altimate-code@${target}`
330350
switch (m) {
331351
case "npm":
332-
return `Cannot write to the npm global prefix (${dir}). Run \`sudo npm install -g ${pkg}\`, or switch to a user-owned prefix with \`npm config set prefix ~/.npm-global\`.`
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+
)
333357
case "pnpm":
334-
return `Cannot write to the pnpm global directory (${dir}). Run \`pnpm setup\` to use a user-owned location, or re-run the install with elevated permissions.`
358+
return (
359+
`Cannot write to the pnpm global directory (${dir}). ` +
360+
`Run \`pnpm setup\` to use a user-owned location, or re-run the install with elevated permissions.`
361+
)
335362
case "bun":
336-
return `Cannot write to the bun global bin directory (${dir}). Set BUN_INSTALL to a user-owned location, or re-run the install with elevated permissions.`
363+
return (
364+
`Cannot write to the bun global bin directory (${dir}). ` +
365+
`Set BUN_INSTALL to a user-owned location, or re-run the install with elevated permissions.`
366+
)
337367
case "yarn":
338-
return `Cannot write to the yarn global directory (${dir}). Set a user-owned prefix with \`yarn config set prefix ~/.yarn\`, or re-run with elevated permissions.`
368+
return (
369+
`Cannot write to the yarn global directory (${dir}). ` +
370+
`Set a user-owned prefix with \`yarn config set prefix ~/.yarn\`, or re-run with elevated permissions.`
371+
)
339372
case "curl":
340373
return `Cannot write to the install directory (${dir}). Fix its permissions, or re-run the installer.`
341374
default:
@@ -367,41 +400,45 @@ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient | AppProce
367400
return "sh"
368401
})
369402

370-
const upgradeCurl = Effect.fnUntraced(function* (target: string) {
371-
// altimate_change start — friendly fetch error + manual-recovery hint, branded install URL, bounded timeout
372-
const response = yield* httpOk.execute(HttpClientRequest.get(UPGRADE_INSTALL_URL)).pipe(
373-
Effect.timeout(UPGRADE_FETCH_TIMEOUT_MS),
374-
Effect.mapError(
375-
(err) =>
376-
new UpgradeFailedError({
377-
stderr:
378-
`Could not download install script from ${UPGRADE_INSTALL_URL}: ${errorMessage(err)}. ` +
379-
`Re-run the install manually: curl -fsSL ${UPGRADE_INSTALL_URL} | bash — ` +
380-
`or download a release binary directly from https://github.com/AltimateAI/altimate-code/releases/latest`,
381-
}),
382-
),
383-
)
384-
const body = yield* response.text.pipe(
385-
Effect.mapError(() => new UpgradeFailedError({ stderr: upgradeFailure("curl") })),
386-
)
387-
// altimate_change end
388-
const bodyBytes = new TextEncoder().encode(body)
389-
const shell = yield* upgradeScriptShell()
390-
const result = yield* appProcess
391-
.run(
392-
ChildProcess.make(shell, [], {
393-
stdin: Stream.make(bodyBytes),
394-
env: { VERSION: target },
395-
extendEnv: true,
396-
}),
403+
const upgradeCurl = Effect.fnUntraced(
404+
function* (target: string) {
405+
// altimate_change start — friendly fetch error + manual-recovery hint, branded install URL, bounded timeout
406+
const response = yield* httpOk
407+
.execute(HttpClientRequest.get(UPGRADE_INSTALL_URL))
408+
.pipe(
409+
Effect.timeout(UPGRADE_FETCH_TIMEOUT_MS),
410+
Effect.mapError(
411+
(err) =>
412+
new UpgradeFailedError({
413+
stderr:
414+
`Could not download install script from ${UPGRADE_INSTALL_URL}: ${errorMessage(err)}. ` +
415+
`Re-run the install manually: curl -fsSL ${UPGRADE_INSTALL_URL} | bash — ` +
416+
`or download a release binary directly from https://github.com/AltimateAI/altimate-code/releases/latest`,
417+
}),
418+
),
419+
)
420+
const body = yield* response.text.pipe(
421+
Effect.mapError(() => new UpgradeFailedError({ stderr: upgradeFailure("curl") })),
397422
)
398-
.pipe(Effect.mapError(() => new UpgradeFailedError({ stderr: upgradeFailure("curl") })))
399-
return {
400-
code: result.exitCode,
401-
stdout: result.stdout.toString("utf8"),
402-
stderr: result.stderr.toString("utf8"),
403-
}
404-
})
423+
// altimate_change end
424+
const bodyBytes = new TextEncoder().encode(body)
425+
const shell = yield* upgradeScriptShell()
426+
const result = yield* appProcess
427+
.run(
428+
ChildProcess.make(shell, [], {
429+
stdin: Stream.make(bodyBytes),
430+
env: { VERSION: target },
431+
extendEnv: true,
432+
}),
433+
)
434+
.pipe(Effect.mapError(() => new UpgradeFailedError({ stderr: upgradeFailure("curl") })))
435+
return {
436+
code: result.exitCode,
437+
stdout: result.stdout.toString("utf8"),
438+
stderr: result.stderr.toString("utf8"),
439+
}
440+
},
441+
)
405442

406443
// altimate_change start — Windows curl-install upgrade via PowerShell
407444
// The curl/standalone install on native Windows lives in %USERPROFILE%\.altimate\bin
@@ -411,18 +448,20 @@ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient | AppProce
411448
const upgradePowershell = Effect.fnUntraced(function* (target: string) {
412449
// Probe-only fetch to surface a friendly error before we hand the URL to
413450
// PowerShell (which would otherwise fail opaquely inside `irm | iex`).
414-
yield* httpOk.execute(HttpClientRequest.head(UPGRADE_INSTALL_PS_URL)).pipe(
415-
Effect.timeout(UPGRADE_FETCH_TIMEOUT_MS),
416-
Effect.mapError(
417-
(err) =>
418-
new UpgradeFailedError({
419-
stderr:
420-
`Could not download install script from ${UPGRADE_INSTALL_PS_URL}: ${errorMessage(err)}. ` +
421-
`Re-run the install manually: powershell -c "irm ${UPGRADE_INSTALL_PS_URL} | iex" — ` +
422-
`or download a release binary directly from https://github.com/AltimateAI/altimate-code/releases/latest`,
423-
}),
424-
),
425-
)
451+
yield* httpOk
452+
.execute(HttpClientRequest.head(UPGRADE_INSTALL_PS_URL))
453+
.pipe(
454+
Effect.timeout(UPGRADE_FETCH_TIMEOUT_MS),
455+
Effect.mapError(
456+
(err) =>
457+
new UpgradeFailedError({
458+
stderr:
459+
`Could not download install script from ${UPGRADE_INSTALL_PS_URL}: ${errorMessage(err)}. ` +
460+
`Re-run the install manually: powershell -c "irm ${UPGRADE_INSTALL_PS_URL} | iex" — ` +
461+
`or download a release binary directly from https://github.com/AltimateAI/altimate-code/releases/latest`,
462+
}),
463+
),
464+
)
426465
return yield* run(
427466
["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", `irm ${UPGRADE_INSTALL_PS_URL} | iex`],
428467
{ env: { VERSION: target } },
@@ -523,7 +562,8 @@ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient | AppProce
523562
switch (m) {
524563
case "curl":
525564
// altimate_change start — native Windows has no bash; use the PS installer
526-
upgradeResult = process.platform === "win32" ? yield* upgradePowershell(target) : yield* upgradeCurl(target)
565+
upgradeResult =
566+
process.platform === "win32" ? yield* upgradePowershell(target) : yield* upgradeCurl(target)
527567
// altimate_change end
528568
break
529569
case "npm":
@@ -575,7 +615,11 @@ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient | AppProce
575615
return yield* new UpgradeFailedError({ stderr: `Unknown installation method: ${m}` })
576616
}
577617
// altimate_change start — telemetry for upgrade result
578-
const telemetryMethod = (["npm", "bun", "brew"].includes(m) ? m : "other") as "npm" | "bun" | "brew" | "other"
618+
const telemetryMethod = (["npm", "bun", "brew"].includes(m) ? m : "other") as
619+
| "npm"
620+
| "bun"
621+
| "brew"
622+
| "other"
579623
if (!upgradeResult || upgradeResult.code !== 0) {
580624
// altimate_change start — make non-permission failures diagnosable (#1305).
581625
// The success path below logs the real stdout/stderr; this branch used to drop
@@ -594,11 +638,12 @@ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient | AppProce
594638
stdout: upgradeResult?.stdout,
595639
stderr: upgradeResult?.stderr,
596640
})
641+
const logDir = yield* Effect.promise(() => getLogDir())
597642
const base = upgradeFailure(m, upgradeResult)
598643
const stderr = [
599644
base,
600645
classified.hint ? `Likely cause: ${classified.hint}.` : undefined,
601-
`Details were written to ${Global.Path.log}.`,
646+
`Details were written to ${logDir}.`,
602647
]
603648
.filter(Boolean)
604649
.join(" ")
@@ -646,9 +691,7 @@ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient | AppProce
646691
)
647692

648693
// altimate_change start — Layer.suspend defers facade refs past circular module-init
649-
export const defaultLayer = Layer.suspend(() =>
650-
layer.pipe(Layer.provide(FetchHttpClient.layer), Layer.provide(AppProcess.defaultLayer)),
651-
)
694+
export const defaultLayer = Layer.suspend(() => layer.pipe(Layer.provide(FetchHttpClient.layer), Layer.provide(AppProcess.defaultLayer)))
652695
// altimate_change end
653696

654697
const { runPromise } = makeRuntime(Service, defaultLayer)

‎packages/opencode/test/install/upgrade-method.test.ts‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,13 @@ describe("installation method detection", () => {
4040
// altimate_change end
4141
})
4242

43-
test("`.local/bin` is not treated as a standalone install", () => {
44-
// altimate_change start — #1305: `.local/bin` is a generic user bin dir. Treating it
45-
// as curl misrouted `npm config set prefix ~/.local` installs into `curl | bash`,
46-
// which orphaned the npm copy and left two binaries fighting over PATH.
47-
expect(INSTALLATION_SRC).not.toMatch(/path\.join\("\.local", "bin"\)/)
43+
test("all three standalone directories are still recognised", () => {
44+
// altimate_change start — #1305: the three curl-install directories from #820
45+
// (.altimate/bin, .opencode/bin, .local/bin) must all keep resolving to "curl".
46+
// Behavioural coverage lives in test/installation/resolve-install.test.ts; this
47+
// asserts the source still carries all three so a refactor cannot quietly drop one.
48+
expect(INSTALLATION_SRC).toContain("altimate|opencode")
49+
expect(INSTALLATION_SRC).toContain(".local")
4850
// altimate_change end
4951
})
5052
})

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

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,9 @@ describe("resolveInstall", () => {
2121
// The npm bin/altimate shim spawns the PLATFORM package, so execPath is the nested
2222
// platform binary rather than the wrapper — detection must match the -<os>-<arch> suffix.
2323
["npm, default prefix", `${NPM_PREFIXED}/${PLATFORM}`, "npm"],
24-
// Regression: this is the layout the old `.local/bin` rule misread as "curl", which
25-
// made `altimate upgrade` run `curl | bash` and orphan the npm install.
24+
// The prefix here is ~/.local, so packages land in ~/.local/lib/node_modules — NOT
25+
// ~/.local/bin, which holds only the shim. That is why keeping the `.local/bin`
26+
// standalone branch is safe: the two can never collide on execPath.
2627
[
2728
"npm, prefix set to ~/.local",
2829
"/home/u/.local/lib/node_modules/@altimateai/altimate-code/node_modules/@altimateai/altimate-code-linux-x64/bin/altimate-code",
@@ -50,6 +51,7 @@ describe("resolveInstall", () => {
5051
["brew, intel prefix", "/usr/local/Cellar/altimate-code/0.11.2/bin/altimate", "brew"],
5152
["standalone install", "/home/u/.altimate/bin/altimate", "curl"],
5253
["standalone, pre-v0.7.1 dir", "/home/u/.opencode/bin/altimate", "curl"],
54+
["standalone, distro-resolved ~/.local/bin", "/home/u/.local/bin/altimate", "curl"],
5355
["scoop", "C:\\Users\\u\\scoop\\apps\\altimate-code\\current\\altimate.exe", "scoop"],
5456
["choco", "C:\\ProgramData\\chocolatey\\lib\\altimate-code\\tools\\altimate.exe", "choco"],
5557
// A dev build or an unrecognised location must not be attributed to a package
@@ -75,8 +77,11 @@ describe("resolveInstall", () => {
7577
expect(resolveInstall("/home/u/.altimate/bin/altimate", {}).root).toBe("/home/u/.altimate/bin")
7678
})
7779

78-
test("a plain user bin directory is not a standalone install", () => {
79-
// `.local/bin` on its own carries no information about who installed the binary.
80-
expect(resolveInstall("/home/u/.local/bin/altimate", {}).method).toBe("unknown")
80+
test("a standalone binary in ~/.local/bin is still a curl install (#820 back-compat)", () => {
81+
// Kept deliberately: it is a distro-resolved standalone location and is what
82+
// test/sanity/Dockerfile installs to. Safe because the node_modules match runs first —
83+
// see the npm-under-~/.local case above, which resolves to npm rather than here.
84+
expect(resolveInstall("/home/u/.local/bin/altimate", {}).method).toBe("curl")
85+
expect(resolveInstall("/home/u/.local/bin/altimate", {}).root).toBe("/home/u/.local/bin")
8186
})
8287
})

0 commit comments

Comments
 (0)