Skip to content

Commit cc57ee1

Browse files
saravmajesticclaude
andcommitted
fix: verify only against exact targets; bound ownership to our own packages (#1305)
Round-4 review findings, plus two more found by applying the same adversarial pass to the fixes themselves before pushing rather than after. **`altimate upgrade latest` always reported a successful upgrade as failed (CRITICAL).** `cli/cmd/upgrade.ts` forwards `args.target` verbatim, so a dist-tag (`latest`, `beta`) or a range (`^0.12.0`) reaches `upgrade()` as a literal string. The manager resolves it correctly and installs a concrete version — which the post-upgrade check then compared against the unresolved literal. `normalize("0.12.0") !== normalize("latest")` is true for every input, so there was no path on which a non-exact target could pass. Comparing a resolved version against a specifier is not a check; it is a guaranteed mismatch. Verification now only contradicts when the target is an exact version (`semver.valid`), and logs that it could not verify otherwise. **`ownerOf()` could attribute another package's dependency to our wrapper (MAJOR).** Being somewhere under the manager's root is weaker than belonging to our package: `<root>/some-other-cli/node_modules/@altimateai/altimate-code-<platform>/...` satisfied the containment check and was claimed by whichever single wrapper happened to be installed. Only two placements actually mean the platform package was installed for us — hoisted to the manager's own top level, or held in its virtual store — so the first path segment relative to the tree root now has to be `@altimateai` or a dot-prefixed store directory. **A transient probe failure was cached for the life of the process (MAJOR).** `computeIdentity` never fails in the Effect sense — `text()` turns a failed spawn into an empty string — so `Effect.cached` happily memoised a degraded `unknown`, silently disabling upgrade and blocking uninstall until restart. The identity now distinguishes "the manager answered and we are not in its tree", which is durable, from "the manager did not answer", which is not, and retries only the latter. Found while reviewing those fixes, before pushing: * A naive `if (unprobed) recompute` would have re-spawned the manager on every call for anyone whose manager genuinely is not installed — on a path that runs at every startup check. The retry is itself memoised, giving exactly one extra attempt shared by all callers, with no check-then-act window. * `uninstall` still carried a `?? "@altimateai/altimate-code"` default — the same silent substitution that made an earlier revision delete a user's data and then remove a package that was never installed. It is unreachable today, because a package-manager method is only returned once ownership is confirmed, but the shape is the bug. A managed method with no confirmed package now refuses and prints manual steps. * Recovery guidance printed `@latest` regardless of what was asked for; it now echoes the requested target. Tests: non-exact targets (`latest`, `beta`, `^0.12.0`) are not reported as failures, while an exact target that does not match afterwards still fails; a sibling package's transitive platform dependency is not ours, and a hoisted one is. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
1 parent c6e9c51 commit cc57ee1

5 files changed

Lines changed: 152 additions & 19 deletions

File tree

‎packages/opencode/src/cli/cmd/uninstall.ts‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -94,13 +94,27 @@ export const UninstallCommand = {
9494
}
9595
// altimate_change end
9696

97-
const targets = await collectRemovalTargets(args, method)
98-
9997
// altimate_change start — #1305: the package the MANAGER confirms owns this binary.
10098
// publish.ts ships both a scoped and an unscoped wrapper; removing the wrong one removes
10199
// nothing while uninstall goes on to delete config and cache.
102-
const pkg = (await Installation.packageName()) ?? "@altimateai/altimate-code"
103-
await showRemovalSummary(targets, method, pkg)
100+
//
101+
// No `?? "@altimateai/altimate-code"` default here. A package-manager method is only
102+
// returned once ownership was confirmed, so a missing name alongside one of those methods
103+
// is a contradiction, not a case to guess through — and guessing is precisely what made an
104+
// earlier revision delete a user's data and then remove a package that was not installed.
105+
const pkg = await Installation.packageName()
106+
const managed = method === "npm" || method === "pnpm" || method === "bun" || method === "yarn"
107+
if (managed && !pkg) {
108+
prompts.log.error(`Detected a ${method} installation but could not confirm which package owns it.`)
109+
prompts.log.info("Nothing was removed. Remove the package with your package manager, then delete:")
110+
for (const dir of [Global.Path.data, Global.Path.config, Global.Path.cache, Global.Path.state]) {
111+
prompts.log.info(` ${dir}`)
112+
}
113+
prompts.outro("Nothing was removed")
114+
return
115+
}
116+
const targets = await collectRemovalTargets(args, method)
117+
await showRemovalSummary(targets, method, pkg ?? "altimate-code")
104118
// altimate_change end
105119

106120
if (!args.force && !args.dryRun) {
@@ -122,7 +136,7 @@ export const UninstallCommand = {
122136

123137
// altimate_change start — #1305: pass the verified package name through so removal
124138
// targets the wrapper the user actually installed.
125-
await executeUninstall(method, targets, pkg)
139+
await executeUninstall(method, targets, pkg ?? "altimate-code")
126140
// altimate_change end
127141

128142
prompts.outro("Done")

‎packages/opencode/src/cli/cmd/upgrade.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -61,13 +61,17 @@ export const UpgradeCommand = {
6161
? `Cannot determine how altimate was installed (running from ${process.execPath}).`
6262
: `Upgrading a ${method} installation is not supported.`,
6363
)
64+
// altimate_change — #1305: echo the target the user actually asked for. Printing
65+
// `@latest` after `altimate upgrade 0.8.10` tells them to install something other than
66+
// what they requested.
67+
const want = args.target ? args.target.replace(/^v/, "") : "latest"
6468
prompts.log.info("Upgrade with whichever tool installed it:")
65-
prompts.log.info(" npm: npm install -g altimate-code@latest")
66-
prompts.log.info(" pnpm: pnpm install -g altimate-code@latest")
67-
prompts.log.info(" bun: bun install -g altimate-code@latest")
69+
prompts.log.info(` npm: npm install -g altimate-code@${want}`)
70+
prompts.log.info(` pnpm: pnpm install -g altimate-code@${want}`)
71+
prompts.log.info(` bun: bun install -g altimate-code@${want}`)
6872
// altimate_change — #1305: yarn is in UNSUPPORTED_UPGRADE_METHODS and routes here, so it
6973
// needs a line; uninstall.ts's equivalent message already had one.
70-
prompts.log.info(" yarn: yarn global add altimate-code@latest")
74+
prompts.log.info(` yarn: yarn global add altimate-code@${want}`)
7175
prompts.log.info(" Homebrew: brew upgrade altimate-code")
7276
prompts.log.info(
7377
process.platform === "win32"

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

Lines changed: 60 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -160,8 +160,19 @@ export function ownerOf(root: string, execPath: string): string | undefined {
160160
if (isInside(execPath, path.join(root, ...name.split("/")))) return name
161161
}
162162
if (!PLATFORM_PKG_RE.test(execPath)) return undefined
163-
// Must be this manager's tree — `dirname(root)` covers stores kept beside `node_modules`.
164-
if (!isInside(execPath, root) && !isInside(execPath, path.dirname(root))) return undefined
163+
// Must be this manager's tree. `dirname(root)` covers stores kept beside `node_modules`.
164+
const base = isInside(execPath, root) ? root : isInside(execPath, path.dirname(root)) ? path.dirname(root) : ""
165+
if (!base) return undefined
166+
// Sharing the manager's root is NOT the same as belonging to our wrapper.
167+
// `<root>/some-other-cli/node_modules/@altimateai/altimate-code-<platform>/...` is an
168+
// unrelated package's dependency that merely lives under the same root; claiming it would
169+
// upgrade or remove OUR package on the strength of someone else's dependency tree.
170+
// Only two placements mean the platform package was installed for us: hoisted to the
171+
// manager's own top level, or held in its virtual store.
172+
const first = path.relative(realpathOr(base), realpathOr(execPath)).split(path.sep)[0] ?? ""
173+
const hoisted = first === "@altimateai"
174+
const virtualStore = first.startsWith(".") && first !== "." && first !== ".."
175+
if (!hoisted && !virtualStore) return undefined
165176
// Exactly one of our wrappers installed: it is the only thing that could have pulled this
166177
// platform package in. Both installed means we cannot say which, and guessing would
167178
// upgrade or remove the wrong one.
@@ -356,6 +367,8 @@ export const UNSUPPORTED_UPGRADE_METHODS: Method[] = ["unknown", "yarn", "scoop"
356367
/** One resolved answer about this install, shared by every consumer. */
357368
interface ResolvedIdentity {
358369
readonly method: Method
370+
/** True when the manager could not be queried at all, so this answer is not durable. */
371+
readonly unprobed?: boolean
359372
/** Verified owning package — present only when a manager confirmed it. */
360373
readonly packageName?: string
361374
readonly packageRoot: string
@@ -591,11 +604,13 @@ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient | AppProce
591604
return { method: candidate, packageRoot: layout.packageRoot, writable: layout.writable } as ResolvedIdentity
592605
}
593606
const owner = ownerOf(layout.packageRoot, realExecPath())
594-
return (
595-
owner
596-
? { method: candidate, packageName: owner, packageRoot: layout.packageRoot, writable: layout.writable }
597-
: { method: "unknown" as Method, packageRoot: "", writable: [] }
598-
) as ResolvedIdentity
607+
if (owner) {
608+
return { method: candidate, packageName: owner, packageRoot: layout.packageRoot, writable: layout.writable }
609+
}
610+
// Distinguish "the manager answered and we are not in its tree" — a fact about this
611+
// install — from "the manager did not answer", which is a fact about one probe.
612+
// `text()` turns a failed spawn into an empty string, so an empty root is the latter.
613+
return { method: "unknown" as Method, packageRoot: "", writable: [], unprobed: layout.packageRoot === "" }
599614
})
600615

601616
// Effect.cached rather than `let cached` guarded by `if (cached) return cached`: that is a
@@ -604,8 +619,28 @@ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient | AppProce
604619
// reach method() — would each compute a result and the slower would overwrite the faster,
605620
// so a degraded probe landing second pins "unknown" for the rest of the process.
606621
// Effect.cached dedupes the in-flight computation instead of just its result.
607-
const cachedIdentity = yield* Effect.cached(computeIdentity)
608-
const identity = () => cachedIdentity
622+
// Two layers, both memoised, because each solves a different problem and a plain
623+
// `if (unprobed) recompute` solves neither cleanly:
624+
//
625+
// - `Effect.cached` memoises whatever the effect first RESOLVES to, and computeIdentity
626+
// never fails in the Effect sense (`text()` swallows a failed spawn and returns ""),
627+
// so a single transient hiccup would pin "unknown" for the life of the process —
628+
// silently disabling upgrade and blocking uninstall until restart.
629+
// - Retrying on every call instead would re-spawn the manager forever for anyone whose
630+
// manager genuinely is not installed, on a path that runs at every startup check.
631+
//
632+
// Caching the retry itself gives exactly one extra attempt, shared by all callers, with
633+
// no check-then-act window: a definitive answer is kept, a failed probe is retried once,
634+
// and a second failure is then accepted rather than re-probed indefinitely.
635+
const firstAttempt = yield* Effect.cached(computeIdentity)
636+
const resolvedIdentity = yield* Effect.cached(
637+
Effect.gen(function* () {
638+
const first = yield* firstAttempt
639+
if (!first.unprobed) return first
640+
return yield* computeIdentity
641+
}),
642+
)
643+
const identity = () => resolvedIdentity
609644

610645
/** The package to install or remove for `m`.
611646
*
@@ -1066,7 +1101,22 @@ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient | AppProce
10661101
// output is neither: we cannot verify, so we say so rather than failing a good
10671102
// upgrade or claiming one we did not confirm.
10681103
const unrunnable = verify.code !== 0
1069-
const contradicted = after !== "" && normalize(after) !== normalize(target)
1104+
// Only an EXACT version can contradict. `target` is whatever the caller passed, and
1105+
// `cli/cmd/upgrade.ts` forwards `args.target` verbatim — so `altimate upgrade latest`,
1106+
// a dist-tag (`beta`), or a range (`^0.12.0`) all reach here as literal strings. The
1107+
// manager resolves them correctly and installs a concrete version, which then can
1108+
// never equal the literal, so every such upgrade was reported as a failure. Comparing
1109+
// a resolved version against an unresolved specifier is not a check, it is a guaranteed
1110+
// mismatch.
1111+
const exactTarget = semver.valid(normalize(target)) !== null
1112+
const contradicted = exactTarget && after !== "" && normalize(after) !== normalize(target)
1113+
if (!exactTarget && after !== "") {
1114+
yield* Effect.logInfo("upgrade target was not an exact version — not verified against it", {
1115+
method: m,
1116+
target,
1117+
running: redactSecrets(after),
1118+
})
1119+
}
10701120
const T2 = yield* Effect.promise(() => getTelemetry())
10711121
if (after === "" && !unrunnable) {
10721122
yield* Effect.logWarning("could not verify the upgraded binary", {

‎packages/opencode/test/installation/installation.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,46 @@ describe("installation", () => {
9191
})
9292
// altimate_change end
9393

94+
// altimate_change start — #1305: `cli/cmd/upgrade.ts` forwards `args.target` verbatim, so a
95+
// dist-tag or range reaches upgrade() as a literal. Comparing the resolved version against
96+
// that literal can never match, which reported EVERY `altimate upgrade latest` as a failure.
97+
// Verification now only contradicts on an exact version.
98+
describe("non-exact upgrade targets", () => {
99+
for (const target of ["latest", "beta", "^0.12.0"]) {
100+
testEffect(
101+
testLayer(
102+
() => new Response("", { status: 200 }),
103+
(cmd, args) => {
104+
// The manager resolves the specifier and installs a concrete version.
105+
if (args.includes("--version")) return "0.12.0"
106+
return ""
107+
},
108+
),
109+
).effect(`upgrade to "${target}" is not reported as a failure`, () =>
110+
Effect.gen(function* () {
111+
yield* Installation.use.upgrade("npm", target)
112+
}),
113+
)
114+
}
115+
116+
testEffect(
117+
testLayer(
118+
() => new Response("", { status: 200 }),
119+
(cmd, args) => {
120+
if (args.includes("--version")) return "0.9.9"
121+
return ""
122+
},
123+
),
124+
).effect("an EXACT target that does not match afterwards still fails", () =>
125+
Effect.gen(function* () {
126+
const error = yield* Effect.flip(Installation.use.upgrade("npm", "0.12.0"))
127+
expect(error).toBeInstanceOf(Installation.UpgradeFailedError)
128+
expect(error.stderr).toContain("0.9.9")
129+
}),
130+
)
131+
})
132+
// altimate_change end
133+
94134
describe("latest", () => {
95135
testEffect(testLayer(() => jsonResponse({ tag_name: "v1.2.3" }))).effect(
96136
"reads release version from GitHub releases",

‎packages/opencode/test/installation/ownership.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,31 @@ describe("ownerOf", () => {
163163
expect(ownerOf(store, exec)).toBeUndefined()
164164
})
165165

166+
test("another top-level package's transitive platform dependency is not ours", () => {
167+
// `<root>/some-other-cli/node_modules/@altimateai/altimate-code-<platform>/...` sits
168+
// under the manager's root, so a containment-only check accepted it and attributed it to
169+
// our single installed wrapper — upgrading or removing OUR package because someone else
170+
// depends on the platform build.
171+
const store = path.join(root, "sibling-dep", "node_modules")
172+
fs.mkdirSync(path.join(store, "altimate-code"), { recursive: true })
173+
const foreign = path.join(store, "some-other-cli", "node_modules", "@altimateai", "altimate-code-linux-x64", "bin")
174+
fs.mkdirSync(foreign, { recursive: true })
175+
const exec = path.join(foreign, "altimate-code")
176+
fs.writeFileSync(exec, "")
177+
expect(ownerOf(store, exec)).toBeUndefined()
178+
})
179+
180+
test("a platform package hoisted to the manager's own top level IS ours", () => {
181+
// The placement that legitimately means "installed for us": hoisted beside the wrapper.
182+
const store = path.join(root, "hoisted", "node_modules")
183+
fs.mkdirSync(path.join(store, "altimate-code"), { recursive: true })
184+
const hoisted = path.join(store, "@altimateai", "altimate-code-linux-x64", "bin")
185+
fs.mkdirSync(hoisted, { recursive: true })
186+
const exec = path.join(hoisted, "altimate-code")
187+
fs.writeFileSync(exec, "")
188+
expect(ownerOf(store, exec)).toBe("altimate-code")
189+
})
190+
166191
test("a platform binary outside the manager's tree does not borrow its identity", () => {
167192
// A project-local platform package must not be attributed to a global wrapper.
168193
const store = path.join(root, "bounded", "node_modules")

0 commit comments

Comments
 (0)