Skip to content

Commit ec21cc0

Browse files
fix(workspace): address codex review on the engine attach
Three findings from the codex review of dfb1838, all verified against the branch before fixing. **Replacing a live entry must not disable it in the config that owns it.** Teardown used `MCP.disconnect`, which persists `enabled: false` to whichever config file actually holds the entry — for an IDE-written or user-global `datamate`, that is the GLOBAL config. Our replacement is written project-local, so the user's engine stayed disabled in every OTHER project. `MCP.remove` is the right call: runtime-only teardown that closes the client, drops it from state and publishes ToolsChanged, touching no file. The reason for closing at all is unchanged — `MCP.add` does not close the client it overwrites. **The memo now follows the binding, not just the session id.** `ensure` was memoised per session, but `recordApprovedBinding` is reachable mid-session from the TUI workspace panel as well as `altimate-code link`. A session that started unbound would therefore never attach, and one re-linked to another workspace kept serving the old workspace's tools — both silently, for the rest of the session. The memo is keyed on the bound workspace, so a re-link produces a fresh attach on the next turn with its own wait budget, and an unchanged binding stays memoised. `ensure` is deliberately NOT async and registers its entry SYNCHRONOUSLY. `whenAttached` is called on the following line and looks the session up by id; an await before registration made that lookup miss, so the turn skipped the wait entirely — reintroducing the first-turn gap this module exists to close. Caught by the existing `whenAttached` tests, and now pinned by one that asserts the registration is visible immediately. **Pre-release versions no longer clear the floor.** `compareVersions` stripped the pre-release suffix, so `0.7.0-beta.1` compared equal to `0.7.0` and passed every compatibility gate. The floor exists to require behaviour that shipped in a release — the locked `--datamate` pin the attribution checks depend on — and a pre-release of that version predates it. Precedence now follows SemVer §11.3: a release outranks any pre-release of it, identifiers compare numerically where numeric, numeric ranks below alphanumeric, and a shorter identifier set ranks lower. Build metadata is ignored. Non-numeric cores still compare as older, so unreadable `--version` output can never clear a floor. 9 further tests: pre-release precedence and build metadata, an engine reporting a pre-release of the floor, re-link mid-session, unbound-then-linked, unchanged binding still memoised, and synchronous registration.
1 parent dfb1838 commit ec21cc0

2 files changed

Lines changed: 210 additions & 32 deletions

File tree

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

Lines changed: 98 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ export const syncInternals: {
124124
status: () => Promise<McpStatus>
125125
add: (name: string, cfg: LocalMcpConfig) => Promise<unknown>
126126
connect: (name: string) => Promise<unknown>
127-
disconnect: (name: string) => Promise<unknown>
127+
remove: (name: string) => Promise<unknown>
128128
tools: () => Promise<Record<string, unknown>>
129129
}
130130
persist?: (name: string, cfg: LocalMcpConfig) => Promise<void>
@@ -138,23 +138,56 @@ export function isEnabled(): boolean {
138138
return CoreFlag.ALTIMATE_WORKSPACE
139139
}
140140

141-
/** Numeric semver compare on the `major.minor.patch` core; pre-release tags
142-
* are ignored. Returns <0, 0, >0. Non-numeric input compares as older. */
141+
/** SemVer precedence compare. Returns <0, 0, >0.
142+
*
143+
* Build metadata is ignored, and a NON-numeric core component compares as older
144+
* so unreadable `--version` output can never clear a floor.
145+
*
146+
* Pre-release ordering is honoured rather than stripped: `0.7.0-beta.1` is
147+
* BELOW `0.7.0`. That matters here — the floor exists to require behaviour that
148+
* shipped in a specific release (the locked `--datamate` pin), and a pre-release
149+
* of that version predates it. Treating them as equal let a beta clear the floor
150+
* and be trusted for reuse. */
143151
export function compareVersions(a: string, b: string): number {
144-
const parse = (v: string) =>
145-
v
146-
.trim()
147-
.replace(/^v/, "")
148-
.split("-")[0]
149-
.split(".")
150-
.map((n) => Number.parseInt(n, 10))
151-
const pa = parse(a)
152-
const pb = parse(b)
152+
const split = (v: string) => {
153+
const bare = v.trim().replace(/^v/, "")
154+
const plus = bare.indexOf("+")
155+
const noBuild = plus >= 0 ? bare.slice(0, plus) : bare
156+
const dash = noBuild.indexOf("-")
157+
return {
158+
core: (dash >= 0 ? noBuild.slice(0, dash) : noBuild).split(".").map((n) => Number.parseInt(n, 10)),
159+
pre: dash >= 0 ? noBuild.slice(dash + 1) : "",
160+
}
161+
}
162+
const pa = split(a)
163+
const pb = split(b)
153164
for (let i = 0; i < 3; i++) {
154-
const x = Number.isFinite(pa[i]) ? pa[i] : -1
155-
const y = Number.isFinite(pb[i]) ? pb[i] : -1
165+
const x = Number.isFinite(pa.core[i]) ? pa.core[i] : -1
166+
const y = Number.isFinite(pb.core[i]) ? pb.core[i] : -1
156167
if (x !== y) return x - y
157168
}
169+
// Same core: a release outranks every pre-release of it (SemVer §11.3).
170+
if (!pa.pre && !pb.pre) return 0
171+
if (!pa.pre) return 1
172+
if (!pb.pre) return -1
173+
const ia = pa.pre.split(".")
174+
const ib = pb.pre.split(".")
175+
for (let i = 0; i < Math.max(ia.length, ib.length); i++) {
176+
const x = ia[i]
177+
const y = ib[i]
178+
if (x === undefined) return -1
179+
if (y === undefined) return 1
180+
const nx = /^\d+$/.test(x)
181+
const ny = /^\d+$/.test(y)
182+
if (nx && ny) {
183+
const d = Number(x) - Number(y)
184+
if (d !== 0) return d
185+
} else if (nx !== ny) {
186+
return nx ? -1 : 1
187+
} else if (x !== y) {
188+
return x < y ? -1 : 1
189+
}
190+
}
158191
return 0
159192
}
160193

@@ -220,7 +253,7 @@ function mcp() {
220253
status: () => MCP.status() as Promise<McpStatus>,
221254
add: (name: string, cfg: LocalMcpConfig) => MCP.add(name, cfg),
222255
connect: (name: string) => MCP.connect(name),
223-
disconnect: (name: string) => MCP.disconnect(name),
256+
remove: (name: string) => MCP.remove(name),
224257
tools: () => MCP.tools() as Promise<Record<string, unknown>>,
225258
}
226259
)
@@ -486,7 +519,14 @@ async function run(): Promise<Outcome> {
486519
// Close the live registration first: `MCP.add` does not close the client it
487520
// overwrites, so adding over a running stdio server starts a second engine
488521
// and abandons the first with its pipes still open.
489-
await client.disconnect(DATAMATE_KEY).catch((err) => {
522+
//
523+
// `remove`, NOT `disconnect`. `MCP.disconnect` persists `enabled: false` to
524+
// whichever config file actually holds the entry — which for an IDE-written
525+
// or user-global `datamate` is the GLOBAL config. Our replacement is written
526+
// project-locally, so disconnecting would leave the user's engine disabled in
527+
// every OTHER project. `remove` is runtime-only teardown: it closes the
528+
// client, drops it from state, and publishes ToolsChanged, touching no file.
529+
await client.remove(DATAMATE_KEY).catch((err) => {
490530
log.warn("could not close the engine entry being replaced", { err: String(err) })
491531
})
492532
}
@@ -538,14 +578,51 @@ async function run(): Promise<Outcome> {
538578
* answers costs the first turn a pause rather than the turn itself. */
539579
export const ATTACH_WAIT_MS = 15_000
540580

541-
type SessionAttach = { task: Promise<Outcome>; waitTimedOut?: boolean }
581+
type SessionAttach = { key?: string; task: Promise<Outcome>; waitTimedOut?: boolean }
542582

543583
const sessions = new Map<string, SessionAttach>()
544584

545-
export async function ensure(sessionID: string): Promise<Outcome> {
546-
const existing = sessions.get(sessionID)
547-
if (existing) return existing.task
548-
const task = run()
585+
/** What a memoised attach is valid FOR.
586+
*
587+
* Memoising on the session id alone was wrong: the binding can change while a
588+
* session is open — `recordApprovedBinding` is reachable mid-session from the
589+
* TUI workspace panel as well as from `altimate-code link`. A session that
590+
* started unbound would then never attach, and one that was re-linked to another
591+
* workspace would keep serving the old workspace's tools, both silently and for
592+
* the rest of the session. Keying on the bound workspace makes a re-link produce
593+
* a fresh attach on the next turn and leaves everything else memoised as before. */
594+
async function attachKey(): Promise<string> {
595+
if (!isEnabled()) return "disabled"
596+
const binding = await resolveBinding()
597+
return binding ? `workspace:${binding.datamateId}` : "unbound"
598+
}
599+
600+
export function ensure(sessionID: string): Promise<Outcome> {
601+
// NOT async, and the entry is registered SYNCHRONOUSLY. `whenAttached` is
602+
// called on the line after this one and looks the session up by id; if the
603+
// registration happened after an await, that lookup would find nothing and the
604+
// turn would sail past without waiting — which is exactly the first-turn gap
605+
// this module exists to close. All the async work happens inside the task.
606+
const previous = sessions.get(sessionID)
607+
const entry = { key: previous?.key, waitTimedOut: previous?.waitTimedOut } as SessionAttach
608+
entry.task = (async (): Promise<Outcome> => {
609+
const key = await attachKey()
610+
// Same workspace as the attach we already did for this session: reuse it.
611+
if (previous && previous.key === key) return previous.task
612+
// First attach for this session, or the binding changed under it. A changed
613+
// binding gets a fresh attach AND a fresh wait budget: the previous budget
614+
// was spent on a different workspace's engine.
615+
entry.key = key
616+
entry.waitTimedOut = false
617+
return attachOnce(sessionID)
618+
})()
619+
sessions.set(sessionID, entry)
620+
return entry.task
621+
}
622+
623+
/** One attach, with the outcome logged exactly once. */
624+
function attachOnce(sessionID: string): Promise<Outcome> {
625+
return run()
549626
.catch((err): Outcome => {
550627
log.warn("workspace engine attach failed", { err: String(err) })
551628
return { kind: "connect-failed", error: String(err) }
@@ -556,8 +633,6 @@ export async function ensure(sessionID: string): Promise<Outcome> {
556633
log.info("workspace engine outcome", { sessionID, ...outcome })
557634
return outcome
558635
})
559-
sessions.set(sessionID, { task })
560-
return task
561636
}
562637

563638
/** Wait for a session's in-flight attach, capped.

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

Lines changed: 112 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ type Harness = {
3232
added: Array<{ name: string; cfg: LocalMcpConfig }>
3333
persisted: Array<{ name: string; cfg: LocalMcpConfig }>
3434
connects: string[]
35-
disconnects: string[]
35+
removes: string[]
3636
toasts: Array<{ title: string; message: string; variant: string }>
3737
statusQueue: Array<Record<string, { status: string; error?: string } | undefined>>
3838
tools: Record<string, unknown>
@@ -51,7 +51,7 @@ function install(opts: {
5151
added: [],
5252
persisted: [],
5353
connects: [],
54-
disconnects: [],
54+
removes: [],
5555
toasts: [],
5656
statusQueue: opts.statuses ?? [{}],
5757
tools: opts.tools ?? {},
@@ -79,8 +79,8 @@ function install(opts: {
7979
connect: async (name) => {
8080
h.connects.push(name)
8181
},
82-
disconnect: async (name) => {
83-
h.disconnects.push(name)
82+
remove: async (name) => {
83+
h.removes.push(name)
8484
},
8585
tools: async () => h.tools,
8686
}
@@ -234,7 +234,7 @@ describe("ensure", () => {
234234
replaced: "http://localhost:7801/sse",
235235
})
236236
expect(h.connects).toHaveLength(0) // no pointless retry of a dead port
237-
expect(h.disconnects).toHaveLength(0) // a dead URL has nothing live to close
237+
expect(h.removes).toHaveLength(0) // a dead URL has nothing live to close
238238
expect(h.added).toHaveLength(1)
239239
expect(h.added[0].cfg.command).toEqual(["datamate", "start-stdio", "--datamate", "42"])
240240
expect(h.toasts[0].message).toContain("Replaced the unreachable engine URL http://localhost:7801/sse")
@@ -363,9 +363,11 @@ describe("ensure — attribution of a CONNECTED entry", () => {
363363
})
364364
// The replacement is a pinned spawn, so the engine we end up on is ours.
365365
expect(h.added[0].cfg.command).toEqual(["datamate", "start-stdio", "--datamate", "42"])
366-
// ...and the live one it displaced was CLOSED first. `MCP.add` does not close
367-
// the client it overwrites, so skipping this orphans a second live engine.
368-
expect(h.disconnects).toEqual(["datamate"])
366+
// ...and the live one it displaced was torn down first. `MCP.add` does not
367+
// close the client it overwrites, so skipping this orphans a second live
368+
// engine. It must be `remove` (runtime-only), never `disconnect`, which
369+
// would persist `enabled: false` into the config that owns the entry.
370+
expect(h.removes).toEqual(["datamate"])
369371
expect(h.toasts[0].message).toContain("not pinned to this workspace")
370372
})
371373

@@ -401,7 +403,7 @@ describe("ensure — attribution of a CONNECTED entry", () => {
401403
expect(await ensure("s1")).toEqual({ kind: "reused", available: 2 })
402404
expect(h.added).toHaveLength(0)
403405
expect(h.persisted).toHaveLength(0)
404-
expect(h.disconnects).toHaveLength(0) // reuse must never close what it reuses
406+
expect(h.removes).toHaveLength(0) // reuse must never tear down what it reuses
405407
})
406408

407409
test("a recovered entry is gated too: retried back to life but unpinned, it is replaced", async () => {
@@ -458,3 +460,104 @@ describe("ensure — the version floor applies to a REUSED entry", () => {
458460
expect(h.added).toHaveLength(0)
459461
})
460462
})
463+
464+
describe("compareVersions — pre-release precedence (SemVer §11.3)", () => {
465+
test("a pre-release of the floor version does NOT clear the floor", () => {
466+
// The floor exists to require behaviour that shipped in a release; a
467+
// pre-release of that version predates it, so it must rank below.
468+
expect(compareVersions("0.7.0-beta.1", "0.7.0")).toBeLessThan(0)
469+
expect(compareVersions("0.7.0", "0.7.0-beta.1")).toBeGreaterThan(0)
470+
expect(compareVersions("0.7.0-beta.1", MIN_ENGINE_VERSION)).toBeLessThan(0)
471+
})
472+
test("identifiers order by SemVer rules", () => {
473+
expect(compareVersions("0.7.0-alpha", "0.7.0-beta")).toBeLessThan(0)
474+
expect(compareVersions("0.7.0-beta.2", "0.7.0-beta.10")).toBeLessThan(0) // numeric, not lexical
475+
expect(compareVersions("0.7.0-alpha", "0.7.0-alpha.1")).toBeLessThan(0) // fewer fields rank lower
476+
expect(compareVersions("0.7.0-alpha.1", "0.7.0-alpha.beta")).toBeLessThan(0) // numeric < alphanumeric
477+
expect(compareVersions("0.7.0-beta.1", "0.7.0-beta.1")).toBe(0)
478+
})
479+
test("build metadata is ignored", () => {
480+
expect(compareVersions("0.7.0+build.5", "0.7.0")).toBe(0)
481+
expect(compareVersions("0.8.0+x", "0.7.0")).toBeGreaterThan(0)
482+
})
483+
test("a release still outranks an older release", () => {
484+
expect(compareVersions("0.7.1", "0.7.0")).toBeGreaterThan(0)
485+
expect(compareVersions("0.6.9", "0.7.0")).toBeLessThan(0)
486+
})
487+
})
488+
489+
describe("ensure — pre-release engines are refused", () => {
490+
test("an engine reporting a pre-release of the floor is too old", async () => {
491+
const h = install({ version: "0.7.0-beta.1" })
492+
expect(await ensure("s1")).toEqual({ kind: "engine-too-old", found: "0.7.0-beta.1" })
493+
expect(h.added).toHaveLength(0)
494+
expect(h.persisted).toHaveLength(0)
495+
})
496+
})
497+
498+
describe("ensure — the memo follows the BINDING, not just the session id", () => {
499+
const spawnTwice: Harness["statusQueue"] = [
500+
{},
501+
{ datamate: { status: "connected" } },
502+
{},
503+
{ datamate: { status: "connected" } },
504+
]
505+
506+
test("a re-link mid-session attaches the NEW workspace", async () => {
507+
// recordApprovedBinding is reachable mid-session from the TUI workspace
508+
// panel, so a live session's binding really can change under it.
509+
let current: CachedBinding | null = binding // datamate 42
510+
const h = install({ statuses: spawnTwice, tools: { datamate_dbt_build_model: 1 } })
511+
syncInternals.resolveBinding = async () => current
512+
513+
const first = await ensure("s1")
514+
expect(first).toMatchObject({ kind: "attached" })
515+
expect(h.added[0].cfg.command).toEqual(["datamate", "start-stdio", "--datamate", "42"])
516+
517+
current = { ...binding, datamateId: 99, datamateName: "other" } as CachedBinding
518+
const second = await ensure("s1")
519+
expect(second).toMatchObject({ kind: "attached" })
520+
expect(h.added).toHaveLength(2)
521+
expect(h.added[1].cfg.command).toEqual(["datamate", "start-stdio", "--datamate", "99"])
522+
})
523+
524+
test("a session that starts UNBOUND attaches once the project is linked", async () => {
525+
let current: CachedBinding | null = null
526+
const h = install({ statuses: spawnTwice, tools: { datamate_dbt_build_model: 1 } })
527+
syncInternals.resolveBinding = async () => current
528+
529+
expect(await ensure("s1")).toEqual({ kind: "unbound" })
530+
expect(h.added).toHaveLength(0)
531+
532+
current = binding
533+
expect(await ensure("s1")).toMatchObject({ kind: "attached" })
534+
expect(h.added).toHaveLength(1)
535+
})
536+
537+
test("an unchanged binding is still memoised — no second attach per turn", async () => {
538+
const h = install({
539+
statuses: [{}, { datamate: { status: "connected" } }],
540+
tools: { datamate_dbt_build_model: 1 },
541+
})
542+
const first = await ensure("s1")
543+
const second = await ensure("s1")
544+
const third = await ensure("s1")
545+
expect(second).toBe(first)
546+
expect(third).toBe(first)
547+
expect(h.added).toHaveLength(1)
548+
expect(h.persisted).toHaveLength(1)
549+
})
550+
551+
test("registration is SYNCHRONOUS, so whenAttached on the next line sees it", async () => {
552+
// ensure() must not await before registering: prompt.ts calls whenAttached
553+
// immediately after, and a late registration would make the turn skip the
554+
// wait entirely — the exact first-turn gap this module closes.
555+
const h = install({ tools: { datamate_dbt_build_model: 1 } })
556+
syncInternals.versionOf = () => new Promise<string | null>(() => {}) // never settles
557+
void ensure("s1")
558+
const started = performance.now()
559+
await whenAttached("s1", 30)
560+
expect(performance.now() - started).toBeGreaterThanOrEqual(20)
561+
expect(h).toBeDefined()
562+
})
563+
})

0 commit comments

Comments
 (0)