Skip to content

Commit bf30354

Browse files
fix(workspace): ask about the running engine the way it runs, and keep asking until the answer is given
Four sites where a rule stated in one place had not reached its neighbour. The reuse answer, like the attached one, is given after announcements that are awaits; it now asks the same two questions again after the last of them and settles a change the same way it would have before them. The verdict handling is one closure asked twice, so the two askings cannot drift. The version probe resolves a relative `cwd` against the instance directory, as the engine's own launch does; probed against wherever this process started, a relative command or PATH entry could name a different binary than the one the engine runs. The memo's re-probe key carries the whole launch identity of both halves, not their argv: a replacement with the same argv under a different PATH or working directory runs a different binary and is probed again. `entryIdentity` is the one definition, shared with `sameEntry`. The undo keeps an entry that was rewritten AND disabled while it was held. Projecting the disable onto what the undo replaced would have overwritten the newer transport with the old one; neither the transport nor the disable is ours. A read-count fixture gains the reuse answer's second intent read. Reverting each of the four fails a named test.
1 parent 5de0acf commit bf30354

6 files changed

Lines changed: 163 additions & 45 deletions

File tree

‎packages/opencode/src/altimate/workspace/engine-probes.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
// Everything that asks the outside world a question: the binary, its version,
44
// MCP, the workspace allowlist, and the user-facing toast. Moved verbatim — the
55
// state machine buys nothing here, and every touched line is new-bug surface.
6+
import path from "path"
67
import launch from "cross-spawn"
78
import { which as whichBinary } from "@opencode-ai/core/util/which"
89
import { MCP, ToolsChanged } from "@/mcp"
@@ -200,5 +201,12 @@ export async function notify(toast: Toast): Promise<void> {
200201
export async function engineVersionOf(entry: ExistingEntry | null): Promise<string | null> {
201202
const bin = commandArgv(entry)[0]
202203
const direct = bin && /(^|[\\/])datamate(\.[a-z]+)?$/i.test(bin) ? bin : null
203-
return direct ? await versionOf(direct, { environment: entry?.environment, cwd: entry?.cwd }) : null
204+
if (!direct) return null
205+
// Probed the way the engine is launched: MCP resolves a relative `cwd`
206+
// against the instance directory, so the probe does too. Left relative, it
207+
// would resolve against wherever this process happened to start, and a
208+
// relative command or PATH entry could name a different binary there.
209+
const base = currentDirectory()
210+
const cwd = entry?.cwd ? (base ? path.resolve(base, entry.cwd) : entry.cwd) : undefined
211+
return await versionOf(direct, { environment: entry?.environment, cwd })
204212
}

‎packages/opencode/src/altimate/workspace/engine-seams.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ export const syncInternals: {
1616
resolveBinding?: () => Promise<CachedBinding | null>
1717
which?: (cmd: string) => string | null
1818
versionOf?: (bin: string, spawn?: { environment?: Record<string, string>; cwd?: string }) => Promise<string | null>
19+
/** The instance directory a relative launch `cwd` resolves against. */
20+
instanceDirectory?: () => string | null
1921
mcp?: {
2022
status: () => Promise<McpStatus>
2123
add: (name: string, cfg: LocalMcpConfig) => Promise<unknown>
@@ -44,6 +46,7 @@ export function isEnabled(): boolean {
4446
}
4547

4648
export function currentDirectory(): string | null {
49+
if (syncInternals.instanceDirectory) return syncInternals.instanceDirectory()
4750
try {
4851
return Instance.directory
4952
} catch {

‎packages/opencode/src/altimate/workspace/engine-sync.ts‎

Lines changed: 47 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ import {
7070
isUrlEntry,
7171
pinnedWorkspace,
7272
sameEntry,
73+
entryIdentity,
7374
ENGINE_BINARY,
7475
INSTALL_HINT,
7576
MIN_ENGINE_VERSION,
@@ -98,6 +99,7 @@ import { serializeAttach, trackedChainsForTests, attachChains } from "./engine-c
9899
export {
99100
attributableEngine,
100101
sameEntry,
102+
entryIdentity,
101103
clearsFloor,
102104
compareVersions,
103105
engineToolKeys,
@@ -806,6 +808,13 @@ async function run(sessionID: string): Promise<Outcome> {
806808
return "failed"
807809
}
808810
if (now?.enabled === false) {
811+
if (!sameEntry(now, installed)) {
812+
// Rewritten AND disabled while we held it. Neither the transport nor
813+
// the disable is ours: projecting the disable onto what we replaced
814+
// would overwrite the newer transport with the old one.
815+
log.info("not restoring; the entry was rewritten and disabled since we installed", { workspaceId })
816+
return "restored"
817+
}
809818
log.info("the entry was disabled while we held it; keeping the disable rather than undoing it", {
810819
workspaceId,
811820
})
@@ -1102,30 +1111,35 @@ async function run(sessionID: string): Promise<Outcome> {
11021111
//
11031112
// The tool and allowlist reads above are two awaits; `confirmServing`
11041113
// asks the two questions every named answer asks after them.
1105-
const verdict = await confirmServing(runningEngine(inspection))
1106-
if (verdict === "replaced" || verdict === "gone") {
1107-
// A replacement is someone else's and not ours to detach; a client that
1108-
// is gone has nothing to detach. Either way the next decision judges
1109-
// what is there on its own merits.
1110-
log.info("the engine we judged is no longer the one serving; not answering for it", {
1111-
workspaceId,
1112-
verdict,
1113-
})
1114-
return { kind: "superseded" }
1115-
}
1116-
if (verdict === "disabled") return await refuseDisabled()
1117-
if (verdict === "unreadable") return await refuseUnreadable("intent could not be confirmed")
1118-
if (verdict === "moved") {
1119-
// Detach, do not merely decline. The caller runs `resolveTools` whatever
1120-
// this returns, so leaving the old client registered hands that turn the
1121-
// previous workspace's tools and credentials anyway — the outcome is
1122-
// advice, the registration is what the model sees.
1114+
// What a non-`ok` verdict means for a reuse answer. Asked twice: once
1115+
// after the lookup awaits, and again after the announcements — which are
1116+
// awaits too, and every await after a guard belongs to the guard.
1117+
const settleReuse = async (verdict: Awaited<ReturnType<typeof confirmServing>>): Promise<Outcome | null> => {
1118+
if (verdict === "ok") return null
1119+
if (verdict === "replaced" || verdict === "gone") {
1120+
// A replacement is someone else's and not ours to detach; a client
1121+
// that is gone has nothing to detach. Either way the next decision
1122+
// judges what is there on its own merits.
1123+
log.info("the engine we judged is no longer the one serving; not answering for it", {
1124+
workspaceId,
1125+
verdict,
1126+
})
1127+
return { kind: "superseded" }
1128+
}
1129+
if (verdict === "disabled") return await refuseDisabled()
1130+
if (verdict === "unreadable") return await refuseUnreadable("intent could not be confirmed")
1131+
// Moved. Detach, do not merely decline: the caller runs `resolveTools`
1132+
// whatever this returns, so leaving the old client registered hands
1133+
// that turn the previous workspace's tools and credentials anyway — the
1134+
// outcome is advice, the registration is what the model sees.
11231135
log.info("binding changed while reusing; detaching rather than answering for the old workspace", {
11241136
workspaceId,
11251137
})
11261138
await removeIfOurs(runningEngine(inspection), { reason: "superseded while reusing" })
11271139
return { kind: "superseded" }
11281140
}
1141+
const settled = await settleReuse(await confirmServing(runningEngine(inspection)))
1142+
if (settled) return settled
11291143
// The gap is reported only for the engine this turn is actually answered
11301144
// with. Announcing it before the questions above would warn about an
11311145
// engine that is then refused or found replaced — a second signal for a
@@ -1139,6 +1153,17 @@ async function run(sessionID: string): Promise<Outcome> {
11391153
variant: "warning",
11401154
})
11411155
}
1156+
const reused: Outcome = {
1157+
kind: "reused",
1158+
available,
1159+
...(declaredKeys ? { declared: declaredKeys.keys.length, missing } : {}),
1160+
}
1161+
await noteHostedNeighbours(reused)
1162+
// The announcements above are awaits; the answer must be true when it is
1163+
// given, not only when it was fixed. Same check, same handling, after
1164+
// the last of them.
1165+
const afterAnnouncing = await settleReuse(await confirmServing(runningEngine(inspection)))
1166+
if (afterAnnouncing) return afterAnnouncing
11421167
clearAnnouncement(sessionID)
11431168
log.info("reusing existing engine entry", {
11441169
workspaceId,
@@ -1147,12 +1172,6 @@ async function run(sessionID: string): Promise<Outcome> {
11471172
declared: declaredKeys?.keys.length,
11481173
missing,
11491174
})
1150-
const reused: Outcome = {
1151-
kind: "reused",
1152-
available,
1153-
...(declaredKeys ? { declared: declaredKeys.keys.length, missing } : {}),
1154-
}
1155-
await noteHostedNeighbours(reused)
11561175
return reused
11571176
}
11581177

@@ -1589,7 +1608,10 @@ async function memoStillValid(workspaceId: string, record?: SessionAttach): Prom
15891608
// worth naming: a binary swapped in place under an unchanged command is not
15901609
// caught until the next session.
15911610
const running = runningEngine(inspection)
1592-
const command = `${commandArgv(running).join(" ")}|${commandArgv(configuredEntry(inspection)).join(" ")}`
1611+
// Keyed on the whole launch identity of both halves, not their argv: a
1612+
// replacement with the same argv under a different PATH or working
1613+
// directory runs a different binary, and must be probed again.
1614+
const command = `${entryIdentity(running)}|${entryIdentity(configuredEntry(inspection))}`
15931615
if (record && record.validated === command) return true
15941616
const found = await engineVersionOf(running)
15951617
if (!clearsFloor(found)) {

‎packages/opencode/src/altimate/workspace/engine-types.ts‎

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -238,20 +238,25 @@ const IDENTITY_FIELDS: Record<Exclude<keyof ExistingEntry, "enabled">, true> = {
238238
}
239239

240240
export function sameEntry(a: ExistingEntry | null | undefined, b: ExistingEntry | null | undefined): boolean {
241-
const shape = (e: ExistingEntry | null | undefined) => {
242-
const raw = (e ?? {}) as Record<string, unknown>
243-
const parts: Record<string, unknown> = {
244-
// `command` and `args` are compared as the argv they produce, since the
245-
// same invocation can be spelled either way.
246-
argv: commandArgv((e ?? null) as ExistingEntry | null),
247-
}
248-
for (const field of Object.keys(IDENTITY_FIELDS)) {
249-
if (field === "command" || field === "args") continue
250-
parts[field] = raw[field] ?? null
251-
}
252-
return JSON.stringify(parts)
241+
return entryIdentity(a) === entryIdentity(b)
242+
}
243+
244+
/** The identity of the process an entry describes, as one comparable string —
245+
* the same fields `sameEntry` compares, usable as a cache key. A cache keyed
246+
* on argv alone accepts a replacement with the same argv under a different
247+
* PATH or working directory, which runs a different binary. */
248+
export function entryIdentity(e: ExistingEntry | null | undefined): string {
249+
const raw = (e ?? {}) as Record<string, unknown>
250+
const parts: Record<string, unknown> = {
251+
// `command` and `args` are compared as the argv they produce, since the
252+
// same invocation can be spelled either way.
253+
argv: commandArgv((e ?? null) as ExistingEntry | null),
254+
}
255+
for (const field of Object.keys(IDENTITY_FIELDS)) {
256+
if (field === "command" || field === "args") continue
257+
parts[field] = raw[field] ?? null
253258
}
254-
return shape(a) === shape(b)
259+
return JSON.stringify(parts)
255260
}
256261

257262
/** Is this engine version usable at all?

‎packages/opencode/test/altimate/workspace/engine-sync.test.ts‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import {
2929
type LocalMcpConfig,
3030
type Outcome,
3131
} from "../../../src/altimate/workspace/engine-sync"
32+
import { engineVersionOf } from "../../../src/altimate/workspace/engine-probes"
3233
import type { CachedBinding } from "../../../src/altimate/workspace/state"
3334
import type { ExistingEntry } from "../../../src/altimate/workspace/engine-sync"
3435

@@ -1370,6 +1371,84 @@ describe("an answer is revalidated before it is given", () => {
13701371
expect(h.toasts.filter((t) => t.title.endsWith("connected"))).toHaveLength(1)
13711372
expect(h.toasts.filter((t) => t.variant === "error")).toHaveLength(0)
13721373
})
1374+
1375+
test("a re-link during the reuse announcements is not answered with the old workspace", async () => {
1376+
// The reuse answer is fixed after the lookup and given after the
1377+
// missing-tools warning and the hosted-neighbours note, which are awaits.
1378+
// Same rule as the attached path: asked again after the last announcement.
1379+
let current: CachedBinding | null = binding // 42
1380+
const h = install({
1381+
existing: { type: "local", command: ["datamate", "start-stdio", "--datamate", "42"] },
1382+
statuses: [{ datamate: { status: "connected" } }],
1383+
tools: { datamate_dbt_build_model: 1 }, // dbt_compile_model is declared but missing → a warning is announced
1384+
})
1385+
syncInternals.resolveBinding = async () => current
1386+
const prevNotify = syncInternals.notify!
1387+
syncInternals.notify = async (toast) => {
1388+
await prevNotify(toast)
1389+
if (toast.title.includes("missing declared tools")) current = { ...binding, datamateId: 99, datamateName: "other" } as CachedBinding
1390+
}
1391+
expect((await ensure("s1")).kind).toBe("superseded")
1392+
expect(h.removes, "left the old workspace's engine serving under the new binding").toEqual(["datamate"])
1393+
expect(h.added).toHaveLength(0)
1394+
})
1395+
1396+
test("a memo is re-probed when the running launch changes under an unchanged argv", async () => {
1397+
// Identity is the whole launch — a replacement with the same argv under a
1398+
// different PATH runs a different binary, and a cache keyed on argv alone
1399+
// would accept it without asking its version.
1400+
const h = install({
1401+
existing: { type: "local", command: ["datamate", "start-stdio", "--datamate", "42"] },
1402+
statuses: [{ datamate: { status: "connected" } }],
1403+
tools: { datamate_dbt_build_model: 1 },
1404+
})
1405+
let probes = 0
1406+
syncInternals.versionOf = async () => ((probes += 1), "0.7.0")
1407+
await ensure("s1") // reuse: probes once
1408+
await ensure("s1") // memo validation: probes once and records the launch identity
1409+
const validated = probes
1410+
await ensure("s1") // unchanged launch: no probe
1411+
expect(probes, "re-probed an unchanged launch").toBe(validated)
1412+
h.spawnedNow = {
1413+
type: "local",
1414+
command: ["datamate", "start-stdio", "--datamate", "42"],
1415+
environment: { PATH: "/somewhere/else/bin" },
1416+
} as never
1417+
await ensure("s1")
1418+
expect(probes, "accepted a replacement with the same argv under a different PATH without probing").toBe(validated + 1)
1419+
})
1420+
1421+
test("the undo keeps an entry that was rewritten AND disabled while it was held", async () => {
1422+
// Neither the new transport nor the disable is ours: projecting the disable
1423+
// onto what we replaced would overwrite the newer transport with the old one.
1424+
let current: CachedBinding | null = binding
1425+
const h = install({ statuses: [{}, { datamate: { status: "connected" } }], tools: { datamate_dbt_build_model: 1 } })
1426+
syncInternals.resolveBinding = async () => current
1427+
syncInternals.projectEntry = async () =>
1428+
h.persisted.length
1429+
? ({ type: "local", command: ["/their/datamate", "start-stdio", "--datamate", "42"], enabled: false } as ExistingEntry)
1430+
: null
1431+
const prevTools = syncInternals.mcp!.tools!
1432+
syncInternals.mcp!.tools = async () => {
1433+
current = { ...binding, datamateId: 99, datamateName: "other" } as CachedBinding
1434+
return prevTools()
1435+
}
1436+
expect((await ensure("s1")).kind).toBe("superseded")
1437+
expect(h.restores, "overwrote a transport the user rewrote while we held the entry").toHaveLength(0)
1438+
})
1439+
1440+
test("the version probe resolves a relative cwd the way the engine is launched", async () => {
1441+
// MCP resolves a relative `cwd` against the instance directory. Probed
1442+
// against the process's own directory instead, a relative command or PATH
1443+
// entry can name a different binary than the one the engine runs.
1444+
const seen: Array<string | undefined> = []
1445+
syncInternals.instanceDirectory = () => "/proj/root"
1446+
syncInternals.versionOf = async (_bin, spawn) => ((seen.push(spawn?.cwd)), "0.7.0")
1447+
await engineVersionOf({ type: "local", command: ["datamate", "start-stdio", "--datamate", "42"], cwd: "tools" } as ExistingEntry)
1448+
await engineVersionOf({ type: "local", command: ["datamate", "start-stdio", "--datamate", "42"], cwd: "/abs/tools" } as ExistingEntry)
1449+
await engineVersionOf({ type: "local", command: ["datamate", "start-stdio", "--datamate", "42"] } as ExistingEntry)
1450+
expect(seen).toEqual(["/proj/root/tools", "/abs/tools", undefined])
1451+
})
13731452
})
13741453

13751454
describe("a cached success is re-probed against the floor", () => {

‎packages/opencode/test/altimate/workspace/seam-contract.test.ts‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -538,12 +538,13 @@ describe("the retry re-inspects, and never writes the memo early or twice", () =
538538
expect(outcome).toMatchObject({ kind: "reused" })
539539
expect(h.connects, "repaired with the config-writing primitive").toHaveLength(0)
540540
expect(h.added, "the retry restarts the entry exactly once").toHaveLength(1)
541-
// Four: the inspection, the pre-revive world check's intent read, the
542-
// re-inspection, and the reuse answer's own world check. The second is the
543-
// guard confirming intent immediately before starting a process; the
544-
// fourth confirms it again before the answer names the engine — mutations
545-
// and named answers both re-read.
546-
expect(entryReads).toBe(4)
541+
// Five: the inspection, the pre-revive world check's intent read, the
542+
// re-inspection, and the reuse answer's two world checks — one after the
543+
// lookup awaits and one after the announcements. The second is the guard
544+
// confirming intent immediately before starting a process; the last two
545+
// confirm it before the answer names the engine and again when the answer
546+
// is given — mutations and named answers both re-read.
547+
expect(entryReads).toBe(5)
547548
expect(statusReads).toBe(2)
548549
expect(reads.every((r) => r === undefined)).toBe(true) // nothing observable mid-run
549550
expect(settledOutcome("s1")).toBe(outcome)

0 commit comments

Comments
 (0)