Skip to content

Commit 88f267c

Browse files
saravmajesticclaude
andcommitted
feat(workspace): record workspace sync state and publish changes to clients
Every client needed to say when workspace skills and memory were last checked and what changed, but only the TUI sidebar could see part of it ("skills synced Xm ago"), and an IDE extension running `serve` saw nothing. - Add `altimate/workspace/sync-state.ts`: one record per synced entity kind per project (last checked, last changed, count, status, what changed), persisted under the state dir so the TUI main thread and the server worker share it. Diffs are generic over `{id: {label, version}}`, so a new kind records the same metadata. - Skill sync and memory loads record into it from their existing paths; no new timers. The first check is a baseline, not a change. - Publish `altimate.workspace.sync.changed` on the bus, only when a check found a difference or an error state changed. - Add `GET /altimate/workspace/status`, returning the recorded state for the request's workspace. - TUI sidebar shows "memory loaded Xm ago" from the same state. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 1409803 commit 88f267c

10 files changed

Lines changed: 637 additions & 7 deletions

File tree

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import { WorkspaceApi, type ProjectIdentifier } from "./api-client"
2727
import { resolveProjectIdentifier } from "./detect"
2828
import * as MemorySync from "./memory-sync"
2929
import * as SkillSync from "./skill-sync"
30+
import * as SyncState from "./sync-state"
3031
import {
3132
clearLocalBinding,
3233
currentScope,
@@ -59,6 +60,11 @@ export interface StatusReport {
5960
* per-process, so a fresh session has not synced yet even for a project whose
6061
* snapshot is current on disk. Callers must not render it as "never synced". */
6162
skillsSyncedAt: number | null
63+
// altimate_change start — workspace sync state
64+
/** When this project's workspace memory was last loaded, from the shared sync state, or
65+
* null when no load has been recorded for this binding. */
66+
memoryLoadedAt?: number | null
67+
// altimate_change end
6268
}
6369

6470
export interface RefreshReport {
@@ -156,6 +162,7 @@ export async function status(
156162
...(memory === "unreadable" ? { memoryUnreadable: true as const } : {}),
157163
skillsEnabled: SkillSync.isEnabled(),
158164
skillsSyncedAt: await skillsSyncedAt(directory, binding),
165+
memoryLoadedAt: binding ? (SyncState.read(directory, binding.datamateId)?.entities.memory?.lastCheckedAt ?? null) : null,
159166
}
160167
}
161168

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

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1376,7 +1376,7 @@ type LoadOutcome = (
13761376
| { status: "unlinked" }
13771377
| { status: "disabled" }
13781378
| { status: "error" }
1379-
) & { epoch?: string; dir?: string | null }
1379+
) & { epoch?: string; dir?: string | null; /** The workspace the load read, once resolved. */ datamateId?: number }
13801380

13811381
/** Read this project's workspace memory. Pure: it publishes nothing, so a slow
13821382
* load that has been superseded cannot write over a newer result. */
@@ -1403,9 +1403,10 @@ async function loadWorkspaceMemory(directory?: string): Promise<LoadOutcome> {
14031403
vouched = epoch
14041404
if (!stable) return { status: "error", epoch, dir }
14051405
if (!binding) return { status: "unlinked", epoch, dir }
1406+
const datamateId = binding.datamateId
14061407
const enabled = await memoryStatus(binding)
1407-
if (enabled === "error") return { status: "error", epoch, dir }
1408-
if (enabled === "disabled") return { status: "disabled", epoch, dir }
1408+
if (enabled === "error") return { status: "error", epoch, dir, datamateId }
1409+
if (enabled === "disabled") return { status: "disabled", epoch, dir, datamateId }
14091410

14101411
const ownProjectKey = projectKeyFor(binding)
14111412
const ownWorkspace = String(binding.datamateId)
@@ -1441,7 +1442,7 @@ async function loadWorkspaceMemory(directory?: string): Promise<LoadOutcome> {
14411442
if (block.expires && new Date(block.expires) <= new Date()) continue
14421443
blocks.push(block)
14431444
}
1444-
return { status: "loaded", blocks, epoch, dir }
1445+
return { status: "loaded", blocks, epoch, dir, datamateId }
14451446
} catch (err) {
14461447
log.warn("workspace memory load failed", { err: String(err) })
14471448
// Stamped like any other outcome: without an epoch the session would reload (and make
@@ -1461,6 +1462,9 @@ function commitLoad(sessionID: string, state: SessionMemory, outcome: LoadOutcom
14611462
if (outcome.epoch !== epochFor(outcome.dir ?? null)) return
14621463
state.loadedEpoch = outcome.epoch
14631464
state.dir = outcome.dir ?? null
1465+
// altimate_change start — workspace sync state
1466+
recordSyncState(outcome)
1467+
// altimate_change end
14641468
// An error keeps whatever the session had and is not retried every turn (as before).
14651469
if (outcome.status === "error") return
14661470
state.overlay = outcome.status === "loaded" ? outcome.blocks : []
@@ -1469,6 +1473,29 @@ function commitLoad(sessionID: string, state: SessionMemory, outcome: LoadOutcom
14691473
}
14701474
}
14711475

1476+
// altimate_change start — workspace sync state
1477+
/** Record a committed load in the workspace sync state. Memory is loaded per session but
1478+
* recorded per project, so a second session reading the same blocks is not a change.
1479+
* Detached: the load is already committed and nothing waits on status metadata. A load
1480+
* that could not resolve a workspace, or found memory off, records nothing. */
1481+
function recordSyncState(outcome: LoadOutcome): void {
1482+
if (!outcome.dir || outcome.datamateId === undefined) return
1483+
if (outcome.status !== "loaded" && outcome.status !== "error") return
1484+
const { dir, datamateId } = outcome
1485+
const items =
1486+
outcome.status === "loaded"
1487+
? Object.fromEntries(
1488+
outcome.blocks.map((block) => [block.id, { label: blockTitle(block), version: block.updated ?? "" }]),
1489+
)
1490+
: undefined
1491+
void import("./sync-state")
1492+
.then((SyncState) =>
1493+
SyncState.record(dir, datamateId, "memory", items ? { items } : { error: "could not load workspace memory" }),
1494+
)
1495+
.catch((err) => log.warn("could not record the memory sync state", { err: String(err) }))
1496+
}
1497+
// altimate_change end
1498+
14721499
/** A session's cloud overlay. Returns a copy so a caller cannot mutate the
14731500
* cached state in place. */
14741501
export function overlayBlocks(sessionID: string): RemoteMemoryBlock[] {

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

Lines changed: 62 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,8 @@ export interface Manifest {
101101
interface RemoteSummary {
102102
publicId: string
103103
updatedAt: string
104+
/** Display name, for the sync-state change list. Optional: sync never depends on it. */
105+
name?: string
104106
}
105107

106108
/** ``CustomSkillDetail.files`` — ``CustomSkillFileMeta`` is ``{path, size}``. */
@@ -244,6 +246,39 @@ export function describeSyncProblems(result: SyncResult): { title: string; messa
244246
return { title: `${n} workspace skill${n === 1 ? "" : "s"} skipped`, message: lines.join("\n") }
245247
}
246248

249+
// altimate_change start — workspace sync state
250+
/** Record this run in the workspace sync state. `rows` is the list the published snapshot
251+
* describes, or null when the run left the snapshot as it was — the items are then
252+
* unknown to this run and the previous record stands. Imported lazily: the state module
253+
* reaches the bus, which this module must not load on the opted-out path. */
254+
async function recordSyncState(
255+
directory: string,
256+
datamateId: number,
257+
result: SyncResult,
258+
rows: RemoteSummary[] | null,
259+
dropped: Set<string>,
260+
): Promise<void> {
261+
const problem = describeSyncProblems(result)
262+
const items = rows
263+
? Object.fromEntries(
264+
rows
265+
.filter((row) => !dropped.has(row.publicId))
266+
.map((row) => [row.publicId, { label: displayId(row.name ?? row.publicId), version: row.updatedAt }]),
267+
)
268+
: undefined
269+
try {
270+
const SyncState = await import("./sync-state")
271+
await SyncState.record(directory, datamateId, "skills", {
272+
...(items ? { items } : {}),
273+
...(problem ? { error: `${problem.title}: ${problem.message.split("\n").join("; ")}` } : {}),
274+
})
275+
} catch (err) {
276+
// Status metadata: never the reason a sync fails.
277+
log.warn("could not record the skill sync state", { err: String(err) })
278+
}
279+
}
280+
// altimate_change end
281+
247282
/** A fixed, user-facing reason for a skill that failed to sync. The raw error
248283
* can carry request URLs, server text or local paths — diagnostics for the
249284
* log, not for a toast. */
@@ -746,10 +781,14 @@ function parsePage(
746781
const rows: RemoteSummary[] = []
747782
for (const row of p.items) {
748783
if (!row || typeof row !== "object") return null
749-
const r = row as { public_id?: unknown; updated_at?: unknown }
784+
const r = row as { public_id?: unknown; updated_at?: unknown; name?: unknown }
750785
if (typeof r.public_id !== "string" || !r.public_id) return null
751786
if (typeof r.updated_at !== "string" || !r.updated_at) return null
752-
rows.push({ publicId: r.public_id, updatedAt: r.updated_at })
787+
rows.push({
788+
publicId: r.public_id,
789+
updatedAt: r.updated_at,
790+
...(typeof r.name === "string" && r.name ? { name: r.name } : {}),
791+
})
753792
}
754793
return { rows, pages: rawPages, total }
755794
}
@@ -1109,6 +1148,15 @@ export async function syncSkills(directory: string): Promise<SyncResult> {
11091148
// Set once the workspace's list has actually been read. Only then has this
11101149
// project been "checked", and only then should the poll interval start.
11111150
let sawRemote = false
1151+
// altimate_change start — workspace sync state
1152+
// What the sync-state record needs: the workspace checked, the list it read, the skills
1153+
// that list named but this run could not install (and had no previous copy of), and
1154+
// whether the run left a snapshot describing that list.
1155+
let checkedDatamateId: number | undefined
1156+
let remoteRows: RemoteSummary[] | null = null
1157+
const dropped = new Set<string>()
1158+
let published = false
1159+
// altimate_change end
11121160
const run = (async () => {
11131161
// Checked BEFORE the binding: `resolveBinding` needs credentials too, so a
11141162
// disconnected client would otherwise return on a null binding and never
@@ -1212,6 +1260,7 @@ export async function syncSkills(directory: string): Promise<SyncResult> {
12121260
return
12131261
}
12141262
const binding = outcome.binding
1263+
checkedDatamateId = binding.datamateId
12151264

12161265
// Refuse to touch a directory we did not create. Everything below either
12171266
// deletes this tree or replaces it wholesale, so without this a user's own
@@ -1279,6 +1328,7 @@ export async function syncSkills(directory: string): Promise<SyncResult> {
12791328
return
12801329
}
12811330
sawRemote = true
1331+
remoteRows = remote
12821332
syncedFor.set(canon, accountKeyOf(creds.altimateInstanceName, creds.altimateUrl, account))
12831333
// The workspace has skills now, even if installing them fails below.
12841334
if (remote.length > 0) await clearEmptyRecordFor(canon, currentEmptyKey)
@@ -1289,6 +1339,7 @@ export async function syncSkills(directory: string): Promise<SyncResult> {
12891339
// live by then — another process can swap a partial snapshot in
12901340
// between, and the marker would vouch for a sync this run never made.
12911341
validated = manifest
1342+
published = true
12921343
return
12931344
}
12941345

@@ -1302,6 +1353,7 @@ export async function syncSkills(directory: string): Promise<SyncResult> {
13021353
if (written && (after?.status !== "bound" || after.binding.datamateId !== binding.datamateId))
13031354
await withdrawEmptyRecord(canon, written)
13041355
changed = true
1356+
published = true
13051357
log.info("workspace has no custom skills; removed the local snapshot")
13061358
return
13071359
}
@@ -1354,6 +1406,7 @@ export async function syncSkills(directory: string): Promise<SyncResult> {
13541406
failed = true
13551407
log.warn("skipping a workspace skill with an unusable id", { skill: summary.publicId })
13561408
skippedSkills.push({ skill: displayId(summary.publicId), reason: "its id is not usable as a folder name" })
1409+
dropped.add(summary.publicId)
13571410
continue
13581411
}
13591412
try {
@@ -1435,6 +1488,7 @@ export async function syncSkills(directory: string): Promise<SyncResult> {
14351488
}
14361489
if (!carried) {
14371490
await fs.rm(path.join(staging, summary.publicId), { recursive: true, force: true }).catch(() => {})
1491+
dropped.add(summary.publicId)
14381492
}
14391493
log.warn("skipping a workspace skill; the rest of the snapshot still publishes", {
14401494
skill: summary.publicId,
@@ -1516,6 +1570,7 @@ export async function syncSkills(directory: string): Promise<SyncResult> {
15161570
await fs.rm(retired, { recursive: true, force: true }).catch(() => {})
15171571
await clearEmptyRecordFor(canon, currentEmptyKey)
15181572
changed = true
1573+
published = true
15191574
log.info("workspace skills synced", {
15201575
datamateId: binding.datamateId,
15211576
skills: remote.length,
@@ -1566,7 +1621,11 @@ export async function syncSkills(directory: string): Promise<SyncResult> {
15661621
// too — otherwise a problem it fixed would stay latched, and its return
15671622
// would never be announced.
15681623
if (skippedSkills.length === 0 && !syncError) store.announced.delete(canon)
1569-
return { changed, skipped: skippedSkills, error: syncError }
1624+
const result: SyncResult = { changed, skipped: skippedSkills, error: syncError }
1625+
// altimate_change start — workspace sync state
1626+
if (checkedDatamateId !== undefined) await recordSyncState(canon, checkedDatamateId, result, published ? remoteRows : null, dropped)
1627+
// altimate_change end
1628+
return result
15701629
})()
15711630
inFlight.set(canon, settled)
15721631
try {

0 commit comments

Comments
 (0)