Skip to content

Commit 37dd23d

Browse files
fix(workspace): revalidate after cached-success validation, and restore the project entry
Codex round 18. Two findings, both verified, both proven by revert. **The memoised-success path needed the final binding check too.** Validating a cached success is itself awaited work — status, config, and sometimes a version probe — so the binding can move underneath it. That path lives in `ensure()`, outside `run()`, and so never had run's closing check: a confirmed-valid engine for the workspace just left was returned as the answer for the one just joined, and the turn took its tools and credentials. This is the same rule that has now been applied in four places: revalidate before answering, because an answer this flow gives is acted on. The rule was right; it had not been carried to the one path that does its validating elsewhere. **A superseded attach now restores the project entry, not the merged one.** `existingEntry()` returns the merged view, which may come from global config, while `persist()` writes to the project file. Restoring the merged value wrote a copy of the global entry into the project — a permanent override shadowing every later global update, disable or removal, produced by an attach that was meant to leave configuration untouched. The project file's own entry is snapshotted before persisting and that is what goes back, which means removing the override when there was nothing there before. Undoing a write is only correct if it restores what that write replaced, and the thing replaced was never the merged view.
1 parent 3597444 commit 37dd23d

2 files changed

Lines changed: 80 additions & 3 deletions

File tree

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

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ import { which as whichBinary } from "@opencode-ai/core/util/which"
6262
import { Instance } from "@/project/instance"
6363
import { Log } from "@/altimate/util/log"
6464
import { MCP, ToolsChanged } from "@/mcp"
65-
import { addMcpToConfig, removeMcpFromConfig, resolveConfigPath } from "@/mcp/config"
65+
import { addMcpToConfig, readMcpEntryFromDisk, removeMcpFromConfig, resolveConfigPath } from "@/mcp/config"
6666
import { Config } from "@/config/config"
6767
import { AltimateApi } from "@/altimate/api/client"
6868
import { DATAMATE_KEY } from "@/altimate/datamate-transport"
@@ -134,6 +134,7 @@ export const syncInternals: {
134134
}
135135
persist?: (name: string, cfg: LocalMcpConfig) => Promise<void>
136136
persistRestore?: (name: string, previous: ExistingEntry | null) => Promise<void>
137+
projectEntry?: () => Promise<ExistingEntry | null>
137138
/** The configured (merged) MCP entry under `name`, or null if none. */
138139
existingEntry?: (name: string) => Promise<ExistingEntry | null>
139140
freshConfig?: () => Promise<{ mcp?: Record<string, ExistingEntry | undefined> }>
@@ -337,6 +338,24 @@ async function freshConfig(): Promise<{ mcp?: Record<string, ExistingEntry | und
337338
return (await Config.get()) as { mcp?: Record<string, ExistingEntry | undefined> }
338339
}
339340

341+
/** The entry in the PROJECT config only, not the merged view.
342+
*
343+
* `existingEntry()` returns the merged value, which may come from global config,
344+
* while `persist()` writes to the project file. Restoring the merged value would
345+
* write a copy of the global entry into the project — a permanent override that
346+
* shadows every later global update, disable or removal, from an attach that was
347+
* meant to leave configuration untouched. */
348+
async function projectEntry(): Promise<ExistingEntry | null> {
349+
if (syncInternals.projectEntry) return syncInternals.projectEntry()
350+
try {
351+
const configPath = await resolveConfigPath(projectRoot())
352+
return ((await readMcpEntryFromDisk(DATAMATE_KEY, configPath)) as ExistingEntry | undefined) ?? null
353+
} catch (err) {
354+
log.warn("could not read the project-level engine entry", { err: String(err) })
355+
return null
356+
}
357+
}
358+
340359
/** Put the config back the way we found it.
341360
*
342361
* `persist()` commits the pin BEFORE the engine is known to be ours, so a
@@ -839,6 +858,9 @@ async function run(): Promise<Outcome> {
839858
log.info("abandoning attach; the binding changed before the engine was installed", { workspaceId })
840859
return { kind: "superseded" }
841860
}
861+
// Snapshot what persist() is about to overwrite — the project file's own
862+
// entry, not the merged view — so a supersede can put back exactly that.
863+
const projectBefore = await projectEntry()
842864
await persist(DATAMATE_KEY, cfg)
843865
await client.add(DATAMATE_KEY, cfg)
844866

@@ -873,7 +895,7 @@ async function run(): Promise<Outcome> {
873895
})
874896
// And the config: `persist()` committed the pin before the engine was known
875897
// to be ours, and bootstrap starts every enabled entry.
876-
await persistRestore(DATAMATE_KEY, entry)
898+
await persistRestore(DATAMATE_KEY, projectBefore)
877899
return { kind: "superseded" }
878900
}
879901

@@ -1072,7 +1094,14 @@ export function ensure(sessionID: string): Promise<Outcome> {
10721094
if (sameWorkspace && !isRepairable(previous!.outcome)) {
10731095
// Re-probe before trusting a cached success — see `engineStillConnected`.
10741096
const boundTo = await attachKeyWorkspace()
1075-
if (!wasServing(previous!.outcome) || !boundTo || (await engineStillOurs(boundTo, entry))) return previous!.task
1097+
const reusable =
1098+
!wasServing(previous!.outcome) || !boundTo || (await engineStillOurs(boundTo, entry))
1099+
// Validating the cached success is itself awaited work — status, config and
1100+
// possibly a version probe — so the binding can move underneath it. This
1101+
// path lives outside `run()` and therefore never had its final check;
1102+
// without one, a confirmed-valid engine for the workspace we just left is
1103+
// returned as the answer for the one we just joined.
1104+
if (reusable && (await attachKeyWorkspace()) === boundTo) return previous!.task
10761105
log.info("cached attach is no longer connected; re-attaching", { sessionID })
10771106
}
10781107
entry.key = key

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

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1475,3 +1475,51 @@ describe("ensure — round 16", () => {
14751475
expect(h.connects).toHaveLength(0)
14761476
})
14771477
})
1478+
1479+
describe("ensure — round 18", () => {
1480+
test("a re-link DURING cached-success validation is not answered with the old workspace", async () => {
1481+
// The memoised-success path does its own awaited validation outside run(),
1482+
// so it never had run()'s final binding check. Status, config and version
1483+
// work all await; a re-link inside them left `boundTo` pointing at the old
1484+
// workspace and returned its cached task — handing the turn A's tools and
1485+
// credentials under binding B.
1486+
let current: CachedBinding | null = binding // 42
1487+
const h = install({
1488+
statuses: [{}, { datamate: { status: "connected" } }, { datamate: { status: "connected" } }, {}, { datamate: { status: "connected" } }],
1489+
tools: { datamate_dbt_build_model: 1 },
1490+
})
1491+
syncInternals.resolveBinding = async () => current
1492+
const first = await ensure("s1")
1493+
expect(first).toMatchObject({ kind: "attached" })
1494+
1495+
// The re-link lands while the cached success is being re-validated.
1496+
syncInternals.versionOf = async () => {
1497+
current = { ...binding, datamateId: 99, datamateName: "other" } as CachedBinding
1498+
return "0.7.0"
1499+
}
1500+
const second = await ensure("s1")
1501+
expect(second, "returned the cached success for a workspace the project had left").not.toBe(first)
1502+
})
1503+
1504+
test("a superseded attach removes the project override rather than copying the global entry", async () => {
1505+
// existingEntry() returns the MERGED value, which may come from global, while
1506+
// persist() writes to the project file. Restoring the merged value would
1507+
// write a copy of the global entry into the project — a permanent override
1508+
// shadowing every later global update, disable or removal.
1509+
let current: CachedBinding | null = binding
1510+
const h = install({
1511+
existing: { type: "local", command: ["datamate", "start-stdio"], enabled: true }, // merged, from global
1512+
statuses: [{ datamate: { status: "connected" } }, { datamate: { status: "connected" } }],
1513+
tools: { datamate_dbt_build_model: 1 },
1514+
})
1515+
syncInternals.resolveBinding = async () => current
1516+
syncInternals.projectEntry = async () => null // the PROJECT file has no entry of its own
1517+
const prevAdd = syncInternals.mcp!.add
1518+
syncInternals.mcp!.add = async (n, c) => {
1519+
await prevAdd(n, c)
1520+
current = { ...binding, datamateId: 99, datamateName: "other" } as CachedBinding
1521+
}
1522+
expect(await ensure("s1")).toEqual({ kind: "superseded" })
1523+
expect(h.restores, "restored something into the project file instead of removing the override").toEqual([null])
1524+
})
1525+
})

0 commit comments

Comments
 (0)