loop: ocm-session-move completed after 7 iterations

This commit is contained in:
Chris Scott committed 2026-07-08 13:51:36 -04:00
1 parent 54323267f5
commit ac8ab89b4a
11 files changed
+694 -60

No files matched your search

+6 -2
View File
@@ -35,7 +35,7 @@ Add the package to your OpenCode config and OpenCode will fetch it on next start
// ~/.config/opencode/opencode.json
{
"$schema": "https://opencode.ai/config.json",
"plugin": ["@opencode-manager/ocm-cli"]
"plugin": ["@opencode-manager/ocm-cli", "@opencode-manager/ocm-cli/tui"]
}
```
@@ -51,7 +51,7 @@ If `~/.local/bin` is not on your PATH, the message will tell you. Add this to yo
export PATH="$HOME/.local/bin:$PATH"
```
The plugin itself is a no-op — it does not register tools, commands, or hooks. Its only side effect is the bin symlink, so all real work happens through the `ocm` CLI.
The default plugin entry only installs the bin symlink. The `./tui` entry registers `/ocm-move`, a TUI command that keeps the local session and copies the active session to the Manager after pushing the current repo state. Run it from inside a local OpenCode session after `ocm login` and after the repo exists on the Manager (`ocm push --create` if needed).
### Option B — global package manager install
@@ -129,6 +129,10 @@ The child takes over the terminal (`stdio: inherit`); closing the TUI exits `ocm
`ocm pull` uses a fast git bundle + working-tree patch by default to sync the matching Manager repo over `$PWD`. Pass `--full` to use the legacy tarball mirror. If the fast path fails, `ocm` prompts before reverting to the tarball mirror (and proceeds automatically when there is no TTY to prompt).
### TUI `/ocm-move`
When the TUI plugin entry is installed, `/ocm-move` is available in local OpenCode sessions. It checks that the matching Manager repo has not diverged, pushes the local git state with the fast bundle + working-tree patch path, exports the active session history from the local OpenCode `/sync` API, rewrites local repo directories to the Manager repo directory, and replays the session through `/api/opencode-proxy/sync/replay`. The local session is retained.
- `--force` skips the dirty-working-tree check on `pull` and the safety bail on `push`.
- `--create` (on `push`) creates a new Manager repo when no `origin` match is found.
- `--yes` skips the interactive create confirmation.
+14
View File
@@ -73,6 +73,20 @@ import ocm from '@opencode-manager/ocm-cli'
export default [ocm]
```
The package also exposes an OpenCode TUI plugin at
`@opencode-manager/ocm-cli/tui`. It registers `/ocm-move`, which keeps the
local session and copies the active session to the Manager after pushing the
current repo state. Use it from inside an OpenCode session after `ocm login`
and after the repo already exists on the Manager (`ocm push --create` if
needed).
```ts
import ocm from '@opencode-manager/ocm-cli'
import ocmTui from '@opencode-manager/ocm-cli/tui'
export default [ocm, ocmTui]
```
## Requirements
- `opencode` available on `PATH`
+3 -33
View File
@@ -9,6 +9,7 @@ import { createProgressReporter } from '../src/progress.js'
import { getBranchName, getOriginUrl } from '../src/local-repo.js'
import { resolveOpenCodeProjectId } from '@opencode-manager/shared/project-id'
import { resolveTarget } from '../src/resolve-target.js'
import { type ManagerRepo, fetchRepos, toRemoteRepoSummaries } from '../src/manager-repos.js'
import packageJson from '../package.json' with { type: 'json' }
const VERSION = packageJson.version
@@ -30,16 +31,6 @@ Usage:
ocm --help Show this help
`
interface ManagerRepo {
repoId: number
name: string
branch: string | null
cloneStatus: string
directory: string
projectId?: string | null
extra: { repoId: number; localPath: string; fullPath: string }
}
function die(msg: string, code = 1): never {
process.stderr.write(`ocm: ${msg}\n`)
process.exit(code)
@@ -124,17 +115,6 @@ function requireToken(state: OcmState): string {
return token
}
async function fetchRepos(managerUrl: string, token: string): Promise<ManagerRepo[]> {
const res = await fetch(`${managerUrl}/api/internal/opencode-workspaces`, {
headers: { Authorization: `Bearer ${token}` },
})
if (!res.ok) {
throw new Error(`manager responded ${res.status} ${res.statusText}`)
}
const data = (await res.json()) as { workspaces: ManagerRepo[] }
return data.workspaces
}
function attach(managerUrl: string, token: string, repo: ManagerRepo): never {
const proxyUrl = `${managerUrl}/api/opencode-proxy`
const args = [
@@ -364,12 +344,7 @@ export async function cmdPush(args: string[]): Promise<void> {
const api = new ManagerApi(state.managerUrl, token)
const repos = await fetchRepos(state.managerUrl, token)
const remotes: RemoteRepoSummary[] = repos.map((r) => ({
repoId: r.repoId,
name: r.name,
projectId: r.projectId ?? null,
branch: r.branch,
}))
const remotes: RemoteRepoSummary[] = toRemoteRepoSummaries(repos)
const plan = await prepareMirror(process.cwd(), remotes)
@@ -447,12 +422,7 @@ async function cmdPull(args: string[]): Promise<void> {
const api = new ManagerApi(state.managerUrl, token)
const repos = await fetchRepos(state.managerUrl, token)
const remotes: RemoteRepoSummary[] = repos.map((r) => ({
repoId: r.repoId,
name: r.name,
projectId: r.projectId ?? null,
branch: r.branch,
}))
const remotes: RemoteRepoSummary[] = toRemoteRepoSummaries(repos)
const plan = await prepareMirror(process.cwd(), remotes)
+3
View File
@@ -13,6 +13,9 @@
"exports": {
".": {
"import": "./dist/plugin.js"
},
"./tui": {
"import": "./dist/tui.js"
}
},
"bin": {
+15 -25
View File
@@ -6,37 +6,27 @@ const dist = join(root, 'dist')
rmSync(dist, { recursive: true, force: true })
console.log('Bundling ocm CLI...')
const cliResult = await Bun.build({
entrypoints: [join(root, 'bin', 'ocm.ts')],
outdir: dist,
target: 'node',
format: 'esm',
naming: { entry: 'ocm.js' },
})
async function bundleEntry(label: string, entrypoint: string, outputName: string): Promise<void> {
console.log(`Bundling ${label}...`)
const result = await Bun.build({
entrypoints: [join(root, entrypoint)],
outdir: dist,
target: 'node',
format: 'esm',
naming: { entry: outputName },
})
if (!cliResult.success) {
for (const log of cliResult.logs) {
if (result.success) return
for (const log of result.logs) {
console.error(log)
}
process.exit(1)
}
console.log('Bundling opencode plugin entry...')
const pluginResult = await Bun.build({
entrypoints: [join(root, 'src', 'plugin.ts')],
outdir: dist,
target: 'node',
format: 'esm',
naming: { entry: 'plugin.js' },
})
if (!pluginResult.success) {
for (const log of pluginResult.logs) {
console.error(log)
}
process.exit(1)
}
await bundleEntry('ocm CLI', join('bin', 'ocm.ts'), 'ocm.js')
await bundleEntry('opencode plugin entry', join('src', 'plugin.ts'), 'plugin.js')
await bundleEntry('TUI plugin entry', join('src', 'tui-plugin.ts'), 'tui.js')
const ocmJsPath = join(dist, 'ocm.js')
const ocmJsContent = readFileSync(ocmJsPath, 'utf-8')
+31
View File
@@ -0,0 +1,31 @@
import type { RemoteRepoSummary } from './mirror.js'
export interface ManagerRepo {
repoId: number
name: string
branch: string | null
cloneStatus: string
directory: string
projectId?: string | null
extra: { repoId: number; localPath: string; fullPath: string }
}
export async function fetchRepos(managerUrl: string, token: string): Promise<ManagerRepo[]> {
const res = await fetch(`${managerUrl}/api/internal/opencode-workspaces`, {
headers: { Authorization: `Bearer ${token}` },
})
if (!res.ok) {
throw new Error(`manager responded ${res.status} ${res.statusText}`)
}
const data = (await res.json()) as { workspaces: ManagerRepo[] }
return data.workspaces
}
export function toRemoteRepoSummaries(repos: ManagerRepo[]): RemoteRepoSummary[] {
return repos.map((r) => ({
repoId: r.repoId,
name: r.name,
projectId: r.projectId ?? null,
branch: r.branch,
}))
}
+19
View File
@@ -0,0 +1,19 @@
import type { ReplayEvent } from './session-move.js'
export function createManagerReplay(managerUrl: string, token: string) {
return async (remoteDirectory: string, events: ReplayEvent[]): Promise<{ sessionID: string }> => {
const url = `${managerUrl}/api/opencode-proxy/sync/replay?directory=${encodeURIComponent(remoteDirectory)}`
const res = await fetch(url, {
method: 'POST',
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
body: JSON.stringify({ directory: remoteDirectory, events }),
})
if (!res.ok) {
const text = await res.text().catch(() => '')
throw new Error(`replay failed (${res.status}): ${text.slice(0, 200)}`)
}
return (await res.json()) as { sessionID: string }
}
}
+153
View File
@@ -0,0 +1,153 @@
export type HistoryEventRow = { id: string; aggregate_id: string; seq: number; type: string; data: Record<string, unknown> }
export type ReplayEvent = { id: string; aggregateID: string; seq: number; type: string; data: Record<string, unknown> }
export type CollectResult =
| { kind: 'ok'; events: ReplayEvent[] }
| { kind: 'empty' }
| { kind: 'gap'; missingSeq: number }
export type RewriteContext = { localRoot: string; remoteRoot: string }
export function collectSessionEvents(rows: HistoryEventRow[], sessionID: string): CollectResult {
const filtered = rows.filter((r) => r.aggregate_id === sessionID)
if (filtered.length === 0) return { kind: 'empty' }
const sorted = [...filtered].sort((a, b) => a.seq - b.seq)
if (sorted[0]!.seq !== 0) return { kind: 'gap', missingSeq: 0 }
for (let i = 1; i < sorted.length; i++) {
if (sorted[i]!.seq !== sorted[i - 1]!.seq + 1) {
return { kind: 'gap', missingSeq: sorted[i - 1]!.seq + 1 }
}
}
const events: ReplayEvent[] = sorted.map((r) => ({
id: r.id,
aggregateID: r.aggregate_id,
seq: r.seq,
type: r.type,
data: r.data,
}))
return { kind: 'ok', events }
}
/**
* Rewrites collected replay events for replay on a remote Manager server.
*
* Coercion rule for `data.timestamp` matches the prior implementation in
* commit 686c820d (`coerceReplayBodyTimestamps`): ISO 8601 string timestamps
* are converted to epoch milliseconds via `Date.parse`; already-numeric values
* are left untouched.
*/
export function rewriteEventsForRemote(events: ReplayEvent[], ctx: RewriteContext): ReplayEvent[] {
return events.map((event) => {
const data = deepClone(event.data)
if (shouldRewriteDirectory(event.type)) {
rewriteDirectory(data, 'info', ctx)
stripWorkspaceID(data, 'info')
}
if (isMovedEvent(event.type)) {
rewriteDirectory(data, 'location', ctx)
stripWorkspaceID(data, 'location')
}
coerceTimestamp(data)
return { ...event, data }
})
}
function shouldRewriteDirectory(type: string): boolean {
return type.startsWith('session.created') || type.startsWith('session.updated')
}
function isMovedEvent(type: string): boolean {
return type.startsWith('session.next.moved')
}
function rewriteDirectory(
data: Record<string, unknown>,
key: 'info' | 'location',
ctx: RewriteContext,
): void {
const container = data[key]
if (!container || typeof container !== 'object') return
const obj = container as Record<string, unknown>
const dir = obj.directory
if (typeof dir !== 'string') return
if (dir === ctx.localRoot) {
obj.directory = ctx.remoteRoot
} else if (dir.startsWith(ctx.localRoot + '/')) {
obj.directory = ctx.remoteRoot + dir.slice(ctx.localRoot.length)
}
}
function stripWorkspaceID(data: Record<string, unknown>, key: 'info' | 'location'): void {
const container = data[key]
if (!container || typeof container !== 'object') return
const obj = container as Record<string, unknown>
delete obj.workspaceID
}
/** Per commit 686c820d: coerce `data.timestamp` from ISO string to epoch ms. */
function coerceTimestamp(data: Record<string, unknown>): void {
const ts = data.timestamp
if (typeof ts !== 'string') return
const epoch = Date.parse(ts)
if (!Number.isFinite(epoch)) return
data.timestamp = epoch
}
export type TransferDeps = {
fetchLocalHistory: () => Promise<HistoryEventRow[]>
replayEvents: (remoteDirectory: string, events: ReplayEvent[]) => Promise<{ sessionID: string }>
}
export type TransferInput = { sessionID: string; localRoot: string; remoteDirectory: string }
export type TransferResult =
| { kind: 'moved'; sessionID: string; replayedEvents: number }
| { kind: 'not-found' }
| { kind: 'corrupt-history'; missingSeq: number }
| { kind: 'replay-failed'; message: string }
export function planReplayBatches(events: ReplayEvent[], batchSize = 10): ReplayEvent[][] {
const batches: ReplayEvent[][] = []
for (let i = 0; i < events.length; i += batchSize) {
batches.push(events.slice(i, i + batchSize))
}
return batches
}
export async function transferSession(input: TransferInput, deps: TransferDeps): Promise<TransferResult> {
const rows = await deps.fetchLocalHistory()
const collect = collectSessionEvents(rows, input.sessionID)
if (collect.kind === 'empty') return { kind: 'not-found' }
if (collect.kind === 'gap') return { kind: 'corrupt-history', missingSeq: collect.missingSeq }
const rewritten = rewriteEventsForRemote(collect.events, {
localRoot: input.localRoot,
remoteRoot: input.remoteDirectory,
})
const batches = planReplayBatches(rewritten)
let replayed = 0
for (const batch of batches) {
try {
await deps.replayEvents(input.remoteDirectory, batch)
replayed += batch.length
} catch (err) {
return { kind: 'replay-failed', message: err instanceof Error ? err.message : String(err) }
}
}
return { kind: 'moved', sessionID: input.sessionID, replayedEvents: replayed }
}
function deepClone<T>(obj: T): T {
return JSON.parse(JSON.stringify(obj))
}
+119
View File
@@ -0,0 +1,119 @@
import type { TuiPluginApi, TuiPluginModule } from './tui-types.js'
import { readState } from './state.js'
import { getToken } from './keychain.js'
import { fetchRepos, toRemoteRepoSummaries } from './manager-repos.js'
import { ManagerApi, ManagerApiError } from './manager-api.js'
import { prepareMirror, checkPushDivergence, mirrorUpFast } from './mirror.js'
import { transferSession, type HistoryEventRow } from './session-move.js'
import { createManagerReplay } from './remote-replay.js'
const tui = async (api: TuiPluginApi): Promise<void> => {
api.keymap.registerLayer({
commands: [
{
name: 'ocm.session.move',
title: 'Move session to Manager',
description: 'Push repo state and move this session to OpenCode Manager',
slashName: 'ocm-move',
run: () => runSessionMove(api),
},
],
})
}
async function runSessionMove(api: TuiPluginApi): Promise<void> {
try {
const current = api.route.current
if (current.name !== 'session' || !current.params) {
api.ui.toast({ variant: 'error', message: 'Not in a session' })
return
}
const sessionID = String(current.params.sessionID)
const session = api.state.session.get(sessionID)
if (!session?.directory) {
api.ui.toast({ variant: 'error', message: 'Session has no directory' })
return
}
const state = readState()
if (!state?.managerUrl) {
api.ui.toast({ variant: 'error', message: 'No manager configured. Run `ocm login <url>` first.' })
return
}
const token = getToken(state.managerUrl)
if (!token) {
api.ui.toast({ variant: 'error', message: `No token in Keychain. Run \`ocm login ${state.managerUrl}\`.` })
return
}
const repos = await fetchRepos(state.managerUrl, token)
const plan = await prepareMirror(session.directory, toRemoteRepoSummaries(repos))
if (plan.matched.length === 0) {
api.ui.toast({ variant: 'error', message: 'No matching Manager repo; run `ocm push --create` first' })
return
}
if (plan.matched.length > 1) {
const names = plan.matched.map((r) => `${r.name} (id=${r.repoId})`).join(', ')
api.ui.toast({ variant: 'error', message: `Multiple Manager repos match: ${names}` })
return
}
const matched = plan.matched[0]!
const repoId = matched.repoId
const remoteRepo = repos.find((r) => r.repoId === repoId)
const remoteDirectory = remoteRepo!.directory
const managerApi = new ManagerApi(state.managerUrl, token)
try {
const divergence = await checkPushDivergence(plan.repoRoot, managerApi, repoId)
if (divergence.diverged || divergence.serverDirty) {
api.ui.toast({ variant: 'error', title: 'Remote has diverged', message: 'Remote has diverged; resolve with `ocm push --force` first' })
return
}
} catch (error) {
if (!(error instanceof ManagerApiError && error.status === 404)) throw error
}
api.ui.toast({ message: 'Pushing repo state…' })
await mirrorUpFast(plan, { api: managerApi, force: false })
if (!api.client.sync) {
api.ui.toast({ variant: 'error', message: 'Local opencode is too old for session move (needs /sync API)' })
return
}
const raw = await api.client.sync.history.list({ body: {} })
const rows: HistoryEventRow[] = Array.isArray(raw)
? (raw as HistoryEventRow[])
: ((raw as { data?: HistoryEventRow[] })?.data ?? [])
const result = await transferSession(
{ sessionID, localRoot: plan.repoRoot, remoteDirectory },
{ fetchLocalHistory: async () => rows, replayEvents: createManagerReplay(state.managerUrl, token) },
)
switch (result.kind) {
case 'moved':
api.ui.toast({ variant: 'success', message: `Session moved to Manager (${result.replayedEvents} events). Local copy kept — run \`ocm\` to attach.` })
break
case 'not-found':
api.ui.toast({ variant: 'error', message: 'No durable history found for this session' })
break
case 'corrupt-history':
api.ui.toast({ variant: 'error', message: `Session history has a gap at sequence ${result.missingSeq}` })
break
case 'replay-failed':
api.ui.toast({ variant: 'error', message: `Replay failed: ${result.message}` })
break
}
} catch (err) {
api.ui.toast({ variant: 'error', message: err instanceof Error ? err.message : String(err) })
}
}
export default { id: 'ocm', tui } satisfies TuiPluginModule
+12
View File
@@ -0,0 +1,12 @@
export type TuiRouteCurrent = { name: 'session'; params: { sessionID: string } } | { name: string; params?: Record<string, unknown> }
export type TuiSessionInfo = { id: string; directory: string; title?: string }
export type TuiToast = { title?: string; message: string; variant?: 'info' | 'success' | 'error' | 'warning' }
export type TuiCommandDef = { name: string; title: string; description?: string; slashName?: string; run: () => void | Promise<void> }
export type TuiPluginApi = {
route: { readonly current: TuiRouteCurrent }
state: { session: { get: (sessionID: string) => TuiSessionInfo | undefined } }
ui: { toast: (input: TuiToast) => void }
keymap: { registerLayer: (layer: { commands: TuiCommandDef[]; bindings?: Record<string, unknown> }) => unknown }
client: { sync?: { history: { list: (opts: { body: Record<string, number> }) => Promise<unknown> } } }
}
export type TuiPluginModule = { id?: string; tui: (api: TuiPluginApi, options?: Record<string, unknown>) => Promise<void> }
+319
View File
@@ -0,0 +1,319 @@
import { describe, it, expect, vi } from 'vitest'
import { collectSessionEvents, rewriteEventsForRemote, transferSession, planReplayBatches, type HistoryEventRow, type ReplayEvent, type TransferDeps } from '../src/session-move.js'
describe('collectSessionEvents', () => {
it('collects a session\'s events in seq order with remapped aggregateID', () => {
const rows: HistoryEventRow[] = [
{ id: 'e3', aggregate_id: 'ses_a', seq: 2, type: 'append', data: { text: 'c' } },
{ id: 'e1', aggregate_id: 'ses_a', seq: 0, type: 'append', data: { text: 'a' } },
{ id: 'e2', aggregate_id: 'ses_a', seq: 1, type: 'append', data: { text: 'b' } },
{ id: 'e4', aggregate_id: 'ses_b', seq: 0, type: 'append', data: { text: 'x' } },
]
const result = collectSessionEvents(rows, 'ses_a')
expect(result).toEqual({
kind: 'ok',
events: [
{ id: 'e1', aggregateID: 'ses_a', seq: 0, type: 'append', data: { text: 'a' } },
{ id: 'e2', aggregateID: 'ses_a', seq: 1, type: 'append', data: { text: 'b' } },
{ id: 'e3', aggregateID: 'ses_a', seq: 2, type: 'append', data: { text: 'c' } },
],
})
})
it('returns empty when the session has no events', () => {
const rows: HistoryEventRow[] = [
{ id: 'e1', aggregate_id: 'other', seq: 0, type: 'append', data: {} },
]
const result = collectSessionEvents(rows, 'unknown')
expect(result).toEqual({ kind: 'empty' })
})
it('detects a gap in the sequence', () => {
const rows: HistoryEventRow[] = [
{ id: 'e1', aggregate_id: 'ses_a', seq: 0, type: 'append', data: {} },
{ id: 'e2', aggregate_id: 'ses_a', seq: 1, type: 'append', data: {} },
{ id: 'e3', aggregate_id: 'ses_a', seq: 3, type: 'append', data: {} },
]
const result = collectSessionEvents(rows, 'ses_a')
expect(result).toEqual({ kind: 'gap', missingSeq: 2 })
})
it('detects a gap when sequence does not start at 0', () => {
const rows: HistoryEventRow[] = [
{ id: 'e1', aggregate_id: 'ses_a', seq: 1, type: 'append', data: {} },
{ id: 'e2', aggregate_id: 'ses_a', seq: 2, type: 'append', data: {} },
]
const result = collectSessionEvents(rows, 'ses_a')
expect(result).toEqual({ kind: 'gap', missingSeq: 0 })
})
})
describe('rewriteEventsForRemote', () => {
const ctx = {
localRoot: '/Users/x/repo',
remoteRoot: '/workspace/repos/repo',
}
it('rewrites session.created info directory to the remote root', () => {
const events: ReplayEvent[] = [
{
id: 'e1', aggregateID: 'ses_a', seq: 0,
type: 'session.created.1',
data: { info: { directory: '/Users/x/repo' } },
},
]
const result = rewriteEventsForRemote(events, ctx)
expect(result[0]!.data.info).toEqual({ directory: '/workspace/repos/repo' })
})
it('rewrites session.updated info directory to the remote root', () => {
const events: ReplayEvent[] = [
{
id: 'e1', aggregateID: 'ses_a', seq: 0,
type: 'session.updated.2',
data: { info: { directory: '/Users/x/repo' } },
},
]
const result = rewriteEventsForRemote(events, ctx)
expect(result[0]!.data.info).toEqual({ directory: '/workspace/repos/repo' })
})
it('preserves subdirectories under the repo root', () => {
const events: ReplayEvent[] = [
{
id: 'e1', aggregateID: 'ses_a', seq: 0,
type: 'session.created.1',
data: { info: { directory: '/Users/x/repo/packages/app' } },
},
]
const result = rewriteEventsForRemote(events, ctx)
expect(result[0]!.data.info).toEqual({ directory: '/workspace/repos/repo/packages/app' })
})
it('rewrites session.next.moved location directory', () => {
const events: ReplayEvent[] = [
{
id: 'e1', aggregateID: 'ses_a', seq: 0,
type: 'session.next.moved.1',
data: { location: { directory: '/Users/x/repo/src' } },
},
]
const result = rewriteEventsForRemote(events, ctx)
expect(result[0]!.data.location).toEqual({ directory: '/workspace/repos/repo/src' })
})
it('strips workspaceID from info', () => {
const events: ReplayEvent[] = [
{
id: 'e1', aggregateID: 'ses_a', seq: 0,
type: 'session.created.1',
data: { info: { directory: '/Users/x/repo', workspaceID: 'ws_abc' } },
},
]
const result = rewriteEventsForRemote(events, ctx)
expect(result[0]!.data.info).toEqual({ directory: '/workspace/repos/repo' })
expect('workspaceID' in result[0]!.data.info).toBe(false)
})
it('strips workspaceID from location on moved events', () => {
const events: ReplayEvent[] = [
{
id: 'e1', aggregateID: 'ses_a', seq: 0,
type: 'session.next.moved.1',
data: { location: { directory: '/Users/x/repo', workspaceID: 'ws_abc' } },
},
]
const result = rewriteEventsForRemote(events, ctx)
expect(result[0]!.data.location).toEqual({ directory: '/workspace/repos/repo' })
expect('workspaceID' in result[0]!.data.location).toBe(false)
})
it('coerces ISO time string in data.timestamp to epoch millis (per 686c820d)', () => {
const iso = '2026-07-01T10:00:00.000Z'
const events: ReplayEvent[] = [
{
id: 'e1', aggregateID: 'ses_a', seq: 0,
type: 'session.next.agent.switched.1',
data: { timestamp: iso, agent: 'code' },
},
]
const result = rewriteEventsForRemote(events, ctx)
expect(result[0]!.data.timestamp).toBe(Date.parse(iso))
expect(typeof result[0]!.data.timestamp).toBe('number')
})
it('leaves already-numeric timestamp untouched', () => {
const epoch = 1778974142967
const events: ReplayEvent[] = [
{
id: 'e1', aggregateID: 'ses_a', seq: 0,
type: 'session.next.model.switched.1',
data: { timestamp: epoch },
},
]
const result = rewriteEventsForRemote(events, ctx)
expect(result[0]!.data.timestamp).toBe(epoch)
})
it('leaves unrelated events untouched without mutating input', () => {
const events: ReplayEvent[] = [
{
id: 'e1', aggregateID: 'ses_a', seq: 0,
type: 'session.next.step.ended.2',
data: { sessionID: 'ses_a', step: { kind: 'code' } },
},
]
const frozen = JSON.parse(JSON.stringify(events))
const result = rewriteEventsForRemote(events, ctx)
expect(result[0]!.data).toEqual(frozen[0]!.data)
expect(events).toEqual(frozen)
})
})
describe('planReplayBatches', () => {
it('splits events into batches of batchSize (default 10)', () => {
const events = Array.from({ length: 25 }, (_, i) => ({
id: `e${i}`, aggregateID: 'ses_a', seq: i, type: 'append', data: {},
}))
const batches = planReplayBatches(events)
expect(batches).toHaveLength(3)
expect(batches[0]).toHaveLength(10)
expect(batches[1]).toHaveLength(10)
expect(batches[2]).toHaveLength(5)
expect(batches[0]![0]!.seq).toBe(0)
expect(batches[1]![0]!.seq).toBe(10)
expect(batches[2]![0]!.seq).toBe(20)
})
it('returns a single batch when events fit within batchSize', () => {
const events = Array.from({ length: 3 }, (_, i) => ({
id: `e${i}`, aggregateID: 'ses_a', seq: i, type: 'append', data: {},
}))
const batches = planReplayBatches(events, 10)
expect(batches).toHaveLength(1)
expect(batches[0]).toHaveLength(3)
})
it('returns empty array for empty events', () => {
expect(planReplayBatches([])).toEqual([])
})
})
function makeHistoryEvents(sessionID: string, count: number, opts: { root?: string; types?: string[] } = {}): HistoryEventRow[] {
const root = opts.root ?? '/Users/x/repo'
const types = opts.types ?? ['session.created.1']
return Array.from({ length: count }, (_, i) => ({
id: `e${i}`,
aggregate_id: sessionID,
seq: i,
type: types[Math.min(i, types.length - 1)]!,
data: { info: { directory: root }, timestamp: '2026-07-01T10:00:00.000Z' },
}))
}
describe('transferSession', () => {
const input = { sessionID: 'ses_a', localRoot: '/Users/x/repo', remoteDirectory: '/workspace/repos/repo' }
it('moves a session by replaying its full history in ordered batches', async () => {
const history = makeHistoryEvents('ses_a', 25)
const replayCalls: { dir: string; events: ReplayEvent[] }[] = []
const deps: TransferDeps = {
fetchLocalHistory: vi.fn().mockResolvedValue(history),
replayEvents: vi.fn().mockImplementation(async (dir: string, events: ReplayEvent[]) => {
replayCalls.push({ dir, events })
return { sessionID: 'ses_a' }
}),
}
const result = await transferSession(input, deps)
expect(result).toEqual({ kind: 'moved', sessionID: 'ses_a', replayedEvents: 25 })
expect(replayCalls).toHaveLength(3)
expect(replayCalls[0]!.dir).toBe('/workspace/repos/repo')
expect(replayCalls[0]!.events).toHaveLength(10)
expect(replayCalls[0]!.events[0]!.seq).toBe(0)
expect(replayCalls[1]!.events).toHaveLength(10)
expect(replayCalls[2]!.events).toHaveLength(5)
expect(replayCalls[0]!.events[0]!.data.info.directory).toBe('/workspace/repos/repo')
})
it('reports a missing session', async () => {
const deps: TransferDeps = {
fetchLocalHistory: vi.fn().mockResolvedValue([]),
replayEvents: vi.fn(),
}
const result = await transferSession(input, deps)
expect(result).toEqual({ kind: 'not-found' })
expect(deps.replayEvents).not.toHaveBeenCalled()
})
it('refuses to transfer corrupt history', async () => {
const rows: HistoryEventRow[] = [
{ id: 'e0', aggregate_id: 'ses_a', seq: 0, type: 'session.created.1', data: {} },
{ id: 'e2', aggregate_id: 'ses_a', seq: 2, type: 'session.updated.2', data: {} },
]
const deps: TransferDeps = {
fetchLocalHistory: vi.fn().mockResolvedValue(rows),
replayEvents: vi.fn(),
}
const result = await transferSession(input, deps)
expect(result).toEqual({ kind: 'corrupt-history', missingSeq: 1 })
expect(deps.replayEvents).not.toHaveBeenCalled()
})
it('surfaces replay failure and stops', async () => {
const history = makeHistoryEvents('ses_a', 25)
let callCount = 0
const deps: TransferDeps = {
fetchLocalHistory: vi.fn().mockResolvedValue(history),
replayEvents: vi.fn().mockImplementation(async () => {
callCount++
if (callCount === 2) throw new Error('Replay diverged')
return { sessionID: 'ses_a' }
}),
}
const result = await transferSession(input, deps)
expect(result).toEqual({ kind: 'replay-failed', message: 'Replay diverged' })
expect(callCount).toBe(2)
})
})