Skip to content

Commit 8da3abe

Browse files
sahrizviclaude
andcommitted
fix(workspace): mirror state on globalThis, bounded flush on signals, no sync promise for a stale link
Codex review of #1344 (gpt-5.6-sol). - `mirrorsInFlight` and the per-block queues were plain module state, while this module is reached through two specifiers (`@/…` from `MemoryStore`, relative from the `run` exit path) — the situation skill-sync already anchors its tables on `globalThis` for. Same anchor here, so the set the flush reads is the set the writer filled whatever the runtime does with module records; test mirrors through one specifier and flushes through the other - SIGINT/SIGTERM exited at once, killing an upload of a block saved that turn. The signal handlers now hold for pending mirrors up to 2s (a second signal is not delayed) before exiting with the same code - The team-memory line is not rendered on a stale outcome: "last known … may since have changed" followed by "syncs to the workspace" contradicted itself - Test: the production enablement check (the same `memoryStatus` the write path and backfill run) fills the memo the line reads — skipping the cache write fails it (checked by mutation); a confirmed-on memo on a stale link shows no line Not changed: `serve`, the TUI and ACP exits still do not drain mirrors (pre-existing, separate entry points); the first turn of a cold one-shot `run` can miss the line while the enablement request is in flight — the `altimate_memory_write` description carries the same guidance for that turn. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012Q51zFUmPg1WwtS5CrGJE6
1 parent 841a59e commit 8da3abe

5 files changed

Lines changed: 103 additions & 9 deletions

File tree

‎packages/opencode/src/altimate/workspace/identity.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,9 @@ async function accountScope(): Promise<AccountScope | null> {
314314
* bind, or the first mirror), so the line appears from the next turn on. */
315315
function renderOptions(outcome: BindingOutcome): RenderOptions {
316316
if (outcome.status !== "bound") return {}
317+
// A stale outcome is "last known … may since have changed": promising that a
318+
// save syncs to that workspace would contradict the line above it.
319+
if (outcome.stale) return {}
317320
return { teamMemory: memoryEnabledCached(outcome.binding) === "enabled" }
318321
}
319322

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

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -520,7 +520,16 @@ async function push(
520520
* memory the user deleted. Two rapid saves race the same way and create
521521
* duplicates. Keyed by scope+id, so unrelated blocks still mirror in parallel.
522522
*/
523-
const blockQueues = new Map<string, Promise<unknown>>()
523+
// Anchored on a process-global, as skill-sync's tables are: this module is reached
524+
// through two module graphs in one process — `MemoryStore` via `@/…`, the `run`
525+
// exit path via a relative specifier — and a runtime that keeps a record per
526+
// specifier would fork plain module state. A flush that saw an empty set while
527+
// the writer's copy held the upload would defeat the #1332 fix silently.
528+
const SYNC_STATE = Symbol.for("altimate.memory-sync.state")
529+
const syncState: { blockQueues: Map<string, Promise<unknown>>; mirrorsInFlight: Set<Promise<void>> } = ((
530+
globalThis as unknown as Record<symbol, typeof syncState | undefined>
531+
)[SYNC_STATE] ??= { blockQueues: new Map(), mirrorsInFlight: new Set() })
532+
const blockQueues = syncState.blockQueues
524533

525534
function serialize<T>(scope: "global" | "project", blockId: string, op: () => Promise<T>): Promise<T> {
526535
const key = `${scope}:${blockId}`
@@ -542,7 +551,7 @@ function serialize<T>(scope: "global" | "project", blockId: string, op: () => Pr
542551
* and the block a teammate was meant to see never leaves the machine (#1332).
543552
* Tracked here so `flushPendingMirrors` can hold the exit for them, the way
544553
* `skill-sync.flushPendingSyncs` holds it for a cold skill sync. */
545-
const mirrorsInFlight = new Set<Promise<void>>()
554+
const mirrorsInFlight = syncState.mirrorsInFlight
546555

547556
/** Hold a task in `mirrorsInFlight` for its lifetime. */
548557
async function tracked(task: Promise<void>): Promise<void> {

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

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1075,14 +1075,29 @@ You are speaking to a non-technical business executive. Follow these rules stric
10751075
// altimate_change end
10761076

10771077
// Register crash handlers to flush the trace on unexpected exit
1078+
// altimate_change start — and hold a signal exit, briefly, for a memory
1079+
// mirror still on the wire: Ctrl-C while the last response streams used to
1080+
// kill the upload of a block saved that turn (#1332). Bounded well below
1081+
// the normal-exit flush, and a second signal is not delayed by the first.
1082+
let signalled = false
1083+
const exitAfterMirrors = (code: number) => {
1084+
if (signalled) return process.exit(code)
1085+
signalled = true
1086+
if (!CoreFlag.ALTIMATE_WORKSPACE) return process.exit(code)
1087+
void import("../../altimate/workspace/memory-sync")
1088+
.then((m) => m.flushPendingMirrors(2_000))
1089+
.catch(() => {})
1090+
.finally(() => process.exit(code))
1091+
}
10781092
const onSigint = () => {
10791093
tracer?.flushSync("Process interrupted")
1080-
process.exit(130)
1094+
exitAfterMirrors(130)
10811095
}
10821096
const onSigterm = () => {
10831097
tracer?.flushSync("Process interrupted")
1084-
process.exit(143)
1098+
exitAfterMirrors(143)
10851099
}
1100+
// altimate_change end
10861101
// altimate_change start — honest rc on fatal abort. beforeExit firing
10871102
// before the run finishes means the event loop drained before the run
10881103
// completed — the prompt/event stream was abandoned (observed: a

‎packages/opencode/test/altimate/workspace/identity-section.test.ts‎

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,32 @@ describe("systemSection", () => {
136136
}
137137
})
138138

139+
test("the production enablement check fills the memo the line reads (codex on #1344)", async () => {
140+
// Not a hand-written cache entry: the sidebar poller's check (`memoryStatus`, the
141+
// same one the write path and the backfill sweep run) asks GET /datamates/ and
142+
// caches a yes; the section reads that. Deleting the cache write would hide the
143+
// line for good, and the previous test would not notice.
144+
const { memoryEnabledForPoller, resetEnablementMemoForTests } = await import("../../../src/altimate/workspace/memory-sync")
145+
globalThis.fetch = (async (input: any) =>
146+
new Response(
147+
JSON.stringify(
148+
String(input).includes("/datamates/") ? { datamates: [{ id: 91, name: "Team", memory_enabled: true }] } : {},
149+
),
150+
{ status: 200, headers: { "content-type": "application/json" } },
151+
)) as unknown as typeof fetch
152+
const binding = { datamateId: 91, datamateName: "Team", repoRemote: null, projectPath: projectDir, linkedAt: Date.now() }
153+
await recordApprovedBinding(projectDir, binding)
154+
resetEnablementMemoForTests()
155+
try {
156+
expect(await inProject(systemSection)).not.toContain("Team memory:")
157+
expect(await memoryEnabledForPoller(binding as never)).toBe("enabled")
158+
resetOutcomeMemoForTests()
159+
expect(await inProject(systemSection)).toContain("Team memory:")
160+
} finally {
161+
resetEnablementMemoForTests()
162+
}
163+
})
164+
139165
test("renders nothing when the workspace pilot is off", async () => {
140166
// A user outside the pilot has no Altimate Workspace to be linked to, and
141167
// must not be told every turn that none is linked and how to link one.
@@ -294,11 +320,20 @@ describe("systemSection", () => {
294320
globalThis.fetch = (async () => {
295321
throw new Error("offline")
296322
}) as unknown as typeof fetch
297-
const out = await inProject(systemSection)
298-
expect(out).toContain("was last known to be linked to Altimate Workspace id 9")
299-
expect(out).toContain('is "Finance"')
300-
expect(out).toContain("could not be re-verified just now")
301-
expect(out).not.toContain("This project is linked to Altimate Workspace id 9")
323+
// Memory was confirmed on earlier; that does not make a sync promise true of a
324+
// binding the server can no longer vouch for. (codex on #1344)
325+
const { memoryEnabledCache, resetEnablementMemoForTests } = await import("../../../src/altimate/workspace/memory-sync")
326+
memoryEnabledCache.set(9, { checkedAt: Date.now() })
327+
try {
328+
const out = await inProject(systemSection)
329+
expect(out).toContain("was last known to be linked to Altimate Workspace id 9")
330+
expect(out).toContain('is "Finance"')
331+
expect(out).toContain("could not be re-verified just now")
332+
expect(out).not.toContain("This project is linked to Altimate Workspace id 9")
333+
expect(out).not.toContain("Team memory:")
334+
} finally {
335+
resetEnablementMemoForTests()
336+
}
302337
})
303338

304339
test("concurrent steps share one resolve (single-flight)", async () => {

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,38 @@ describe("mirrorBlock", () => {
374374
expect(Date.now() - started).toBeLessThan(50)
375375
})
376376

377+
test("a mirror tracked through one module specifier is flushed through another (codex on #1344)", async () => {
378+
// `MemoryStore` reaches this module via `@/…`, the `run` exit path via a relative
379+
// path. Whether or not the runtime keeps one record per specifier, the set the
380+
// flush reads must be the set the writer filled — hence the `globalThis` anchor.
381+
const viaAlias = await import("@/altimate/workspace/memory-sync")
382+
let release!: () => void
383+
const gate = new Promise<void>((r) => (release = r))
384+
const original = globalThis.fetch
385+
globalThis.fetch = (async (input: any, init?: any) => {
386+
await gate
387+
return original(input, init)
388+
}) as unknown as typeof fetch
389+
createResult = [{ id: "mem-alias" }]
390+
let settled = false
391+
const mirror = viaAlias.mirrorBlock(block({ id: "via-alias" })).then(() => (settled = true))
392+
try {
393+
await Bun.sleep(20)
394+
const flush = flushPendingMirrors() // the relative-import copy
395+
let flushed = false
396+
void flush.then(() => (flushed = true))
397+
await Bun.sleep(20)
398+
expect(flushed).toBe(false) // it is holding for the alias copy's mirror
399+
release()
400+
await flush
401+
expect(settled).toBe(true)
402+
} finally {
403+
release()
404+
await mirror
405+
globalThis.fetch = original
406+
}
407+
})
408+
377409
test("flushPendingMirrors gives up after its bound rather than hanging exit forever", async () => {
378410
// Gated, not hung forever: `mirrorsInFlight` is module-level, and a mirror that
379411
// never settles would make every later default-bound flush in this process wait

0 commit comments

Comments
 (0)