Skip to content

Commit 55bf62b

Browse files
anandgupta42claude
andcommitted
fix: reload connection config only while the registry is empty
The fingerprint-based reload replaced the process-global config map when the project directory or a file changed, which could close another project's connectors and drop in-memory credentials of a keyring-less `warehouse_add`. Replace it with a structural rule: re-read the sources only while the registry holds zero connections (the case the `warehouse_list` hint addresses). Once any connection is loaded nothing is replaced or closed, so edits to an existing file take effect after a restart. `setConfigs()` injections are not reloaded. The hint says so. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent f27bdc6 commit 55bf62b

3 files changed

Lines changed: 39 additions & 96 deletions

File tree

‎packages/opencode/src/altimate/native/connections/registry.ts‎

Lines changed: 8 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -221,73 +221,22 @@ export function load(): void {
221221

222222
if (configs.has(SCRATCH_NAME)) Log.Default.warn(SCRATCH_NAME_CONFLICT)
223223
loaded = true
224-
// altimate_change start
225-
injected = false
226-
loadedSignature = sourceSignature()
227-
// altimate_change end
228-
}
229-
230-
// altimate_change start — pick up config edited after the first load (e.g. an agent following the
231-
// `warehouse_list` hint) without a restart. Stat-based: two stats plus the env scan per access.
232-
/** True once configs were injected with setConfigs(); they have no on-disk source to compare. */
233-
let injected = false
234-
/** Fingerprint of the sources behind the last load. */
235-
let loadedSignature = ""
236-
/** Bumped whenever a refresh changes a connection's config, so an in-flight connect can tell it is obsolete. */
237-
let configGeneration = 0
238-
/**
239-
* Connections added in this process: the full config (with credentials the sanitized file no longer holds) and
240-
* the sanitized form that was written, so a later edit of the file is not overridden by the older in-memory copy.
241-
*/
242-
const sessionAdded = new Map<string, { full: ConnectionConfig; written: ConnectionConfig }>()
243-
244-
function statSignature(filePath: string): string {
245-
try {
246-
const st = fs.statSync(filePath)
247-
return `${filePath}:${st.mtimeMs}:${st.size}`
248-
} catch {
249-
return `${filePath}:-`
250-
}
251-
}
252-
253-
function sourceSignature(): string {
254-
const env = Object.entries(process.env)
255-
.filter(([key, value]) => key.startsWith(CONN_ENV_PREFIX) && value)
256-
.sort(([a], [b]) => a.localeCompare(b))
257-
.map(([key, value]) => `${key}=${value}`)
258-
return [statSignature(globalConfigPath()), statSignature(localConfigPath()), ...env].join("\n")
259-
}
260-
261-
/** Re-read the sources, keeping this process's own added connections and dropping stale connectors. */
262-
function refresh(): void {
263-
const previous = new Map(configs)
264-
load()
265-
for (const [name, { full, written }] of sessionAdded) {
266-
// Only while the file still holds what add() wrote: a project file or env var defining the name outranks it,
267-
// and a later edit of the global entry must win over the older in-memory copy.
268-
const overridden = Object.hasOwn(loadFromFile(localConfigPath()), name) || Object.hasOwn(loadFromEnv(), name)
269-
if (!overridden && JSON.stringify(configs.get(name)) === JSON.stringify(written)) configs.set(name, full)
270-
else if (!overridden) sessionAdded.delete(name)
271-
}
272-
for (const name of new Set([...previous.keys(), ...configs.keys()])) {
273-
if (JSON.stringify(configs.get(name)) !== JSON.stringify(previous.get(name))) configGeneration++
274-
}
275-
for (const [name, connector] of [...connectors]) {
276-
if (JSON.stringify(configs.get(name)) === JSON.stringify(previous.get(name))) continue
277-
connectors.delete(name)
278-
connector.close().catch(() => {})
279-
}
280224
}
281-
// altimate_change end
282225

283226
/** Ensure configs are loaded. */
284227
function ensureLoaded(): void {
285228
if (!loaded) load()
286-
// altimate_change start
287-
else if (!injected && sourceSignature() !== loadedSignature) refresh()
229+
// altimate_change start — the registry latches on first load, so a connections file created after an empty
230+
// answer (the `warehouse_list` hint) was never seen. Re-read only while nothing is loaded: there is no state to
231+
// replace or close, and a populated registry never changes under a running session.
232+
else if (configs.size === 0 && !injected) load()
288233
// altimate_change end
289234
}
290235

236+
// altimate_change start — set by setConfigs() (tests): an injected empty registry is not a stale one
237+
let injected = false
238+
// altimate_change end
239+
291240
// ---------------------------------------------------------------------------
292241
// Driver factory
293242
// ---------------------------------------------------------------------------
@@ -610,9 +559,6 @@ export async function get(name: string): Promise<Connector> {
610559
})
611560
} catch {}
612561
// altimate_change end
613-
// altimate_change start
614-
const generation = configGeneration
615-
// altimate_change end
616562
const promise = (async () => {
617563
try {
618564
const connector = await createConnector(name, config)
@@ -623,13 +569,6 @@ export async function get(name: string): Promise<Connector> {
623569
closeTunnel(name)
624570
throw connectErr
625571
}
626-
// altimate_change start — the config changed while this connected; caching it would pin the old target
627-
if (generation !== configGeneration && JSON.stringify(configs.get(name)) !== JSON.stringify(config)) {
628-
await connector.close().catch(() => {})
629-
closeTunnel(name)
630-
throw new Error(`Connection "${name}" changed while it was connecting; retry.`)
631-
}
632-
// altimate_change end
633572
connectors.set(name, connector)
634573
fileLog("INFO", "warehouse-connect", "connected", { name, type: config.type, auth: authMethod, duration_ms: Date.now() - startTime })
635574
try {
@@ -818,10 +757,6 @@ export async function add(
818757
// session can connect even when keytar is unavailable. Only the disk
819758
// file uses the sanitized version (credentials stripped).
820759
configs.set(name, normalized)
821-
// altimate_change start — our own write is not an external edit, and the credentials stay in memory
822-
sessionAdded.set(name, { full: normalized, written: sanitized })
823-
loadedSignature = sourceSignature()
824-
// altimate_change end
825760

826761
// Clear cached connector
827762
const cached = connectors.get(name)
@@ -881,10 +816,6 @@ export async function remove(name: string): Promise<{ success: boolean; error?:
881816

882817
// Remove from in-memory
883818
configs.delete(name)
884-
// altimate_change start
885-
sessionAdded.delete(name)
886-
loadedSignature = sourceSignature()
887-
// altimate_change end
888819

889820
// altimate_change start — remove its secrets from the OS credential store too. Entries are keyed by name
890821
// only, so they are kept while this project's config or an env var still defines a connection by that name.
@@ -945,7 +876,6 @@ export function reset(): void {
945876
censusSent = false
946877
// altimate_change start
947878
injected = false
948-
sessionAdded.clear()
949879
// altimate_change end
950880
}
951881

@@ -960,6 +890,5 @@ export function setConfigs(newConfigs: Record<string, ConnectionConfig>): void {
960890
loaded = true
961891
// altimate_change start
962892
injected = true
963-
sessionAdded.clear()
964893
// altimate_change end
965894
}

‎packages/opencode/src/altimate/tools/warehouse-list.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ export function noConnectionsMessage(): string {
2020
` 2. ${localConfigPath()} (this project)`,
2121
` 3. ${CONN_ENV_PREFIX}<NAME> environment variables, each holding one connection's config as JSON`,
2222
"",
23-
"Changes to these sources are picked up on the next call; no restart is needed. Example connections.json:",
23+
"After adding the first connection, call warehouse_list again. Edits to an existing connections.json take effect after a restart. Example connections.json:",
2424
"{",
2525
' "my-db": { "type": "postgres", "host": "localhost", "port": 5432, "database": "mydb", "user": "user", "password": "pass" }',
2626
"}",

‎packages/opencode/test/altimate/warehouse-list-hint.test.ts‎

Lines changed: 30 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ describe("warehouse_list no-connections hint", () => {
8585
expect(Registry.getConfig("late-db")?.type).toBe("postgres")
8686
})
8787

88-
test("an env var set after an empty answer is picked up, and removing a file drops its connection", async () => {
88+
test("an env var set after an empty answer is picked up", async () => {
8989
const tool = await initTool(WarehouseListTool)
9090
const ctx = toolCtx()
9191
await tool.execute({}, ctx)
@@ -95,27 +95,41 @@ describe("warehouse_list no-connections hint", () => {
9595
} finally {
9696
delete process.env.ALTIMATE_CODE_CONN_ENVLATE
9797
}
98-
expect((await tool.execute({}, ctx)).output).toContain("No warehouse connections")
9998
})
10099

101-
test("setConfigs-injected connections are not discarded by the staleness check", () => {
102-
Registry.setConfigs({ injected: { type: "postgres" } })
103-
expect(Registry.names()).toEqual(["injected"])
104-
expect(Registry.names()).toEqual(["injected"])
100+
test("with a connection loaded, editing the file does not replace the configs", () => {
101+
const named = Registry.localConfigPath()
102+
fs.mkdirSync(path.dirname(named), { recursive: true })
103+
fs.writeFileSync(named, JSON.stringify({ "db-a": { type: "postgres", host: "old" } }))
104+
expect(Registry.getConfig("db-a")?.host).toBe("old")
105+
fs.writeFileSync(named, JSON.stringify({ "db-a": { type: "postgres", host: "new" }, "db-b": { type: "postgres" } }))
106+
expect(Registry.getConfig("db-a")?.host).toBe("old")
107+
expect(Registry.names()).toEqual(["db-a"])
105108
})
106109

107-
test("a connection added in-process yields to a later edit of its global entry", async () => {
108-
const added = await Registry.add("edit-me", { type: "postgres", host: "old-host", database: "d" })
109-
expect(added.success).toBe(true)
110+
test("a populated registry is not clobbered when the working project changes", () => {
111+
const named = Registry.localConfigPath()
112+
fs.mkdirSync(path.dirname(named), { recursive: true })
113+
fs.writeFileSync(named, JSON.stringify({ "proj-a": { type: "postgres" } }))
114+
expect(Registry.names()).toEqual(["proj-a"])
115+
116+
const other = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "whl-hint-b-")))
110117
try {
111-
expect(Registry.getConfig("edit-me")?.host).toBe("old-host")
112-
const globalPath = Registry.globalConfigPath()
113-
const onDisk = JSON.parse(fs.readFileSync(globalPath, "utf-8"))
114-
onDisk["edit-me"].host = "new-host"
115-
fs.writeFileSync(globalPath, JSON.stringify(onDisk))
116-
expect(Registry.getConfig("edit-me")?.host).toBe("new-host")
118+
fs.mkdirSync(path.join(other, ".altimate-code"))
119+
fs.writeFileSync(
120+
path.join(other, ".altimate-code", "connections.json"),
121+
JSON.stringify({ "proj-b": { type: "postgres" } }),
122+
)
123+
process.chdir(other)
124+
expect(Registry.names()).toEqual(["proj-a"])
117125
} finally {
118-
await Registry.remove("edit-me")
126+
process.chdir(project)
127+
fs.rmSync(other, { recursive: true, force: true })
119128
}
120129
})
130+
131+
test("setConfigs-injected connections are kept", () => {
132+
Registry.setConfigs({ injected: { type: "postgres" } })
133+
expect(Registry.names()).toEqual(["injected"])
134+
})
121135
})

0 commit comments

Comments
 (0)