test: remove 286 low-value session history tests (#38754)

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-11-05 16:58:57 -08:00
committed by GitHub
co-authored by OrcaWin
parent cc8cdd480b
commit cbc2475d14
35 changed files with 14 additions and 7151 deletions
+1 -3
View File
@@ -639,12 +639,10 @@
2 test-no-wall-clock:src/main/agent-hooks/windows-native-hook-exe-hosts.test.ts
2 test-no-wall-clock:src/main/ai-vault-search/session-search-indexer.test.ts
1 test-no-wall-clock:src/main/ai-vault/parse-cache/session-parse-cache-preview-upgrade.test.ts
3 test-no-wall-clock:src/main/ai-vault/scanners/claude/session-scanner-claude-subagents.test.ts
1 test-no-wall-clock:src/main/ai-vault/scanners/copilot/session-scanner-copilot-cache-upgrade.test.ts
2 test-no-wall-clock:src/main/ai-vault/scanners/copilot/session-scanner-copilot-parser.test.ts
3 test-no-wall-clock:src/main/ai-vault/scanners/cursor/session-scanner-cursor-chat-meta.test.ts
2 test-no-wall-clock:src/main/ai-vault/scanners/cursor/session-scanner-cursor-chat-meta.test.ts
1 test-no-wall-clock:src/main/ai-vault/scanners/devin/session-scanner-devin-db.test.ts
4 test-no-wall-clock:src/main/ai-vault/scanners/devin/session-scanner-devin-parser.test.ts
2 test-no-wall-clock:src/main/ai-vault/scanners/grok/session-scanner-grok-parser.test.ts
3 test-no-wall-clock:src/main/ai-vault/scanners/jcode/session-scanner-jcode-parser.test.ts
1 test-no-wall-clock:src/main/ai-vault/scanners/kimi/session-scanner-kimi-parser.test.ts
+3 -12
View File
@@ -10966,7 +10966,7 @@
"providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"],
"coveredPlatforms": ["macos", "linux"],
"coveredProviders": ["local", "ssh", "remote-runtime"],
"coverageNotes": "Audit1301 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Platform-neutral unit coverage proves the Resource Manager closed badge performs one readiness seed, coalesces unknown spawn signals, skips known-session reattach signals, installs no interval, and re-reads only once per explicit daemon-management kill/restart. AI Vault tab-title sync uses bounded exact identities on the transcript-owning local, SSH, or runtime host and has no access to broad listing; unsupported older hosts retain persisted titles without fallback scans. WSL path translation still needs a Windows integration oracle. Audit1301: src/renderer/src/components/status-bar/use-resource-session-inventory.test.tsx removed. Visibility epochs, event identity fencing, retry and no-polling hook-layer alarms disappear. src/renderer/src/components/status-bar/resource-session-inventory.test.ts reduced. Detached-array/count/noop contracts, authoritative refresh variants, batching cadence, duplicate acknowledgements, error/pause combinations and other identity matrices lose their authored alarms. No equivalent replacement coverage is claimed. Audit1302: src/main/ai-vault/parse-cache/session-parse-cache-persistence.test.ts: Keep real filesystem/SQLite persistence, reopen/restart hits, changed-file invalidation, legacy/corrupt-cache recovery, concurrent scope replacement and optional-cache write failure isolation. Remove configuration/sidecar copy inventories, write-call-only timing/row counts, a wall-clock polling case with an internally hung parser, synthetic UNC aging/stat inventory and a no-op mock pretending to be failed database deletion. Lose these private configuration/scheduling/sidecar/UNC/fault wiring alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim.",
"coverageNotes": "Audit1602 removes mocked transport, deletion and ownership inventories, provider metadata projections, private callback and counter checks, and duplicate reader examples without equivalent replacement coverage. Retained tests exercise SQLite/FTS migrations, transcript/cache/sidecar changes, recovery and cursor boundaries, local process/WAL/lock/framing and generated scripts. Remote and WSL failures and some delivery races remain injected; in-process reopen does not prove crash recovery, and counters do not prove latency or memory bounds. Historical scope before this audit: Audit1301 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Platform-neutral unit coverage proves the Resource Manager closed badge performs one readiness seed, coalesces unknown spawn signals, skips known-session reattach signals, installs no interval, and re-reads only once per explicit daemon-management kill/restart. AI Vault tab-title sync uses bounded exact identities on the transcript-owning local, SSH, or runtime host and has no access to broad listing; unsupported older hosts retain persisted titles without fallback scans. WSL path translation still needs a Windows integration oracle. Audit1301: src/renderer/src/components/status-bar/use-resource-session-inventory.test.tsx removed. Visibility epochs, event identity fencing, retry and no-polling hook-layer alarms disappear. src/renderer/src/components/status-bar/resource-session-inventory.test.ts reduced. Detached-array/count/noop contracts, authoritative refresh variants, batching cadence, duplicate acknowledgements, error/pause combinations and other identity matrices lose their authored alarms. No equivalent replacement coverage is claimed. Audit1302: src/main/ai-vault/parse-cache/session-parse-cache-persistence.test.ts: Keep real filesystem/SQLite persistence, reopen/restart hits, changed-file invalidation, legacy/corrupt-cache recovery, concurrent scope replacement and optional-cache write failure isolation. Remove configuration/sidecar copy inventories, write-call-only timing/row counts, a wall-clock polling case with an internally hung parser, synthetic UNC aging/stat inventory and a no-op mock pretending to be failed database deletion. Lose these private configuration/scheduling/sidecar/UNC/fault wiring alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim.",
"motivatingLinks": [
"https://github.com/stablyai/orca/pull/7002",
"https://github.com/stablyai/orca/pull/6858",
@@ -10977,14 +10977,13 @@
"invariant": "Typing, focus, terminal switch, workspace switch, visibility resume, resize, render, per-pane liveness, and tab-title synchronization must not call global pty:listSessions or aiVault.listSessions; they must use targeted APIs or cached provider-owned state.",
"oracle": "The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The current executable slice asserts targeted visibility/first-input liveness, resize re-assertion after visibility resume, light tab/active-state resume, SSH/remote skip behavior, and a closed Resource Manager budget of one readiness seed plus one coalesced inventory read only for unknown spawn IDs. AI Vault title sync deterministically accepts only resolveSessionTitles, batches at most 64 exact identities, bounds scanner-service calls at sixteen, routes requests to the transcript-owning local/SSH/runtime host, and proves zero broad scans for unsupported hosts. The full hot-path oracle still needs instrumentation around raw focus, split focus, workspace switch, render ticks, and high-session PTY fixtures.",
"commands": [
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/ai-vault-tab-title-sync.test.ts src/main/ai-vault/scan-service/session-scanner-service-client.test.ts src/main/ai-vault/session-titles/session-title-file-reader.test.ts src/main/ai-vault/parse-cache/session-parse-cache-persistence.test.ts src/main/ipc/ai-vault/ai-vault.test.ts src/main/runtime/rpc/methods/ai-vault.test.ts",
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/ai-vault-tab-title-sync.test.ts src/main/ai-vault/session-titles/session-title-file-reader.test.ts src/main/ai-vault/parse-cache/session-parse-cache-persistence.test.ts src/main/ipc/ai-vault/ai-vault.test.ts src/main/runtime/rpc/methods/ai-vault.test.ts",
"ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/pty/pty-startup-barrier-and-listing.test.ts src/renderer/src/components/status-bar/resource-session-inventory.test.ts --maxWorkers=2 --reporter=dot"
],
"testFiles": [
"src/main/ipc/pty/pty-startup-barrier-and-listing.test.ts",
"src/renderer/src/components/status-bar/resource-session-inventory.test.ts",
"src/renderer/src/lib/ai-vault-tab-title-sync.test.ts",
"src/main/ai-vault/scan-service/session-scanner-service-client.test.ts",
"src/main/ai-vault/session-titles/session-title-file-reader.test.ts",
"src/main/ai-vault/parse-cache/session-parse-cache-persistence.test.ts",
"src/main/ipc/ai-vault/ai-vault.test.ts",
@@ -11004,15 +11003,6 @@
"independent hosts resolve concurrently while each host wire stays serial"
]
},
{
"file": "src/main/ai-vault/scan-service/session-scanner-service-client.test.ts",
"assertions": [
"the service waits for ready and runs the cache and interactive lanes independently",
"active and queued calls are bounded together at sixteen",
"cancellation reaches active work and kills a service that ignores it",
"service faults restart queued work under a restart circuit that a forced refresh reopens"
]
},
{
"file": "src/main/ai-vault/parse-cache/session-parse-cache-persistence.test.ts",
"assertions": ["unchanged transcripts remain reusable across process restarts"]
@@ -11059,6 +11049,7 @@
"Run with enough preserved sessions/providers to make a broad listing observable."
],
"knownGaps": [
"Audit1602 removes mocked transport, deletion and ownership inventories, provider metadata projections, private callback and counter checks, and duplicate reader examples without equivalent replacement coverage. Retained tests exercise SQLite/FTS migrations, transcript/cache/sidecar changes, recovery and cursor boundaries, local process/WAL/lock/framing and generated scripts. Remote and WSL failures and some delivery races remain injected; in-process reopen does not prove crash recovery, and counters do not prove latency or memory bounds.",
"Current commands cover Resource Manager readiness/lifecycle inventory counts; the broader targeted-liveness slice still lives on the pending fix-terminal-reliability stack.",
"Current coverage includes the closed Resource Manager's no-interval and known-reattach budgets, but not every hot interaction listed in the invariant.",
"No Electron or IPC-level high-session counter gate yet proves raw focus, workspace switch, render, or high-session typing stay at zero PTY listSessions calls.",
@@ -797,17 +797,13 @@
"src/main/ai-vault/scanners/antigravity/antigravity-index-file-admission.test.ts": 170,
"src/main/ai-vault/scanners/antigravity/antigravity-opening-prompt-workspace.test.ts": 204,
"src/main/ai-vault/cached-session-list-wsl-probe.test.ts": 238,
"src/main/ai-vault/scanners/codex/codex-session-root-dedup.test.ts": 183,
"src/main/ai-vault/transcripts/local-log-tail-reader.test.ts": 59,
"src/main/ai-vault/scanners/omp/omp-session-root.test.ts": 271,
"src/main/ai-vault/scanners/openclaw/openclaw-session-layout.test.ts": 223,
"src/main/ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime-preparation.test.ts": 1230,
"src/main/ai-vault/transcripts/remote-session-content-lines.test.ts": 66,
"src/main/ai-vault/runtime-session-scanner.test.ts": 245,
"src/main/ai-vault/runtime-session-search-call.test.ts": 48,
"src/main/ai-vault/session-cwd-bucket-layouts.test.ts": 62,
"src/main/ai-vault/session-delete-target.test.ts": 240,
"src/main/ai-vault/session-delete.test.ts": 243,
"src/main/ai-vault/transcripts/session-document-consumer-replacement.test.ts": 401,
"src/main/ai-vault/transcripts/session-document-discarded-scalar-memory.test.ts": 441,
"src/main/ai-vault/transcripts/session-document-stream-boundaries.test.ts": 214,
@@ -828,7 +824,6 @@
"src/main/ai-vault/scanners/antigravity/session-scanner-antigravity-source.test.ts": 502,
"src/main/ai-vault/scanners/claude/session-scanner-claude-cwd-drift.test.ts": 525,
"src/main/ai-vault/scanners/claude/session-scanner-claude-subagent-prune.test.ts": 498,
"src/main/ai-vault/scanners/claude/session-scanner-claude-subagents.test.ts": 205,
"src/main/ai-vault/scanners/claude/session-scanner-claude-title.test.ts": 504,
"src/main/ai-vault/scanners/claude/session-scanner-claude-unicode-scope.test.ts": 488,
"src/main/ai-vault/scanners/cline/session-scanner-cline-parser.test.ts": 506,
@@ -836,7 +831,6 @@
"src/main/ai-vault/scanners/codebuddy/session-scanner-codebuddy-source.test.ts": 465,
"src/main/ai-vault/scanners/codex/session-scanner-codex-dual-root.test.ts": 517,
"src/main/ai-vault/scanners/codex/session-scanner-codex-fast-path.test.ts": 392,
"src/main/ai-vault/scanners/codex/session-scanner-codex-parser.test.ts": 195,
"src/main/ai-vault/scanners/codex/session-scanner-codex-title-index.test.ts": 295,
"src/main/ai-vault/scanners/codex/session-scanner-codex-tool-records.test.ts": 177,
"src/main/ai-vault/scanners/codex/session-scanner-codex-workers.test.ts": 543,
@@ -880,7 +874,6 @@
"src/main/ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-open.test.ts": 3734,
"src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-process.test.ts": 3815,
"src/main/ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-scan-scope.test.ts": 54,
"src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-client.test.ts": 181,
"src/main/ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite.test.ts": 410,
"src/main/ai-vault/scanners/opencode2/session-scanner-opencode2-message.test.ts": 138,
"src/main/ai-vault/scanners/opencode2/session-scanner-opencode2-sqlite.test.ts": 306,
@@ -899,7 +892,6 @@
"src/main/ai-vault/session-scanner-scope-walk.test.ts": 5362,
"src/main/ai-vault/session-scanner-scope.test.ts": 550,
"src/main/ai-vault/scan-service/session-scanner-service-cancellation.test.ts": 391,
"src/main/ai-vault/scan-service/session-scanner-service-client.test.ts": 327,
"src/main/ai-vault/scan-service/session-scanner-service-entry.test.ts": 909,
"src/main/ai-vault/scan-service/session-scanner-service-request-deadline.test.ts": 122,
"src/main/ai-vault/scan-service/session-scanner-service-restart-policy.test.ts": 44,
@@ -923,7 +915,6 @@
"src/main/ai-vault/shell-command-words.test.ts": 320,
"src/main/ai-vault/structured-chat-cli-fork.test.ts": 1238,
"src/main/ai-vault/structured-chat-conversation-copy.test.ts": 917,
"src/main/ai-vault/structured-session-ownership-acp-and-pi.test.ts": 2020,
"src/main/ai-vault/structured-session-ownership-client-audience.test.ts": 1092,
"src/main/ai-vault/structured-session-ownership.test.ts": 1191,
"src/main/amp/hook-service.test.ts": 68,
@@ -75,24 +75,6 @@ it('constructs nothing and touches no disk while the setting is off', async () =
expect(errors).toEqual([])
})
it('indexes and answers once the setting is on', async () => {
await writeClaudeTranscript(
transcriptPath(RECENT_SESSION_ID),
['a distinctive conversation'],
RECENT_SESSION_ID
)
const subject = newInstance()
subject.apply({ enabled: true, historyDays: null })
await subject.settled()
expect(await searchFor('distinctive')).toEqual([RECENT_SESSION_ID])
const status = subject.status()
expect(status.enabled).toBe(true)
expect(status.filesIndexed).toBeGreaterThan(0)
expect(status.generation).toBeGreaterThan(0)
expect(errors).toEqual([])
})
it('closes the live pair and starts a new one on a settings change', async () => {
const recent = transcriptPath(RECENT_SESSION_ID)
const ancient = transcriptPath(ANCIENT_SESSION_ID)
@@ -117,26 +99,6 @@ it('closes the live pair and starts a new one on a settings change', async () =>
expect(errors).toEqual([])
})
it('leaves nothing running and no live claim when the setting goes off', async () => {
await writeClaudeTranscript(
transcriptPath(RECENT_SESSION_ID),
['a conversation'],
RECENT_SESSION_ID
)
const subject = newInstance()
subject.apply({ enabled: true, historyDays: null })
await subject.settled()
expect(subject.running).toBe(true)
subject.apply({ enabled: false, historyDays: null })
expect(subject.running).toBe(false)
expect(existsSync(harness.databasePath)).toBe(true)
subject.apply({ enabled: true, historyDays: null })
await subject.settled()
expect(subject.running).toBe(true)
expect(errors).toEqual([])
})
it('removes the database on clear and rebuilds only while consent stands', async () => {
await writeClaudeTranscript(
transcriptPath(RECENT_SESSION_ID),
@@ -208,43 +170,3 @@ it('keeps pagination stable when the clock crosses retention before a purge', as
expect(second.hits[0].sessionId).not.toBe(first.hits[0].sessionId)
expect(errors).toEqual([])
})
it('reports being switched off before blaming a scope it does not know', async () => {
const subject = newInstance()
subject.apply({ enabled: false, historyDays: null })
await subject.settled()
expect(await subject.search({ query: 'anything' }, { kind: 'unknown' })).toEqual({
kind: 'unavailable',
reason: 'disabled'
})
})
it('reports not being ready before blaming a scope it does not know', async () => {
const subject = newInstance()
subject.apply({ enabled: true, historyDays: null })
await subject.settled()
subject.close()
expect(await subject.search({ query: 'anything' }, { kind: 'unknown' })).toEqual({
kind: 'unavailable',
reason: 'not-ready'
})
})
it('answers scope-unknown once it is switched on and ready', async () => {
await writeClaudeTranscript(
transcriptPath(RECENT_SESSION_ID),
['a distinctive conversation'],
RECENT_SESSION_ID
)
const subject = newInstance()
subject.apply({ enabled: true, historyDays: null })
await subject.settled()
expect(await subject.search({ query: 'distinctive' }, { kind: 'unknown' })).toEqual({
kind: 'unavailable',
reason: 'scope-unknown'
})
expect(await searchFor('distinctive')).toEqual([RECENT_SESSION_ID])
})
@@ -38,7 +38,6 @@ vi.mock(
)
import { resetSessionParseCacheForTests } from '../ai-vault/parse-cache/session-parse-cache-store'
import { resetTranscriptConsumersForTests } from '../ai-vault/transcripts/session-transcript-consumers'
import { buildOpenCodeSqliteCandidatePath } from '../../shared/opencode-sqlite-session-path'
import {
appendOpenCodeSqliteTurn,
writeOpenCodeSqliteDatabase
@@ -50,7 +49,6 @@ import { openSessionSearchDatabase } from './session-search-schema'
import {
FakeSessionSearchClock,
openSessionSearchIndexerHarness,
writeClaudeTranscript,
type SessionSearchIndexerHarness
} from './session-search-indexer-test-fixture'
@@ -60,7 +58,6 @@ const TOOL_ONLY = 'zarquonium'
const TOOL_FILE = '/repo/app/src/telemetry/shard-reindex.ts'
const SESSION = 'ses_capture'
const SECOND_SESSION = 'ses_second'
const CLAUDE_SESSION = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'
let harness: SessionSearchIndexerHarness
let clock: FakeSessionSearchClock
@@ -153,26 +150,6 @@ function writeVault(): void {
])
}
it('finds a sentence an OpenCode assistant wrote, through the real indexer', async () => {
writeVault()
await startIndexer()
const response = openEngine().search({ query: ANSWER })
expect(response.planner.route).toBe('phrase')
expect(response.hits).toHaveLength(1)
const hit = response.hits[0]
expect(hit).toMatchObject({
agent: 'opencode',
sessionId: SESSION,
cwd: '/tmp/opencode'
})
expect(hit?.evidence?.role).toBe('assistant')
expect(hit?.evidence?.snippet).toContain('quokkaTelemetry')
expect(openEngine().search({ query: 'reindex the shards' }).hits).toHaveLength(1)
expect(openEngine().search({ query: OTHER }).hits[0]?.sessionId).toBe(SECOND_SESSION)
})
it('searches tool output under the all scope and not under conversation', async () => {
writeVault()
await startIndexer()
@@ -184,48 +161,6 @@ it('searches tool output under the all scope and not under conversation', async
expect(openEngine().search({ query: TOOL_ONLY, scope: 'conversation' }).hits).toEqual([])
})
it('indexes a tool call by its file argument and a failed one by its error', async () => {
writeVault()
await startIndexer()
expect(openEngine().search({ query: TOOL_FILE, scope: 'all' }).hits[0]?.sessionId).toBe(SESSION)
const failed = openEngine().search({ query: 'reindex exited with code', scope: 'all' })
expect(failed.hits[0]?.evidence?.role).toBe('tool')
})
it('folds a reasoning part into the assistant turn it belongs to', async () => {
writeVault()
await startIndexer()
const hit = openEngine().search({ query: 'checking how the shard map is built' }).hits[0]
expect(hit?.sessionId).toBe(SESSION)
expect(hit?.evidence?.role).toBe('assistant')
})
it('reads an OpenCode session once, not on every pass', async () => {
writeVault()
const claudePath = join(harness.claudeProjectDir, 'control.jsonl')
await writeClaudeTranscript(claudePath, ['control turn'], CLAUDE_SESSION)
const started = await startIndexer()
await started.reconcile()
await started.reconcile()
expect(openCodeReadCalls).toEqual([`capture:${SESSION}`, `capture:${SECOND_SESSION}`])
const rows = harness.read((db) =>
db.prepare('SELECT path, state, session_row_id FROM files ORDER BY path').all()
) as { path: string; state: string; session_row_id: number | null }[]
expect(
rows.find((row) => row.path === buildOpenCodeSqliteCandidatePath(dbPath(), SESSION))
).toMatchObject({ state: 'current' })
expect(
rows.find((row) => row.path === buildOpenCodeSqliteCandidatePath(dbPath(), SESSION))
?.session_row_id
).not.toBeNull()
expect(started.status()).toMatchObject({ filesDue: 0, filesFailed: 0, phase: 'current' })
expect(started.status().sessionsByAgent).toMatchObject({ opencode: 2, claude: 1 })
})
it('re-reads a session that gained a message and replaces its rows', async () => {
writeVault()
const started = await startIndexer()
@@ -4,11 +4,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Worker } from 'node:worker_threads'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
removeTree,
WINDOWS_RM_MAX_RETRIES,
WINDOWS_RM_RETRY_DELAY_MS
} from '../../shared/windows-transient-lock-removal'
import { removeTree } from '../../shared/windows-transient-lock-removal'
import { asRecord } from '../ai-vault/session-scanner-record-value'
import SyncDatabase from '../sqlite/sync-database'
import {
@@ -52,26 +48,6 @@ function schemaVersion(db: SyncDatabase): string | undefined {
}
describe('openSessionSearchDatabase', () => {
it('keeps a current-version index and its rows', async () => {
const path = await tempDatabasePath()
const first = openSessionSearchDatabase(path)
first.prepare("INSERT INTO files(path,byte_offset,mtime_ms) VALUES ('a',1,1)").run()
first
.prepare("INSERT INTO messages(session_row_id,role,text_truncated) VALUES (1,'user',1)")
.run()
first.close()
const second = openSessionSearchDatabase(path)
expect(schemaVersion(second)).toBe(String(SESSION_SEARCH_SCHEMA_VERSION))
expect(second.prepare('SELECT COUNT(*) AS c FROM files').get()).toEqual({
c: 1
})
expect(second.prepare('SELECT text_truncated FROM messages').get()).toEqual({
text_truncated: 1
})
second.close()
})
it('keeps a version 8 index that predates prefix hashes and adds the column', async () => {
const path = await tempDatabasePath()
const first = openSessionSearchDatabase(path)
@@ -122,34 +98,6 @@ describe('openSessionSearchDatabase', () => {
}
})
it('carries one FTS table and throws away an index that carries two', async () => {
const path = await tempDatabasePath()
const fresh = openSessionSearchDatabase(path)
const tables = (): string[] =>
(
fresh
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE '%_fts'")
.all() as { name: string }[]
).map((row) => row.name)
expect(tables()).toEqual(['messages_fts'])
// A version bump must remove obsolete tables that CREATE IF NOT EXISTS would retain.
fresh.exec('CREATE VIRTUAL TABLE conversation_fts USING fts5(user_text, assistant_text)')
fresh.prepare("INSERT INTO files(path,byte_offset,mtime_ms) VALUES ('a',1,1)").run()
fresh.prepare("UPDATE meta SET value = '3' WHERE key = 'schema_version'").run()
fresh.close()
const rebuilt = openSessionSearchDatabase(path)
expect(schemaVersion(rebuilt)).toBe(String(SESSION_SEARCH_SCHEMA_VERSION))
expect(
rebuilt
.prepare("SELECT count(*) AS n FROM sqlite_master WHERE name = 'conversation_fts'")
.get()
).toEqual({ n: 0 })
expect(rebuilt.prepare('SELECT COUNT(*) AS c FROM files').get()).toEqual({ c: 0 })
rebuilt.close()
})
it('replaces the file on a version mismatch instead of dropping tables in place', async () => {
const path = await tempDatabasePath()
const stale = openSessionSearchDatabase(path)
@@ -208,151 +156,3 @@ it('rebuilds a file too corrupt to open instead of refusing forever', async () =
rebuilt.close()
}
})
it('rebuilds a file that is not a database at all', async () => {
const path = await tempDatabasePath()
await writeFile(path, 'not a SQLite database')
const rebuilt = openSessionSearchDatabase(path)
try {
expect(schemaVersion(rebuilt)).toBe(String(SESSION_SEARCH_SCHEMA_VERSION))
} finally {
rebuilt.close()
}
})
it('gives up rather than looping when a fresh file still cannot be opened', async () => {
const path = await tempDatabasePath()
await writeFile(path, 'not a SQLite database')
const open = vi.spyOn(SyncDatabase.prototype, 'pragma').mockImplementation(() => {
throw Object.assign(new Error('database disk image is malformed'), {
code: 'SQLITE_CORRUPT'
})
})
try {
expect(() => openSessionSearchDatabase(path)).toThrow(/malformed/)
} finally {
open.mockRestore()
}
})
it('surfaces the unlink failure itself when a stale index cannot be removed', async () => {
const path = await tempDatabasePath()
const stale = openSessionSearchDatabase(path)
stale
.prepare("UPDATE meta SET value = ? WHERE key = 'schema_version'")
.run(String(SESSION_SEARCH_SCHEMA_VERSION + 1))
stale.close()
recordedRmSync.mockReset()
recordedRmSync.mockImplementation(() => {
throw Object.assign(new Error('EPERM: operation not permitted, unlink'), {
code: 'EPERM'
})
})
try {
// A second close could hide the unlink error behind ERR_INVALID_STATE.
expect(() => openSessionSearchDatabase(path)).toThrow(/EPERM/)
expect(() => openSessionSearchDatabase(path)).not.toThrow(/not open/)
} finally {
recordedRmSync.mockReset()
}
})
it('creates the directory the index lives in', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-session-search-mkdir-'))
roots.push(root)
const db = openSessionSearchDatabase(join(root, 'ai-vault-search', 'index.sqlite'))
try {
expect(schemaVersion(db)).toBe(String(SESSION_SEARCH_SCHEMA_VERSION))
} finally {
db.close()
}
})
it('rebuilds when meta exists but its version row is gone', async () => {
const path = await tempDatabasePath()
const damaged = openSessionSearchDatabase(path)
damaged.prepare("INSERT INTO files(path,byte_offset,mtime_ms) VALUES ('a',1,1)").run()
damaged.prepare("DELETE FROM meta WHERE key = 'schema_version'").run()
damaged.close()
const rebuilt = openSessionSearchDatabase(path)
try {
expect(schemaVersion(rebuilt)).toBe(String(SESSION_SEARCH_SCHEMA_VERSION))
expect(rebuilt.prepare('SELECT COUNT(*) AS c FROM files').get()).toEqual({
c: 0
})
} finally {
rebuilt.close()
}
})
it('opens with the pragmas the write path depends on', async () => {
const db = openSessionSearchDatabase(await tempDatabasePath())
try {
// INCREMENTAL auto-vacuum must be enabled on an empty file for bounded page reclamation.
expect(Number(db.pragma('auto_vacuum', { simple: true }))).toBe(2)
expect(String(db.pragma('journal_mode', { simple: true })).toLowerCase()).toBe('wal')
expect(Number(db.pragma('synchronous', { simple: true }))).toBe(1)
expect(Number(db.pragma('journal_size_limit', { simple: true }))).toBe(8388608)
// A nonzero busy timeout allows contended writers to wait instead of failing immediately.
expect(Number(db.pragma('busy_timeout', { simple: true }))).toBe(5000)
} finally {
db.close()
}
})
it("walks a session's rows through an index rather than scanning the table", async () => {
const db = openSessionSearchDatabase(await tempDatabasePath())
try {
const plan = (
db
.prepare('EXPLAIN QUERY PLAN SELECT id FROM messages WHERE session_row_id = ? LIMIT ?')
.all(1, 1) as { detail: string }[]
)
.map((row) => row.detail)
.join(' ')
expect(plan).toContain('messages_session')
} finally {
db.close()
}
})
it("retries a Windows lock that outlives rmSync's own retries", async () => {
const path = await tempDatabasePath()
openSessionSearchDatabase(path).close()
vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
recordedRmSync.mockReset()
const locked = Object.assign(new Error('EPERM: operation not permitted'), {
code: 'EPERM'
})
recordedRmSync.mockImplementationOnce(() => {
throw locked
})
try {
expect(() => removeSessionSearchDatabase(path)).not.toThrow()
expect(recordedRmSync.mock.calls.length).toBe(5)
await expect(stat(path)).rejects.toMatchObject({ code: 'ENOENT' })
} finally {
recordedRmSync.mockReset()
vi.restoreAllMocks()
}
})
it('gives Windows the shared retry options for a late handle release', async () => {
const path = await tempDatabasePath()
vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
recordedRmSync.mockClear()
try {
removeSessionSearchDatabase(path)
expect(recordedRmSync).toHaveBeenCalled()
for (const [, options] of recordedRmSync.mock.calls) {
expect(options).toMatchObject({
maxRetries: WINDOWS_RM_MAX_RETRIES,
retryDelay: WINDOWS_RM_RETRY_DELAY_MS
})
}
} finally {
vi.restoreAllMocks()
}
})
@@ -1,31 +1,14 @@
import { link, mkdir, mkdtemp, rm, utimes } from 'node:fs/promises'
import { mkdtemp, rm, utimes } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { basename, join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type {
AiVaultScanProgress,
AiVaultScanWork
} from '../../shared/ai-vault/scanning/ai-vault-scan-progress'
import {
localAiVaultScanProgress,
onLocalAiVaultScanProgress,
requestLocalAiVaultScan,
resetLocalAiVaultScanProgressForTests,
startLocalAiVaultScanProgress
} from './ai-vault-local-scan-progress'
import { afterEach, expect, it, vi } from 'vitest'
import type { AiVaultScanWork } from '../../shared/ai-vault/scanning/ai-vault-scan-progress'
import { resetLocalAiVaultScanProgressForTests } from './ai-vault-local-scan-progress'
import * as parseCache from './parse-cache/session-scanner-parse-cache'
import * as transcriptFs from '../native-chat/wsl-transcript-fs-access'
import { AiVaultScanTally } from './ai-vault-scan-tally'
import { aiVaultScanWork, trackAiVaultScanProgress } from './ai-vault-scan-progress'
import { writeOpenCodeSqliteDatabase } from './scanners/opencode/sqlite/session-scanner-opencode-sqlite-fixture'
import { scanAiVaultSessions } from './session-scanner'
import { resetSessionParseCacheForTests } from './parse-cache/session-parse-cache-store'
import { AiVaultScannerServiceClient } from './scan-service/session-scanner-service-client'
import {
AiVaultServiceTestChild,
aiVaultServiceRequestId,
readyAiVaultServiceChild
} from './scan-service/session-scanner-service-test-child'
import { isolatedScanRoots, writeJsonlFile } from './session-scanner-test-fixtures'
// Source fixtures exercise the real SQLite readers without a packaged worker bundle.
@@ -61,183 +44,6 @@ afterEach(async () => {
}
})
async function scanInChild(
limit = 20
): Promise<{ reports: AiVaultScanWork[]; final: AiVaultScanWork }> {
tempRoot = await mkdtemp(join(tmpdir(), 'orca-scan-strip-'))
const roots = isolatedScanRoots(tempRoot)
for (const [index, name] of ['a', 'b', 'c'].entries()) {
const path = join(roots.claudeProjectsDir, 'project', `${name}.jsonl`)
await writeJsonlFile(path, [
{
type: 'user',
sessionId: name,
timestamp: '2026-05-01T10:00:00.000Z',
cwd: '/tmp/claude',
message: { role: 'user', content: `ask ${name}` }
}
])
await utimes(path, 1_000 + index, 1_000 + index)
}
// Codex homes and linked profiles can expose hardlinks to the same transcript.
await mkdir(join(roots.claudeProjectsDir, 'linked'))
await link(
join(roots.claudeProjectsDir, 'project', 'a.jsonl'),
join(roots.claudeProjectsDir, 'linked', 'a.jsonl')
)
const signal = new AbortController().signal
const reports: AiVaultScanWork[] = []
let now = 0
trackAiVaultScanProgress(
signal,
(work) => reports.push(work),
() => (now += 1_000)
)
await scanAiVaultSessions({ ...roots, platform: 'darwin', limit, signal })
return { reports, final: aiVaultScanWork(signal)! }
}
function startScan(): {
child: AiVaultServiceTestChild
client: AiVaultScannerServiceClient
scan: Promise<{ work: AiVaultScanWork | null }>
published: (AiVaultScanProgress | null)[]
} {
const child = new AiVaultServiceTestChild()
const client = new AiVaultScannerServiceClient({
processFactory: () => child.asChildProcess(),
init: () => ({ sessionParseCache: null, sessionSearch: null })
})
const published: (AiVaultScanProgress | null)[] = []
onLocalAiVaultScanProgress(({ progress }) => published.push(progress))
const scan = requestLocalAiVaultScan(
(listener) =>
client.request<{ work: AiVaultScanWork | null }>(
{ type: 'request', operation: 'scan', options: {} },
undefined,
listener
),
{ now: () => 5_000 }
)
return { child, client, scan, published }
}
describe('Session History scanner totals and service-client progress state', () => {
it('counts distinct files while walking, then reads, and publishes the finished totals', async () => {
const { reports, final } = await scanInChild()
expect(reports.some((work) => work.stage === 'finding')).toBe(true)
expect(final).toEqual({
stage: 'reading',
agents: [
{
agent: 'claude',
files: 3,
databases: 0,
walking: false,
read: { done: 4, total: 4, skipped: 0 }
}
],
read: { done: 4, total: 4, skipped: 0 }
})
const { child, scan, published } = startScan()
readyAiVaultServiceChild(child)
await vi.waitFor(() => expect(localAiVaultScanProgress('')?.stage).toBe('finding'))
const id = aiVaultServiceRequestId(child, 'scan')
child.emit('message', { type: 'progress', id, work: reports[0] })
child.emit('message', {
type: 'result',
id,
operation: 'scan',
value: { result: { sessions: [], issues: [], scannedAt: '' }, durationMs: 1, work: final }
})
await scan
expect(published.map((progress) => progress?.stage ?? null)).toEqual([
'finding',
reports[0]!.stage,
'finished'
])
expect(localAiVaultScanProgress('')).toEqual({
...final,
scanId: '',
stage: 'finished',
startedAt: 5_000,
settledAt: 5_000
})
})
it('reaches its total when the first pass stops before reading every file it planned', async () => {
const { reports, final } = await scanInChild(1)
expect(final.read).toEqual({ done: 1, total: 2, skipped: 1 })
expect(
reports.filter((work) => work.stage === 'reading').every((work) => work.read.total === 2)
).toBe(true)
})
it('keeps a replacement entry when the scan it replaced fails late', () => {
const earlier = startLocalAiVaultScanProgress('scope', 'earlier', () => 500)
earlier.finish(null)
const old = startLocalAiVaultScanProgress('scope', 'old', () => 1_000)
const replacement = startLocalAiVaultScanProgress('scope', 'replacement', () => 2_000)
old.fail()
expect(localAiVaultScanProgress('scope')).toMatchObject({ stage: 'finding', startedAt: 2_000 })
replacement.fail()
expect(localAiVaultScanProgress('scope')).toMatchObject({
scanId: 'earlier',
stage: 'finished'
})
})
it('settles unfinished work when an interactive timeout retires the shared scanner', async () => {
vi.useFakeTimers()
const { child, client, scan } = startScan()
const rejectedScan = scan.catch((error: Error) => error)
const interactive = client.request({
type: 'request',
operation: 'subagents',
request: { agent: 'claude', parentFilePath: '/tmp/parent.jsonl' }
})
const rejectedInteractive = interactive.catch((error: Error) => error)
readyAiVaultServiceChild(child)
await vi.advanceTimersByTimeAsync(0)
child.emit('message', {
type: 'progress',
id: aiVaultServiceRequestId(child, 'scan'),
work: { stage: 'finding', agents: [], read: { done: 0, total: 0 } }
})
await vi.advanceTimersByTimeAsync(15_000)
expect(await rejectedInteractive).toBeInstanceOf(Error)
expect(await rejectedScan).toBeInstanceOf(Error)
expect(localAiVaultScanProgress('')).toMatchObject({ stage: 'finding', settledAt: 5_000 })
const retry = startLocalAiVaultScanProgress('', 'retry', () => 6_000)
retry.work({ stage: 'reading', agents: [], read: { done: 1, total: 2 } })
retry.fail()
expect(localAiVaultScanProgress('')).toMatchObject({
scanId: 'retry',
stage: 'reading',
settledAt: 6_000,
read: { done: 1, total: 2 }
})
client.dispose()
})
it('counts inode aliases within a namespace but keeps distinct WSL distros', () => {
const tally = new AiVaultScanTally()
for (const path of [
'\\\\wsl$\\Ubuntu\\home\\a\\one.jsonl',
'\\\\wsl.localhost\\ubuntu\\home\\a\\alias.jsonl',
'\\\\wsl$\\Debian\\home\\a\\other.jsonl',
'C:\\Users\\a\\native.jsonl'
]) {
tally.addFile('codex', { path, dev: 1, ino: 100 })
}
expect(tally.snapshot().agents).toMatchObject([{ agent: 'codex', files: 3 }])
})
})
it.each(['cutoff', 'bucket', 'filtered'] as const)(
'freezes %s work without changing cold/warm execution',
async (flow) => {
@@ -356,64 +162,6 @@ it.each(['cutoff', 'bucket', 'filtered'] as const)(
}
)
it.each([false, true])(
'counts repeated global visits and database sessions once (scoped=%s)',
async (scoped) => {
tempRoot = await mkdtemp(join(tmpdir(), 'orca-scan-repeat-'))
const roots = isolatedScanRoots(tempRoot)
await writeJsonlFile(join(roots.droidSessionsDir, 'same.jsonl'), [
{ type: 'session_start', id: 'same', cwd: '/repo', timestamp: '2026-10-19T00:00:00Z' },
{ type: 'message', message: { role: 'user', content: 'Generated' } }
])
const database = join(tempRoot, 'opencode.db')
writeOpenCodeSqliteDatabase(database, [
{ id: 'db-session', directory: '/repo', turns: [{ role: 'user', parts: ['Generated'] }] }
])
const listed = vi.spyOn(parseCache, 'parseListedSessionFile')
const signal = new AbortController().signal
const reports: AiVaultScanWork[] = []
let pendingAfterParses = false
let now = 0
const stop = trackAiVaultScanProgress(
signal,
(work) => {
reports.push(work)
if (listed.mock.calls.length === 3 && work.stage === 'reading' && work.read.done === 0) {
pendingAfterParses = true
}
},
() => (now += 1000)
)
try {
const result = await scanAiVaultSessions({
...roots,
droidProjectsDir: roots.droidSessionsDir,
opencodeDbPaths: [database],
scopePaths: scoped ? ['/repo'] : [],
signal,
limit: 20,
platform: 'darwin'
})
expect(result.sessions.map((row) => row.sessionId).sort()).toEqual(
scoped ? ['db-session', 'same'] : ['db-session', 'same', 'same']
)
expect(listed.mock.calls.filter(([candidate]) => candidate.agent === 'droid')).toHaveLength(2)
expect(aiVaultScanWork(signal)?.read).toEqual({ done: 2, total: 2, skipped: 0 })
if (scoped) {
expect(pendingAfterParses).toBe(true)
}
expect(
reports.filter((work) => work.stage === 'reading').every((work) => work.read.total === 2)
).toBe(true)
expect(
aiVaultScanWork(signal)?.agents.find((agent) => agent.agent === 'opencode')?.read
).toEqual({ done: 1, total: 1, skipped: 0 })
} finally {
stop()
}
}
)
it('does not settle a batch interrupted during its real parser invocation', async () => {
tempRoot = await mkdtemp(join(tmpdir(), 'orca-scan-abort-'))
const roots = isolatedScanRoots(tempRoot)
@@ -1,390 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type {
AiVaultListResult,
AiVaultSession
} from '../../shared/ai-vault/contracts/ai-vault-types'
const mocks = vi.hoisted(() => ({
callRuntimeEnvironment: vi.fn(),
listEnvironments: vi.fn(),
resolveEnvironment: vi.fn()
}))
vi.mock('../../shared/remote-runtime/host-store/runtime-environment-store', () => ({
listEnvironments: mocks.listEnvironments,
resolveEnvironment: mocks.resolveEnvironment
}))
vi.mock('../ipc/runtime-environments/runtime-environment-transport-routing', () => ({
callRuntimeEnvironment: mocks.callRuntimeEnvironment
}))
const {
deleteRuntimeAiVaultSession,
getSavedRuntimeAiVaultHostInfos,
prepareRuntimeAiVaultSessionResume,
scanRuntimeAiVaultSessions
} = await import('./runtime-session-scanner')
beforeEach(() => {
vi.clearAllMocks()
mocks.listEnvironments.mockReturnValue([])
mocks.resolveEnvironment.mockImplementation(() => {
throw new Error('not saved')
})
mocks.callRuntimeEnvironment.mockResolvedValue({
ok: true,
result: result([session('runtime:env-1', 'session-1')])
})
})
describe('runtime AI Vault session scanner', () => {
it('lists saved runtime environments as runtime execution hosts', () => {
mocks.listEnvironments.mockReturnValue([
{ id: 'env-1', name: 'Server 1' },
{ id: 'env-2', name: 'Server 2', connectionDependency: 'ssh-tunnel' }
])
expect(getSavedRuntimeAiVaultHostInfos('/user-data')).toEqual([
{ environmentId: 'env-1', executionHostId: 'runtime:env-1' },
{
environmentId: 'env-2',
executionHostId: 'runtime:env-2',
connectionDependency: 'ssh-tunnel'
}
])
})
it('forwards scan options to the runtime transport', async () => {
await scanRuntimeAiVaultSessions(
'/user-data',
'env-1',
{
limit: 25,
force: true,
scopePaths: ['/srv/app']
},
{ timeoutMs: 3000 }
)
expect(mocks.callRuntimeEnvironment).toHaveBeenCalledWith(
'/user-data',
'env-1',
'aiVault.listSessions',
{
limit: 25,
force: true,
scopePaths: ['/srv/app'],
executionHostId: 'runtime:env-1'
},
3000
)
})
it('caps forwarded project paths and reports scope truncation', async () => {
const scopePaths = Array.from({ length: 80 }, (_, index) => `/srv/repo-${index}`)
const scanResult = await scanRuntimeAiVaultSessions('/user-data', 'env-1', {
scopePaths
})
expect(mocks.callRuntimeEnvironment).toHaveBeenCalledWith(
'/user-data',
'env-1',
'aiVault.listSessions',
expect.objectContaining({ scopePaths: scopePaths.slice(0, 64) }),
undefined
)
expect(scanResult.issues).toContainEqual(
expect.objectContaining({
kind: 'scope',
message: expect.stringContaining('first 64 project paths')
})
)
})
it('stamps sessions and issues returned for a different execution host', async () => {
mocks.callRuntimeEnvironment.mockResolvedValueOnce({
ok: true,
result: result(
[session('local', 'session-1')],
[
{
executionHostId: 'ssh:dev-box',
agent: 'codex',
path: '/sessions/session-1.jsonl',
message: 'could not parse session'
}
]
)
})
const scanResult = await scanRuntimeAiVaultSessions('/user-data', 'env-1', {})
expect(scanResult.sessions).toEqual([
expect.objectContaining({
id: 'runtime:env-1:codex:session-1:/sessions/session-1.jsonl',
executionHostId: 'runtime:env-1'
})
])
expect(scanResult.issues).toEqual([
expect.objectContaining({
executionHostId: 'runtime:env-1',
agent: 'codex',
path: '/sessions/session-1.jsonl'
})
])
})
it('keeps full old-server replies and accepts only a marker matching the sent fingerprint', async () => {
const fingerprint = 'a'.repeat(64)
const old = await scanRuntimeAiVaultSessions('/user-data', 'env-1', {
afterFingerprint: fingerprint
})
expect(old.sessions).toHaveLength(1)
expect(old.unchanged).toBeUndefined()
mocks.callRuntimeEnvironment.mockResolvedValue({
ok: true,
result: {
sessions: [],
issues: [],
scannedAt: 'fresh',
fingerprint,
unchanged: true
}
})
expect(
await scanRuntimeAiVaultSessions('/user-data', 'env-1', { afterFingerprint: fingerprint })
).toMatchObject({ fingerprint, unchanged: true, scannedAt: 'fresh' })
const invalid = await scanRuntimeAiVaultSessions('/user-data', 'env-1', {
afterFingerprint: 'b'.repeat(64)
})
expect(invalid.unchanged).toBeUndefined()
expect(invalid.issues[0]?.kind).toBe('host')
})
it('prepares a resume on the transcript-owning runtime', async () => {
mocks.callRuntimeEnvironment.mockResolvedValueOnce({
ok: true,
result: { useRealCodexHome: true }
})
const args = {
agent: 'codex' as const,
filePath: '/managed/sessions/2026/07/20/rollout-a.jsonl',
codexHome: '/managed',
executionHostId: 'runtime:env-1' as const
}
await expect(prepareRuntimeAiVaultSessionResume('/user-data', 'env-1', args)).resolves.toEqual({
useRealCodexHome: true
})
expect(mocks.callRuntimeEnvironment).toHaveBeenCalledWith(
'/user-data',
'env-1',
'aiVault.prepareSessionResume',
args
)
})
it('keeps a repinned account home instead of stripping it', async () => {
mocks.callRuntimeEnvironment.mockResolvedValueOnce({
ok: true,
result: {
useRealCodexHome: false,
substituteCodexHome: '/data/orca/codex-accounts/account-2/home'
}
})
await expect(
prepareRuntimeAiVaultSessionResume('/user-data', 'env-1', {
agent: 'codex',
filePath: '/managed/sessions/2026/07/20/rollout-a.jsonl',
codexHome: '/managed',
executionHostId: 'runtime:env-1'
})
).resolves.toEqual({
useRealCodexHome: false,
substituteCodexHome: '/data/orca/codex-accounts/account-2/home'
})
})
it.each([
{ agent: 'opencode' as const, sessionId: 'opencode-copy' },
{ agent: 'omp' as const, sessionId: 'omp-copy', filePath: '/pinned-omp/sessions/copy.jsonl' }
])(
'preserves the $agent copy identity and transcript across the paired-host response',
async (forkedSession) => {
mocks.callRuntimeEnvironment.mockResolvedValueOnce({
ok: true,
result: { useRealCodexHome: false, forkedSession }
})
await expect(
prepareRuntimeAiVaultSessionResume('/user-data', 'env-1', {
agent: forkedSession.agent === 'opencode' ? 'opencode2' : 'omp',
sessionId: 'source',
filePath: '/source',
codexHome: null,
executionHostId: 'runtime:env-1',
fork: true
})
).resolves.toEqual({ useRealCodexHome: false, forkedSession })
}
)
it('fails retryably when runtime preparation returns an invalid result', async () => {
mocks.callRuntimeEnvironment.mockResolvedValueOnce({ ok: true, result: {} })
await expect(
prepareRuntimeAiVaultSessionResume('/user-data', 'env-1', {
agent: 'codex',
filePath: '/managed/sessions/2026/07/20/rollout-a.jsonl',
codexHome: '/managed',
executionHostId: 'runtime:env-1'
})
).rejects.toThrow('Invalid aiVault.prepareSessionResume response')
})
it('emits the desktop sentinel only for this exact missing RPC', async () => {
mocks.callRuntimeEnvironment.mockResolvedValueOnce({
ok: false,
error: { code: 'method_not_found', message: 'Unknown method: aiVault.prepareSessionResume' }
})
await expect(
prepareRuntimeAiVaultSessionResume('/user-data', 'env-1', {
agent: 'claude',
filePath: '/sessions/a.jsonl',
codexHome: null,
executionHostId: 'runtime:env-1'
})
).rejects.toThrow('aiVault.prepareSessionResume: method_not_found')
mocks.callRuntimeEnvironment.mockResolvedValueOnce({
ok: false,
error: { code: 'method_not_found', message: 'Unknown method: terminal.send' }
})
await expect(
prepareRuntimeAiVaultSessionResume('/user-data', 'env-1', {
agent: 'claude',
filePath: '/sessions/a.jsonl',
codexHome: null,
executionHostId: 'runtime:env-1'
})
).rejects.toThrow('Unknown method: terminal.send')
})
})
function result(
sessions: AiVaultSession[],
issues: AiVaultListResult['issues'] = []
): AiVaultListResult {
return { sessions, issues, scannedAt: '2026-07-04T00:00:00.000Z' }
}
function session(
executionHostId: AiVaultSession['executionHostId'],
sessionId: string
): AiVaultSession {
return {
id: `${executionHostId}:codex:${sessionId}:/sessions/${sessionId}.jsonl`,
executionHostId,
executionHostPlatform: 'linux',
agent: 'codex',
sessionId,
title: sessionId,
cwd: '/srv/app',
branch: null,
model: null,
filePath: `/sessions/${sessionId}.jsonl`,
codexHome: null,
createdAt: null,
updatedAt: '2026-07-04T03:00:00.000Z',
modifiedAt: '2026-07-04T00:00:00.000Z',
messageCount: 1,
totalTokens: 0,
previewMessages: [],
queuedMessageCount: 0,
subagentTranscriptCount: 0,
resumeCommand: `codex resume ${sessionId}`,
subagent: null
}
}
describe('deleteRuntimeAiVaultSession', () => {
const args = {
agent: 'claude' as const,
sessionId: 'session-1',
filePath: '/home/ada/.claude/projects/-repo/session-1.jsonl',
executionHostId: 'runtime:env-1' as const
}
it('sends only the row identity; the owning host validates the path', async () => {
mocks.callRuntimeEnvironment.mockResolvedValueOnce({ ok: true, result: { outcome: 'deleted' } })
await expect(deleteRuntimeAiVaultSession('/user-data', 'env-1', args)).resolves.toEqual({
outcome: 'deleted'
})
expect(mocks.callRuntimeEnvironment).toHaveBeenCalledWith(
'/user-data',
'env-1',
'aiVault.deleteSession',
{ agent: 'claude', sessionId: 'session-1', filePath: args.filePath },
undefined,
undefined
)
})
it('fences the delete to the pairing the user confirmed against', async () => {
mocks.callRuntimeEnvironment.mockResolvedValueOnce({ ok: true, result: { outcome: 'deleted' } })
await deleteRuntimeAiVaultSession('/user-data', 'env-1', {
...args,
expectedEnvironmentPairingRevision: 7
})
expect(mocks.callRuntimeEnvironment).toHaveBeenCalledWith(
'/user-data',
'env-1',
'aiVault.deleteSession',
{ agent: 'claude', sessionId: 'session-1', filePath: args.filePath },
undefined,
7
)
})
it('asks for a host update only when the host lacks this exact RPC', async () => {
mocks.callRuntimeEnvironment.mockResolvedValueOnce({
ok: false,
error: { code: 'method_not_found', message: 'Unknown method: aiVault.deleteSession' }
})
await expect(deleteRuntimeAiVaultSession('/user-data', 'env-1', args)).resolves.toEqual({
outcome: 'rejected',
agent: 'claude',
reason: 'host-update-required'
})
mocks.callRuntimeEnvironment.mockResolvedValueOnce({
ok: false,
error: { code: 'unavailable', message: 'Remote Orca server is unavailable.' }
})
await expect(deleteRuntimeAiVaultSession('/user-data', 'env-1', args)).resolves.toEqual({
outcome: 'failed',
agent: 'claude',
error: 'Remote Orca server is unavailable.'
})
})
})
describe('runtime row pairing stamp', () => {
it("stamps rows with this desktop's pairing, never the host's own claim", async () => {
mocks.resolveEnvironment.mockReturnValue({ id: 'env-1', createdAt: 1, pairingRevision: 9 })
mocks.callRuntimeEnvironment.mockResolvedValueOnce({
ok: true,
result: result([{ ...session('runtime:env-1', 'session-1'), hostPairingRevision: 3 }])
})
const listed = await scanRuntimeAiVaultSessions('/user-data', 'env-1', {})
expect(listed.sessions.map((row) => row.hostPairingRevision)).toEqual([9])
})
})
@@ -1,574 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { AiVaultScannerServiceClient } from './session-scanner-service-client'
import { AI_VAULT_SERVICE_READY_TIMEOUT_MS } from './session-scanner-service-client-state'
import type { AiVaultSessionSearchInit } from './session-scanner-service-protocol'
import {
AiVaultServiceTestChild,
aiVaultServiceRequestId,
readyAiVaultServiceChild
} from './session-scanner-service-test-child'
const SESSION_SEARCH_ON: AiVaultSessionSearchInit = {
databasePath: '/data/ai-vault/session-search.sqlite',
settings: { enabled: true, historyDays: null },
roots: {}
}
function setupChildren(policy: () => AiVaultSessionSearchInit | null): {
children: AiVaultServiceTestChild[]
client: AiVaultScannerServiceClient
} {
const children: AiVaultServiceTestChild[] = []
const client = new AiVaultScannerServiceClient({
processFactory: () => {
const child = new AiVaultServiceTestChild(12_345 + children.length)
children.push(child)
return child.asChildProcess()
},
init: () => ({ sessionParseCache: null, sessionSearch: policy() })
})
return { children, client }
}
function setup(idleTimeoutMs?: number): {
child: AiVaultServiceTestChild
client: AiVaultScannerServiceClient
} {
const child = new AiVaultServiceTestChild()
const client = new AiVaultScannerServiceClient({
processFactory: () => child.asChildProcess(),
init: () => ({ sessionParseCache: null, sessionSearch: null }),
idleTimeoutMs
})
return { child, client }
}
afterEach(() => {
vi.useRealTimers()
})
describe('AiVaultScannerServiceClient', () => {
it('waits for ready and runs cache and interactive lanes independently', async () => {
const { child, client } = setup()
const titles = client.request({ type: 'request', operation: 'titles', requests: [] })
const subagents = client.request({
type: 'request',
operation: 'subagents',
request: { agent: 'claude', parentFilePath: '/tmp/parent.jsonl' }
})
expect(child.sent).toEqual([expect.objectContaining({ type: 'init', protocol: 1 })])
readyAiVaultServiceChild(child)
await Promise.resolve()
expect(child.sent).toEqual(
expect.arrayContaining([
expect.objectContaining({ operation: 'titles' }),
expect.objectContaining({ operation: 'subagents' })
])
)
child.emit('message', {
type: 'result',
id: aiVaultServiceRequestId(child, 'titles'),
operation: 'titles',
value: { titles: [] }
})
child.emit('message', {
type: 'result',
id: aiVaultServiceRequestId(child, 'subagents'),
operation: 'subagents',
value: { sessions: [], issues: [] }
})
await expect(titles).resolves.toEqual({ titles: [] })
await expect(subagents).resolves.toEqual({ sessions: [], issues: [] })
client.dispose()
})
it('bounds active and queued calls together at sixteen', async () => {
const { child, client } = setup()
const calls = Array.from({ length: 16 }, () =>
client.request({ type: 'request', operation: 'titles', requests: [] })
)
await expect(
client.request({ type: 'request', operation: 'titles', requests: [] })
).rejects.toThrow('queue is full')
readyAiVaultServiceChild(child)
client.dispose()
await Promise.all(calls.map((call) => expect(call).rejects.toThrow('disposed')))
})
it('cancels active work and kills a child that ignores cancellation', async () => {
vi.useFakeTimers()
const { child, client } = setup()
const controller = new AbortController()
const request = client.request(
{ type: 'request', operation: 'titles', requests: [] },
controller.signal
)
readyAiVaultServiceChild(child)
await Promise.resolve()
const id = aiVaultServiceRequestId(child, 'titles')
controller.abort()
await expect(request).rejects.toMatchObject({ name: 'AbortError' })
expect(child.sent).toContainEqual({ type: 'cancel', id })
vi.advanceTimersByTime(1_999)
expect(child.killed).toBe(false)
vi.advanceTimersByTime(1)
expect(child.killed).toBe(true)
client.dispose()
})
it('drops a call cancelled before the child received it', async () => {
vi.useFakeTimers()
const { child, client } = setup()
const controller = new AbortController()
const cancelled = client.request(
{ type: 'request', operation: 'titles', requests: [] },
controller.signal
)
controller.abort()
await expect(cancelled).rejects.toMatchObject({ name: 'AbortError' })
expect(child.sent).not.toContainEqual(expect.objectContaining({ type: 'cancel' }))
readyAiVaultServiceChild(child)
const next = client.request({ type: 'request', operation: 'titles', requests: [] })
await Promise.resolve()
child.emit('message', {
type: 'result',
id: aiVaultServiceRequestId(child, 'titles'),
operation: 'titles',
value: { titles: [] }
})
await expect(next).resolves.toEqual({ titles: [] })
vi.advanceTimersByTime(2_000)
expect(child.killed).toBe(false)
client.dispose()
})
it('retries once when the first cold start misses the ready deadline', async () => {
vi.useFakeTimers()
const children: AiVaultServiceTestChild[] = []
const client = new AiVaultScannerServiceClient({
processFactory: () => {
const child = new AiVaultServiceTestChild(12_345 + children.length)
children.push(child)
return child.asChildProcess()
},
init: () => ({ sessionParseCache: null, sessionSearch: null })
})
const titles = client.request({ type: 'request', operation: 'titles', requests: [] })
expect(children).toHaveLength(1)
vi.advanceTimersByTime(AI_VAULT_SERVICE_READY_TIMEOUT_MS)
expect(children[0]!.killed).toBe(true)
await Promise.resolve()
vi.advanceTimersByTime(250)
expect(children).toHaveLength(2)
readyAiVaultServiceChild(children[1]!)
await Promise.resolve()
children[1]!.emit('message', {
type: 'result',
id: aiVaultServiceRequestId(children[1]!, 'titles'),
operation: 'titles',
value: { titles: [] }
})
await expect(titles).resolves.toEqual({ titles: [] })
client.dispose()
})
it('surfaces the startup error when the retried cold start also fails', async () => {
vi.useFakeTimers()
const children: AiVaultServiceTestChild[] = []
const client = new AiVaultScannerServiceClient({
processFactory: () => {
const child = new AiVaultServiceTestChild(12_345 + children.length)
children.push(child)
return child.asChildProcess()
},
init: () => ({ sessionParseCache: null, sessionSearch: null })
})
const titles = client.request({ type: 'request', operation: 'titles', requests: [] })
vi.advanceTimersByTime(AI_VAULT_SERVICE_READY_TIMEOUT_MS)
await Promise.resolve()
vi.advanceTimersByTime(250)
expect(children).toHaveLength(2)
vi.advanceTimersByTime(AI_VAULT_SERVICE_READY_TIMEOUT_MS)
await expect(titles).rejects.toThrow('did not become ready')
client.dispose()
})
it('starts a queued retry immediately when a forced refresh clears backoff', async () => {
vi.useFakeTimers()
const children: AiVaultServiceTestChild[] = []
const client = new AiVaultScannerServiceClient({
processFactory: () => {
const child = new AiVaultServiceTestChild(18_345 + children.length)
children.push(child)
return child.asChildProcess()
},
init: () => ({ sessionParseCache: null, sessionSearch: null })
})
const titles = client.request({ type: 'request', operation: 'titles', requests: [] })
vi.advanceTimersByTime(AI_VAULT_SERVICE_READY_TIMEOUT_MS)
await Promise.resolve()
expect(children).toHaveLength(1)
client.clearRestartCircuit()
expect(children).toHaveLength(2)
readyAiVaultServiceChild(children[1]!)
await vi.waitFor(() =>
expect(children[1]!.sent).toContainEqual(expect.objectContaining({ operation: 'titles' }))
)
children[1]!.emit('message', {
type: 'result',
id: aiVaultServiceRequestId(children[1]!, 'titles'),
operation: 'titles',
value: { titles: [] }
})
await expect(titles).resolves.toEqual({ titles: [] })
client.dispose()
})
it('lets a forced refresh reopen the circuit instead of waiting out the window', async () => {
vi.useFakeTimers()
const children: AiVaultServiceTestChild[] = []
const client = new AiVaultScannerServiceClient({
processFactory: () => {
const child = new AiVaultServiceTestChild(22_345 + children.length)
children.push(child)
return child.asChildProcess()
},
init: () => ({ sessionParseCache: null, sessionSearch: null })
})
// Two requests exhaust three startup faults because each retries once.
const first = client.request({ type: 'request', operation: 'titles', requests: [] })
vi.advanceTimersByTime(AI_VAULT_SERVICE_READY_TIMEOUT_MS)
await Promise.resolve()
vi.advanceTimersByTime(250)
await Promise.resolve()
vi.advanceTimersByTime(AI_VAULT_SERVICE_READY_TIMEOUT_MS)
await expect(first).rejects.toThrow('did not become ready')
vi.advanceTimersByTime(1_000)
await Promise.resolve()
const blocked = client.request({ type: 'request', operation: 'titles', requests: [] })
vi.advanceTimersByTime(AI_VAULT_SERVICE_READY_TIMEOUT_MS)
await Promise.resolve()
vi.advanceTimersByTime(5_000)
expect(children).toHaveLength(3)
client.clearRestartCircuit()
await vi.waitFor(() => expect(children).toHaveLength(4))
readyAiVaultServiceChild(children[3]!)
await vi.waitFor(() =>
expect(children[3]!.sent).toContainEqual(expect.objectContaining({ operation: 'titles' }))
)
children[3]!.emit('message', {
type: 'result',
id: aiVaultServiceRequestId(children[3]!, 'titles'),
operation: 'titles',
value: { titles: [] }
})
await expect(blocked).resolves.toEqual({ titles: [] })
client.dispose()
})
it('acknowledges cache invalidation through the running child', async () => {
const { child, client } = setup()
const invalidation = client.invalidate(['/tmp/deleted.jsonl'])
readyAiVaultServiceChild(child)
await vi.waitFor(() =>
expect(child.sent).toContainEqual({
type: 'invalidate',
generation: 1,
paths: ['/tmp/deleted.jsonl']
})
)
child.emit('message', { type: 'invalidated', generation: 1 })
await expect(invalidation).resolves.toBeUndefined()
client.dispose()
})
it('leaves a scanning child alone when cache invalidation is slow to acknowledge', async () => {
vi.useFakeTimers()
const { child, client } = setup()
const scan = client.request({ type: 'request', operation: 'scan', options: {} })
readyAiVaultServiceChild(child)
await Promise.resolve()
const invalidation = client.invalidate(['/tmp/deleted.jsonl'])
await Promise.resolve()
vi.advanceTimersByTime(AI_VAULT_SERVICE_READY_TIMEOUT_MS)
await expect(invalidation).resolves.toBeUndefined()
expect(child.killed).toBe(false)
child.emit('message', {
type: 'result',
id: aiVaultServiceRequestId(child, 'scan'),
operation: 'scan',
value: { result: { sessions: [], issues: [], scannedAt: '2026-08-10' }, durationMs: 1 }
})
await expect(scan).resolves.toMatchObject({ result: { sessions: [] } })
client.dispose()
})
it('replaces a child that does not acknowledge cache invalidation', async () => {
vi.useFakeTimers()
const children: AiVaultServiceTestChild[] = []
const client = new AiVaultScannerServiceClient({
processFactory: () => {
const child = new AiVaultServiceTestChild(12_345 + children.length)
children.push(child)
return child.asChildProcess()
},
init: () => ({ sessionParseCache: null, sessionSearch: null })
})
const invalidation = client.invalidate(['/tmp/deleted.jsonl'])
readyAiVaultServiceChild(children[0]!)
await Promise.resolve()
vi.advanceTimersByTime(AI_VAULT_SERVICE_READY_TIMEOUT_MS)
await expect(invalidation).rejects.toThrow('cache invalidation timed out')
expect(children[0]!.killed).toBe(true)
const titles = client.request({ type: 'request', operation: 'titles', requests: [] })
expect(children).toHaveLength(1)
vi.advanceTimersByTime(250)
expect(children).toHaveLength(2)
readyAiVaultServiceChild(children[1]!)
await Promise.resolve()
children[1]!.emit('message', {
type: 'result',
id: aiVaultServiceRequestId(children[1]!, 'titles'),
operation: 'titles',
value: { titles: [] }
})
await expect(titles).resolves.toEqual({ titles: [] })
client.dispose()
})
it('keeps invalidation-only children alive through acknowledgement, then retires them', async () => {
vi.useFakeTimers()
const children: AiVaultServiceTestChild[] = []
const client = new AiVaultScannerServiceClient({
processFactory: () => {
const child = new AiVaultServiceTestChild(12_345 + children.length)
children.push(child)
return child.asChildProcess()
},
init: () => ({ sessionParseCache: null, sessionSearch: null }),
idleTimeoutMs: 100
})
const first = client.request({ type: 'request', operation: 'titles', requests: [] })
readyAiVaultServiceChild(children[0]!)
await Promise.resolve()
children[0]!.emit('message', {
type: 'result',
id: aiVaultServiceRequestId(children[0]!, 'titles'),
operation: 'titles',
value: { titles: [] }
})
await first
vi.advanceTimersByTime(100)
const invalidation = client.invalidate(['/tmp/deleted.jsonl'])
readyAiVaultServiceChild(children[1]!)
await Promise.resolve()
vi.advanceTimersByTime(100)
expect(children[1]!.sent).not.toContainEqual({ type: 'shutdown' })
children[1]!.emit('message', { type: 'invalidated', generation: 1 })
await invalidation
vi.advanceTimersByTime(100)
expect(children[1]!.sent).toContainEqual({ type: 'shutdown' })
client.dispose()
})
it('rejects the active request and kills the child on malformed output', async () => {
const { child, client } = setup()
const request = client.request({ type: 'request', operation: 'titles', requests: [] })
readyAiVaultServiceChild(child)
await Promise.resolve()
child.emit('message', { nope: true })
await expect(request).rejects.toThrow('malformed')
expect(child.killed).toBe(true)
client.dispose()
})
it('spawns a child for the index and never retires it while the index is on', async () => {
vi.useFakeTimers()
const { child, client } = setup(100)
const on = {
databasePath: '/data/ai-vault/session-search.sqlite',
settings: { enabled: true, historyDays: null },
roots: {}
}
client.updateSessionSearch(on)
readyAiVaultServiceChild(child)
await Promise.resolve()
expect(child.sent).toContainEqual(expect.objectContaining({ type: 'init' }))
vi.advanceTimersByTime(10_000)
expect(child.sent).not.toContainEqual({ type: 'shutdown' })
const narrowed = { ...on, settings: { enabled: true, historyDays: 30 } }
client.updateSessionSearch(narrowed)
expect(child.sent).toContainEqual({ type: 'sessionSearch', init: narrowed })
vi.advanceTimersByTime(10_000)
expect(child.sent).not.toContainEqual({ type: 'shutdown' })
client.updateSessionSearch({ ...on, settings: { enabled: false, historyDays: null } })
vi.advanceTimersByTime(100)
expect(child.sent).toContainEqual({ type: 'shutdown' })
client.dispose()
})
it('re-reads the init frame on every spawn so a respawn sees current consent', async () => {
vi.useFakeTimers()
const children: AiVaultServiceTestChild[] = []
let enabled = false
const client = new AiVaultScannerServiceClient({
processFactory: () => {
const child = new AiVaultServiceTestChild(12_345 + children.length)
children.push(child)
return child.asChildProcess()
},
init: () => ({
sessionParseCache: null,
sessionSearch: {
databasePath: '/data/ai-vault/session-search.sqlite',
settings: { enabled, historyDays: null },
roots: {}
}
})
})
const first = client.request({ type: 'request', operation: 'titles', requests: [] })
readyAiVaultServiceChild(children[0]!)
await Promise.resolve()
expect(children[0]!.sent[0]).toMatchObject({ sessionSearch: { settings: { enabled: false } } })
enabled = true
children[0]!.emit('error', new Error('crashed'))
await expect(first).rejects.toThrow('crashed')
void client.request({ type: 'request', operation: 'titles', requests: [] }).catch(() => {})
await vi.advanceTimersByTimeAsync(249)
expect(children).toHaveLength(1)
await vi.advanceTimersByTimeAsync(1)
expect(children).toHaveLength(2)
for (const respawned of children.slice(1)) {
expect(respawned.sent[0]).toMatchObject({ sessionSearch: { settings: { enabled: true } } })
}
client.dispose()
})
it('restarts a child that faulted while the index was holding it', async () => {
vi.useFakeTimers()
const { children, client } = setupChildren(() => SESSION_SEARCH_ON)
client.updateSessionSearch(SESSION_SEARCH_ON)
readyAiVaultServiceChild(children[0]!)
await Promise.resolve()
children[0]!.emit('error', new Error('crashed'))
expect(children).toHaveLength(1)
vi.advanceTimersByTime(250)
expect(children).toHaveLength(2)
expect(children[1]!.sent[0]).toMatchObject({
type: 'init',
sessionSearch: { settings: { enabled: true } }
})
client.dispose()
})
it.each([false, true])(
'waits for circuit expiry before restarting a held child (dispose=%s)',
async (dispose) => {
vi.useFakeTimers()
const { children, client } = setupChildren(() => SESSION_SEARCH_ON)
try {
client.updateSessionSearch(SESSION_SEARCH_ON)
for (const delay of [250, 1_000]) {
readyAiVaultServiceChild(children.at(-1)!)
await Promise.resolve()
children.at(-1)!.emit('error', new Error('temporary fault'))
await vi.advanceTimersByTimeAsync(delay)
}
expect(children).toHaveLength(3)
readyAiVaultServiceChild(children[2]!)
await Promise.resolve()
children[2]!.emit('error', new Error('temporary fault'))
await vi.advanceTimersByTimeAsync(59_999)
expect(children).toHaveLength(3)
if (dispose) {
client.dispose()
}
await vi.advanceTimersByTimeAsync(1)
expect(children).toHaveLength(dispose ? 3 : 4)
if (!dispose) {
readyAiVaultServiceChild(children[3]!)
}
} finally {
client.dispose()
}
}
)
it('leaves a faulted idle child dead while the index is off', async () => {
vi.useFakeTimers()
const { children, client } = setupChildren(() => null)
const titles = client.request({ type: 'request', operation: 'titles', requests: [] })
readyAiVaultServiceChild(children[0]!)
await Promise.resolve()
children[0]!.emit('message', {
type: 'result',
id: aiVaultServiceRequestId(children[0]!, 'titles'),
operation: 'titles',
value: { titles: [] }
})
await titles
children[0]!.emit('error', new Error('crashed'))
vi.advanceTimersByTime(5_000)
expect(children).toHaveLength(1)
client.dispose()
})
it('retires an idle child gracefully, then kills it after the shutdown bound', async () => {
vi.useFakeTimers()
const { child, client } = setup(100)
const request = client.request({ type: 'request', operation: 'titles', requests: [] })
readyAiVaultServiceChild(child)
await Promise.resolve()
child.emit('message', {
type: 'result',
id: aiVaultServiceRequestId(child, 'titles'),
operation: 'titles',
value: { titles: [] }
})
await request
vi.advanceTimersByTime(100)
expect(child.sent).toContainEqual({ type: 'shutdown' })
vi.advanceTimersByTime(2_000)
expect(child.killed).toBe(true)
client.dispose()
})
})
@@ -1,382 +0,0 @@
import { mkdir, mkdtemp, rm, utimes, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { listClaudeSubagentSessions } from './session-scanner-claude-subagents'
import { countSubagentTranscripts } from './session-scanner-subagent-transcripts'
let tempRoots: string[] = []
async function writeJsonlFile(filePath: string, records: unknown[]): Promise<void> {
await mkdir(dirname(filePath), { recursive: true })
await writeFile(filePath, `${records.map((record) => JSON.stringify(record)).join('\n')}\n`)
}
afterEach(async () => {
await Promise.all(tempRoots.map((root) => rm(root, { recursive: true, force: true })))
tempRoots = []
})
async function writeSubagentTranscript(args: {
subagentsDir: string
agentId: string
taskPrompt: string
timestamp: string
}): Promise<void> {
await writeJsonlFile(join(args.subagentsDir, `agent-${args.agentId}.jsonl`), [
{
type: 'user',
sessionId: 'parent-session',
isSidechain: true,
agentId: args.agentId,
timestamp: args.timestamp,
cwd: '/tmp/claude',
message: { role: 'user', content: args.taskPrompt }
}
])
}
describe('listClaudeSubagentSessions', () => {
it('lists subagents titled by the spawn description, newest first, linked to the parent', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-subagent-list-'))
tempRoots.push(root)
const parentFilePath = join(root, 'project', 'parent-session.jsonl')
const subagentsDir = join(root, 'project', 'parent-session', 'subagents')
await writeJsonlFile(parentFilePath, [
{
type: 'user',
sessionId: 'parent-session',
timestamp: '2026-07-05T10:00:00.000Z',
cwd: '/tmp/claude',
message: { role: 'user', content: 'Parent prompt' }
}
])
await writeSubagentTranscript({
subagentsDir,
agentId: 'older',
taskPrompt: 'Task prompt for the older subagent',
timestamp: '2026-07-05T10:01:00.000Z'
})
await writeFile(
join(subagentsDir, 'agent-older.meta.json'),
JSON.stringify({
agentType: 'Explore',
description: 'Map the scanner internals',
toolUseId: 'toolu_older'
})
)
await writeSubagentTranscript({
subagentsDir,
agentId: 'newer',
taskPrompt: 'Task prompt for the newer subagent',
timestamp: '2026-07-05T10:02:00.000Z'
})
await writeFile(
join(subagentsDir, 'agent-newer.meta.json'),
JSON.stringify({
agentType: 'general-purpose',
description: 'Check latest news',
toolUseId: 'toolu_newer'
})
)
const result = await listClaudeSubagentSessions({ parentFilePath, platform: 'darwin' })
expect(result.issues).toEqual([])
expect(result.sessions.map((session) => session.title)).toEqual([
'Check latest news',
'Map the scanner internals'
])
// Fresh transcripts without terminal notifications use the recency fallback.
expect(result.sessions.map((session) => session.subagent)).toEqual([
{ parentSessionId: 'parent-session', agentType: 'general-purpose', status: 'running' },
{ parentSessionId: 'parent-session', agentType: 'Explore', status: 'running' }
])
expect(result.sessions.map((session) => session.messageCount)).toEqual([1, 1])
})
it('falls back to the Task prompt title when the meta sidecar is missing or corrupt', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-subagent-meta-'))
tempRoots.push(root)
const parentFilePath = join(root, 'project', 'parent-session.jsonl')
const subagentsDir = join(root, 'project', 'parent-session', 'subagents')
await writeSubagentTranscript({
subagentsDir,
agentId: 'nometa',
taskPrompt: 'Sidecarless task prompt',
timestamp: '2026-07-05T10:01:00.000Z'
})
await writeSubagentTranscript({
subagentsDir,
agentId: 'badmeta',
taskPrompt: 'Corrupt sidecar task prompt',
timestamp: '2026-07-05T10:02:00.000Z'
})
await writeFile(join(subagentsDir, 'agent-badmeta.meta.json'), '{not json')
const result = await listClaudeSubagentSessions({ parentFilePath, platform: 'darwin' })
expect(result.issues).toEqual([])
expect(result.sessions.map((session) => session.title)).toEqual([
'Corrupt sidecar task prompt',
'Sidecarless task prompt'
])
expect(result.sessions.map((session) => session.subagent?.agentType)).toEqual([null, null])
})
it('resolves statuses from parent task notifications, falling back to transcript recency', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-subagent-status-'))
tempRoots.push(root)
const parentFilePath = join(root, 'project', 'parent-session.jsonl')
const subagentsDir = join(root, 'project', 'parent-session', 'subagents')
await writeJsonlFile(parentFilePath, [
{
type: 'user',
sessionId: 'parent-session',
timestamp: '2026-07-05T10:00:00.000Z',
cwd: '/tmp/claude',
message: { role: 'user', content: 'Parent prompt' }
},
{
type: 'user',
sessionId: 'parent-session',
timestamp: '2026-07-05T10:00:30.000Z',
message: {
role: 'user',
content:
'<task-notification>\n<task-id>finished</task-id>\n<status>running</status>\n</task-notification>'
}
},
{
type: 'user',
sessionId: 'parent-session',
timestamp: '2026-07-05T10:01:00.000Z',
message: {
role: 'user',
content:
'<task-notification>\n<task-id>finished</task-id>\n<status>completed</status>\n</task-notification>'
}
},
{
type: 'queue-operation',
operation: 'enqueue',
sessionId: 'parent-session',
timestamp: '2026-07-05T10:02:00.000Z',
content:
'<task-notification>\n<task-id>crashed</task-id>\n<status>failed</status>\n</task-notification>'
},
{
// Synchronous completion arrives as toolUseResult rather than a notification.
type: 'user',
sessionId: 'parent-session',
timestamp: '2026-07-05T10:03:00.000Z',
message: {
role: 'user',
content: [{ type: 'tool_result', tool_use_id: 'toolu_sync', content: 'done' }]
},
toolUseResult: { status: 'completed', agentId: 'syncdone', agentType: 'Explore' }
}
])
for (const agentId of ['finished', 'crashed', 'active', 'stale', 'syncdone']) {
await writeSubagentTranscript({
subagentsDir,
agentId,
taskPrompt: `Task for ${agentId}`,
timestamp: '2026-07-05T10:00:10.000Z'
})
}
const staleTime = new Date(Date.now() - 60 * 60_000)
await utimes(join(subagentsDir, 'agent-stale.jsonl'), staleTime, staleTime)
const result = await listClaudeSubagentSessions({ parentFilePath, platform: 'darwin' })
expect(result.issues).toEqual([])
const statusByTitle = Object.fromEntries(
result.sessions.map((session) => [session.title, session.subagent?.status ?? null])
)
expect(statusByTitle).toEqual({
'Task for finished': 'completed',
'Task for crashed': 'failed',
'Task for active': 'running',
'Task for stale': null,
'Task for syncdone': 'completed'
})
expect(await countSubagentTranscripts(parentFilePath)).toBe(5)
})
it('reads a terminal status whose <status> sits past the title truncation limit', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-subagent-longnote-'))
tempRoots.push(root)
const parentFilePath = join(root, 'project', 'parent-session.jsonl')
const subagentsDir = join(root, 'project', 'parent-session', 'subagents')
// Put status beyond the title cap to catch accidental notification truncation.
const notification =
'<task-notification>\n<task-id>bigtask</task-id>\n' +
'<tool-use-id>toolu_01HB57dwUE6hQVK6Mh8jVFHA</tool-use-id>\n' +
'<output-file>/private/tmp/claude-501/-Users-me-orca-workspaces-project/' +
'parent-session/tasks/bigtask.output</output-file>\n' +
'<status>completed</status>\n<summary>Agent finished</summary>\n</task-notification>'
expect(notification.indexOf('<status>')).toBeGreaterThan(96)
await writeJsonlFile(parentFilePath, [
{
type: 'user',
sessionId: 'parent-session',
timestamp: '2026-07-05T10:00:00.000Z',
cwd: '/tmp/claude',
message: { role: 'user', content: 'Parent prompt' }
},
{
type: 'user',
sessionId: 'parent-session',
timestamp: '2026-07-05T10:01:00.000Z',
message: { role: 'user', content: notification }
}
])
// Fresh mtime would mask a dropped terminal status as running.
await writeSubagentTranscript({
subagentsDir,
agentId: 'bigtask',
taskPrompt: 'Task for bigtask',
timestamp: '2026-07-05T10:00:10.000Z'
})
const result = await listClaudeSubagentSessions({ parentFilePath, platform: 'darwin' })
expect(result.issues).toEqual([])
expect(result.sessions.map((session) => session.subagent?.status)).toEqual(['completed'])
})
it('ignores a quoted notification in a user prompt so it cannot overwrite a real status', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-subagent-quoted-'))
tempRoots.push(root)
const parentFilePath = join(root, 'project', 'parent-session.jsonl')
const subagentsDir = join(root, 'project', 'parent-session', 'subagents')
await writeJsonlFile(parentFilePath, [
{
type: 'user',
sessionId: 'parent-session',
timestamp: '2026-07-05T10:00:00.000Z',
message: {
role: 'user',
content:
'<task-notification>\n<task-id>quoted</task-id>\n<status>completed</status>\n</task-notification>'
}
},
{
type: 'user',
sessionId: 'parent-session',
timestamp: '2026-07-05T10:01:00.000Z',
message: {
role: 'user',
content:
'Re-run: <task-notification>\n<task-id>quoted</task-id>\n<status>failed</status>\n</task-notification>'
}
}
])
const staleTime = new Date(Date.now() - 60 * 60_000)
await writeSubagentTranscript({
subagentsDir,
agentId: 'quoted',
taskPrompt: 'Task for quoted',
timestamp: '2026-07-05T10:00:10.000Z'
})
await utimes(join(subagentsDir, 'agent-quoted.jsonl'), staleTime, staleTime)
const result = await listClaudeSubagentSessions({ parentFilePath, platform: 'darwin' })
expect(result.issues).toEqual([])
expect(result.sessions.map((session) => session.subagent?.status)).toEqual(['completed'])
})
it('reads a sync-Task toolUseResult status even when its report quotes a notification', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-subagent-turmarker-'))
tempRoots.push(root)
const parentFilePath = join(root, 'project', 'parent-session.jsonl')
const subagentsDir = join(root, 'project', 'parent-session', 'subagents')
await writeJsonlFile(parentFilePath, [
{
// Quoted notification text must not divert this synchronous completion from toolUseResult parsing.
type: 'user',
sessionId: 'parent-session',
timestamp: '2026-07-05T10:03:00.000Z',
message: {
role: 'user',
content: [
{
type: 'tool_result',
tool_use_id: 'toolu_report',
content: 'The subagent explained how <task-notification> records work.'
}
]
},
toolUseResult: { status: 'completed', agentId: 'reporter', agentType: 'Explore' }
}
])
// Stale mtime exposes a dropped completion as unknown.
const staleTime = new Date(Date.now() - 60 * 60_000)
await writeSubagentTranscript({
subagentsDir,
agentId: 'reporter',
taskPrompt: 'Task for reporter',
timestamp: '2026-07-05T10:00:10.000Z'
})
await utimes(join(subagentsDir, 'agent-reporter.jsonl'), staleTime, staleTime)
const result = await listClaudeSubagentSessions({ parentFilePath, platform: 'darwin' })
expect(result.issues).toEqual([])
expect(result.sessions.map((session) => session.subagent?.status)).toEqual(['completed'])
})
it('links to the parent derived from its file path even when the transcript has no sessionId', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-subagent-parent-'))
tempRoots.push(root)
const parentFilePath = join(root, 'project', 'parent-session.jsonl')
const subagentsDir = join(root, 'project', 'parent-session', 'subagents')
// Missing sessionId must not turn the subagent filename into its parent ID.
await writeJsonlFile(join(subagentsDir, 'agent-nosession.jsonl'), [
{
type: 'user',
isSidechain: true,
agentId: 'nosession',
timestamp: '2026-07-05T10:01:00.000Z',
cwd: '/tmp/claude',
message: { role: 'user', content: 'Orphan subagent prompt' }
}
])
const result = await listClaudeSubagentSessions({ parentFilePath, platform: 'darwin' })
expect(result.issues).toEqual([])
expect(result.sessions.map((session) => session.subagent?.parentSessionId)).toEqual([
'parent-session'
])
})
it('returns an empty list when the session never spawned subagents', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-subagent-none-'))
tempRoots.push(root)
const parentFilePath = join(root, 'project', 'parent-session.jsonl')
await writeJsonlFile(parentFilePath, [
{
type: 'user',
sessionId: 'parent-session',
timestamp: '2026-07-05T10:00:00.000Z',
cwd: '/tmp/claude',
message: { role: 'user', content: 'Parent prompt' }
}
])
const result = await listClaudeSubagentSessions({ parentFilePath, platform: 'darwin' })
expect(result).toEqual({ sessions: [], issues: [] })
})
})
@@ -1,419 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import type { AiVaultSession } from '../../../../shared/ai-vault/contracts/ai-vault-types'
import {
dedupeCodexRolloutCopyAliases,
dedupeCodexRolloutFileAliases
} from './codex-session-root-dedup'
import { dedupeScannedSessions } from '../../session-root-dedup'
const REAL_HOME_ROLLOUT =
'/Users/ada/.codex/sessions/2026/07/01/rollout-2026-07-01T10-00-00-019f0000-1111-7222-8333-444444444444.jsonl'
const MANAGED_HOME_ROLLOUT =
'/Users/ada/Library/Application Support/orca/codex-runtime-home/home/sessions/2026/07/01/rollout-2026-07-01T10-00-00-019f0000-1111-7222-8333-444444444444.jsonl'
const MANAGED_HOME = '/Users/ada/Library/Application Support/orca/codex-runtime-home/home'
function codexSession(overrides: Partial<AiVaultSession>): AiVaultSession {
return {
id: `local:codex:${overrides.sessionId ?? 'session-1'}:${overrides.filePath ?? '/tmp/x.jsonl'}`,
executionHostId: 'local',
agent: 'codex',
sessionId: 'session-1',
title: 'Session',
cwd: '/repo/app',
branch: null,
model: null,
filePath: '/tmp/x.jsonl',
codexHome: null,
createdAt: '2026-07-01T10:00:00.000Z',
updatedAt: '2026-07-01T10:05:00.000Z',
modifiedAt: '2026-07-01T10:05:00.000Z',
messageCount: 1,
totalTokens: 10,
previewMessages: [],
queuedMessageCount: 0,
subagentTranscriptCount: 0,
resumeCommand: 'codex resume session-1',
subagent: null,
...overrides
} as AiVaultSession
}
describe('dedupeCodexRolloutFileAliases', () => {
type Candidate = {
agent: string
path: string
codexHome: string | null
hardlinkIdentity?: string
}
const accessors = {
isCodex: (candidate: Candidate) => candidate.agent === 'codex',
getFilePath: (candidate: Candidate) => candidate.path,
getCodexHome: (candidate: Candidate) => candidate.codexHome,
getHardlinkIdentity: (candidate: Candidate) => candidate.hardlinkIdentity ?? null
}
it('keeps the real-home alias when the same rollout exists in both roots', () => {
const managed = {
agent: 'codex',
path: MANAGED_HOME_ROLLOUT,
codexHome: MANAGED_HOME,
hardlinkIdentity: '1:42'
}
const real = {
agent: 'codex',
path: REAL_HOME_ROLLOUT,
codexHome: null,
hardlinkIdentity: '1:42'
}
expect(dedupeCodexRolloutFileAliases([managed, real], accessors)).toEqual([real])
expect(dedupeCodexRolloutFileAliases([real, managed], accessors)).toEqual([real])
})
it('prefers the managed runtime home over other non-default homes', () => {
const managed = {
agent: 'codex',
path: `\\\\wsl$\\Ubuntu\\home\\ada\\.local\\share\\orca\\codex-runtime-home\\home\\sessions\\2026\\07\\01\\rollout-2026-07-01T10-00-00-019f0000-1111-7222-8333-444444444444.jsonl`,
codexHome: '\\\\wsl$\\Ubuntu\\home\\ada\\.local\\share\\orca\\codex-runtime-home\\home',
hardlinkIdentity: '1:42'
}
const wslReal = {
agent: 'codex',
path: `\\\\wsl$\\Ubuntu\\home\\ada\\.codex\\sessions\\2026\\07\\01\\rollout-2026-07-01T10-00-00-019f0000-1111-7222-8333-444444444444.jsonl`,
codexHome: '\\\\wsl$\\Ubuntu\\home\\ada\\.codex',
hardlinkIdentity: '1:42'
}
expect(dedupeCodexRolloutFileAliases([wslReal, managed], accessors)).toEqual([managed])
})
it('recognizes the managed runtime home with backslash separators', () => {
const managed = {
agent: 'codex',
path: 'C:\\Users\\ada\\AppData\\Roaming\\orca\\codex-runtime-home\\home\\sessions\\2026\\07\\01\\rollout-2026-07-01T10-00-00-019f0000-1111-7222-8333-444444444444.jsonl',
codexHome: 'C:\\Users\\ada\\AppData\\Roaming\\orca\\codex-runtime-home\\home',
hardlinkIdentity: '7:9'
}
const custom = {
agent: 'codex',
path: 'D:\\codex\\sessions\\2026\\07\\01\\rollout-2026-07-01T10-00-00-019f0000-1111-7222-8333-444444444444.jsonl',
codexHome: 'D:\\codex',
hardlinkIdentity: '7:9'
}
expect(dedupeCodexRolloutFileAliases([custom, managed], accessors)).toEqual([managed])
})
it('keeps distinct rollouts, non-codex candidates, and non-rollout file names', () => {
const real = { agent: 'codex', path: REAL_HOME_ROLLOUT, codexHome: null }
const other = {
agent: 'codex',
path: '/Users/ada/.codex/sessions/2026/07/02/rollout-2026-07-02T09-00-00-029f0000-1111-7222-8333-555555555555.jsonl',
codexHome: null
}
const oddName = {
agent: 'codex',
path: `${MANAGED_HOME}/sessions/notes.jsonl`,
codexHome: MANAGED_HOME
}
const claude = { agent: 'claude', path: REAL_HOME_ROLLOUT, codexHome: null }
expect(dedupeCodexRolloutFileAliases([real, other, oddName, claude], accessors)).toEqual([
real,
other,
oddName,
claude
])
})
it('keeps same-name files unless a shared hardlink identity proves they alias', () => {
const real = {
agent: 'codex',
path: REAL_HOME_ROLLOUT,
codexHome: null,
hardlinkIdentity: '1:10'
}
const differentFile = {
agent: 'codex',
path: MANAGED_HOME_ROLLOUT,
codexHome: MANAGED_HOME,
hardlinkIdentity: '1:11'
}
const unprovenCopy = {
agent: 'codex',
path: MANAGED_HOME_ROLLOUT,
codexHome: MANAGED_HOME
}
expect(dedupeCodexRolloutFileAliases([real, differentFile], accessors)).toEqual([
real,
differentFile
])
expect(dedupeCodexRolloutFileAliases([real, unprovenCopy], accessors)).toEqual([
real,
unprovenCopy
])
})
it('never treats matching host and WSL inode tuples as one hardlink', () => {
const rolloutName = REAL_HOME_ROLLOUT.split('/').at(-1)
const host = {
agent: 'codex',
path: `C:\\Users\\ada\\.codex\\sessions\\${rolloutName}`,
codexHome: null,
hardlinkIdentity: '1:42'
}
const wsl = {
agent: 'codex',
path: `\\\\wsl$\\Ubuntu\\home\\ada\\.codex\\sessions\\${rolloutName}`,
codexHome: '\\\\wsl$\\Ubuntu\\home\\ada\\.codex',
hardlinkIdentity: '1:42'
}
expect(dedupeCodexRolloutFileAliases([host, wsl], accessors)).toEqual([host, wsl])
})
it('prefers a per-account self-contained home over other non-default homes', () => {
const perAccount = {
agent: 'codex',
path: '/Users/ada/Library/Application Support/orca/codex-accounts/019f0000-aaaa-bbbb/home/sessions/2026/07/01/rollout-2026-07-01T10-00-00-019f0000-1111-7222-8333-444444444444.jsonl',
codexHome:
'/Users/ada/Library/Application Support/orca/codex-accounts/019f0000-aaaa-bbbb/home',
hardlinkIdentity: '3:71'
}
const custom = {
agent: 'codex',
path: '/Users/ada/custom-codex/sessions/2026/07/01/rollout-2026-07-01T10-00-00-019f0000-1111-7222-8333-444444444444.jsonl',
codexHome: '/Users/ada/custom-codex',
hardlinkIdentity: '3:71'
}
expect(dedupeCodexRolloutFileAliases([custom, perAccount], accessors)).toEqual([perAccount])
expect(dedupeCodexRolloutFileAliases([perAccount, custom], accessors)).toEqual([perAccount])
})
it('keeps the real home over a per-account home when they alias', () => {
const perAccount = {
agent: 'codex',
path: '/Users/ada/Library/Application Support/orca/codex-accounts/019f0000-aaaa-bbbb/home/sessions/2026/07/01/rollout-2026-07-01T10-00-00-019f0000-1111-7222-8333-444444444444.jsonl',
codexHome:
'/Users/ada/Library/Application Support/orca/codex-accounts/019f0000-aaaa-bbbb/home',
hardlinkIdentity: '1:42'
}
const real = {
agent: 'codex',
path: REAL_HOME_ROLLOUT,
codexHome: null,
hardlinkIdentity: '1:42'
}
expect(dedupeCodexRolloutFileAliases([perAccount, real], accessors)).toEqual([real])
})
})
describe('dedupeCodexRolloutCopyAliases', () => {
type Candidate = {
agent: string
path: string
codexHome: string | null
}
const accessors = {
isCodex: (candidate: Candidate) => candidate.agent === 'codex',
getFilePath: (candidate: Candidate) => candidate.path,
getCodexHome: (candidate: Candidate) => candidate.codexHome
}
it('collapses cross-volume copies only after session_meta proves the same id', async () => {
const real = { agent: 'codex', path: REAL_HOME_ROLLOUT, codexHome: null }
const managed = {
agent: 'codex',
path: MANAGED_HOME_ROLLOUT,
codexHome: MANAGED_HOME
}
const readSessionMetaId = vi.fn(async () => 'shared-session-id')
await expect(
dedupeCodexRolloutCopyAliases([managed, real], accessors, readSessionMetaId)
).resolves.toEqual([real])
expect(readSessionMetaId).toHaveBeenCalledTimes(2)
})
it('keeps same-name files when ids differ or metadata cannot prove identity', async () => {
const real = { agent: 'codex', path: REAL_HOME_ROLLOUT, codexHome: null }
const managed = {
agent: 'codex',
path: MANAGED_HOME_ROLLOUT,
codexHome: MANAGED_HOME
}
await expect(
dedupeCodexRolloutCopyAliases([real, managed], accessors, async (path) =>
path === REAL_HOME_ROLLOUT ? 'real-id' : 'managed-id'
)
).resolves.toEqual([real, managed])
await expect(
dedupeCodexRolloutCopyAliases([real, managed], accessors, async () => null)
).resolves.toEqual([real, managed])
})
it('does not compare copies across native and WSL execution namespaces', async () => {
const rolloutName = REAL_HOME_ROLLOUT.split('/').at(-1)
const native = {
agent: 'codex',
path: `C:\\Users\\ada\\.codex\\sessions\\${rolloutName}`,
codexHome: null
}
const wsl = {
agent: 'codex',
path: `\\\\wsl$\\Ubuntu\\home\\ada\\.codex\\sessions\\${rolloutName}`,
codexHome: '\\\\wsl$\\Ubuntu\\home\\ada\\.codex'
}
const readSessionMetaId = vi.fn(async () => 'shared-session-id')
await expect(
dedupeCodexRolloutCopyAliases([native, wsl], accessors, readSessionMetaId)
).resolves.toEqual([native, wsl])
expect(readSessionMetaId).not.toHaveBeenCalled()
})
it('proves only contested same-name candidates', async () => {
const real = { agent: 'codex', path: REAL_HOME_ROLLOUT, codexHome: null }
const managed = { agent: 'codex', path: MANAGED_HOME_ROLLOUT, codexHome: MANAGED_HOME }
const lone = {
agent: 'codex',
path: '/Users/ada/.codex/sessions/rollout-2026-08-20T09-00-00-lone.jsonl',
codexHome: null
}
const readSessionMetaId = vi.fn(async () => 'shared-session-id')
await expect(
dedupeCodexRolloutCopyAliases([real, managed, lone], accessors, readSessionMetaId)
).resolves.toEqual([real, lone])
expect(readSessionMetaId).toHaveBeenCalledTimes(2)
})
it('stops proving copies once the scan is cancelled', async () => {
const real = { agent: 'codex', path: REAL_HOME_ROLLOUT, codexHome: null }
const managed = { agent: 'codex', path: MANAGED_HOME_ROLLOUT, codexHome: MANAGED_HOME }
const controller = new AbortController()
controller.abort()
await expect(
dedupeCodexRolloutCopyAliases(
[real, managed],
accessors,
async () => 'shared-session-id',
controller.signal
)
).rejects.toThrow()
})
})
describe('dedupeScannedSessions', () => {
it('collapses a both-roots session to the real-home row', () => {
const managed = codexSession({
filePath: MANAGED_HOME_ROLLOUT,
codexHome: MANAGED_HOME,
id: `local:codex:session-1:${MANAGED_HOME_ROLLOUT}`
})
const real = codexSession({
filePath: REAL_HOME_ROLLOUT,
codexHome: null,
id: `local:codex:session-1:${REAL_HOME_ROLLOUT}`
})
expect(dedupeScannedSessions([managed, real])).toEqual([real])
expect(dedupeScannedSessions([real, managed])).toEqual([real])
})
it('keeps managed-only and real-only sessions unchanged', () => {
const managedOnly = codexSession({
sessionId: 'managed-only',
filePath: `${MANAGED_HOME}/sessions/2026/07/01/rollout-a.jsonl`,
codexHome: MANAGED_HOME
})
const realOnly = codexSession({
sessionId: 'real-only',
filePath: REAL_HOME_ROLLOUT,
codexHome: null
})
expect(dedupeScannedSessions([managedOnly, realOnly])).toEqual([managedOnly, realOnly])
})
it('never collapses across execution hosts or agents', () => {
const local = codexSession({
sessionId: 'session-1',
executionHostId: 'local',
filePath: '/home/ada/.codex/sessions/rollout-shared.jsonl'
})
const remote = codexSession({
sessionId: 'session-1',
executionHostId: 'ssh:build-box',
filePath: '/home/ada/.codex/sessions/rollout-shared.jsonl',
id: 'ssh:build-box:codex:session-1:/home/ada/.codex/sessions/x.jsonl'
})
const claude = codexSession({
sessionId: 'session-1',
agent: 'claude',
filePath: '/home/ada/.codex/sessions/rollout-shared.jsonl'
})
expect(dedupeScannedSessions([local, remote, claude])).toEqual([local, remote, claude])
})
it('preserves same-host session-id collisions when rollout file names differ', () => {
const older = codexSession({
sessionId: 'collision',
filePath: '/Users/ada/.codex/sessions/2026/07/01/rollout-old.jsonl',
codexHome: null,
updatedAt: '2026-07-01T10:00:00.000Z',
modifiedAt: '2026-07-01T10:00:00.000Z'
})
const newer = codexSession({
sessionId: 'collision',
filePath: '/Users/ada/.codex/sessions/2026/07/02/rollout-new.jsonl',
codexHome: null,
updatedAt: '2026-07-02T10:00:00.000Z',
modifiedAt: '2026-07-02T10:00:00.000Z'
})
expect(dedupeScannedSessions([older, newer])).toEqual([older, newer])
})
it('resolves same-rollout aliases with a stable path tie-break', () => {
const tieA = codexSession({
sessionId: 'tie',
filePath: '/Users/ada/a/.codex/sessions/2026/07/01/rollout-tie.jsonl',
codexHome: null
})
const tieB = codexSession({
sessionId: 'tie',
filePath: '/Users/ada/b/.codex/sessions/2026/07/01/rollout-tie.jsonl',
codexHome: null
})
expect(dedupeScannedSessions([tieB, tieA])).toEqual([tieA])
})
it('prefers the managed runtime home over a WSL real home when no host real-home row exists', () => {
const wslManaged = codexSession({
sessionId: 'wsl-pair',
filePath:
'\\\\wsl$\\Ubuntu\\home\\ada\\.local\\share\\orca\\codex-runtime-home\\home\\sessions\\rollout-a.jsonl',
codexHome: '\\\\wsl$\\Ubuntu\\home\\ada\\.local\\share\\orca\\codex-runtime-home\\home'
})
const wslReal = codexSession({
sessionId: 'wsl-pair',
filePath: '\\\\wsl$\\Ubuntu\\home\\ada\\.codex\\sessions\\rollout-a.jsonl',
codexHome: '\\\\wsl$\\Ubuntu\\home\\ada\\.codex'
})
expect(dedupeScannedSessions([wslReal, wslManaged])).toEqual([wslManaged])
})
it('never collapses matching host and WSL session identities', () => {
const rolloutName = REAL_HOME_ROLLOUT.split('/').at(-1)
const host = codexSession({
sessionId: 'shared-id',
filePath: `C:\\Users\\ada\\.codex\\sessions\\${rolloutName}`,
codexHome: null
})
const wsl = codexSession({
sessionId: 'shared-id',
filePath: `\\\\wsl.localhost\\Ubuntu\\home\\ada\\.local\\share\\orca\\codex-runtime-home\\home\\sessions\\${rolloutName}`,
codexHome:
'\\\\wsl.localhost\\Ubuntu\\home\\ada\\.local\\share\\orca\\codex-runtime-home\\home'
})
expect(dedupeScannedSessions([host, wsl])).toEqual([host, wsl])
})
})
@@ -3,7 +3,6 @@ import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { parseCodexSessionFile } from './session-scanner-codex-parser'
import { readCodexTimelineOnlyRecord } from './session-scanner-codex-record-fast-path'
import {
createSessionParseStats,
parseAgentSessionFileCached
@@ -18,11 +17,6 @@ function record(type: string, payload: Record<string, unknown>, timestamp: strin
return JSON.stringify({ timestamp, type, payload })
}
// Only oversized records exercise prefix matching; small records always use the full parser.
function paddedPayload(payloadType: string, extra: Record<string, unknown> = {}) {
return { type: payloadType, ...extra, pad: PAD }
}
let tempRoots: string[] = []
async function writeTranscript(lines: string[], name: string): Promise<FileWithMtime> {
@@ -50,80 +44,6 @@ afterEach(async () => {
tempRoots = []
})
describe('readCodexTimelineOnlyRecord', () => {
// Every record that affects visible fields must bypass the timeline-only fast path.
it.each([
['session_meta', record('session_meta', { id: 'a', pad: PAD }, '2026-08-20T10:00:00.000Z')],
[
'turn_context',
record('turn_context', { cwd: '/repo', pad: PAD }, '2026-08-20T10:00:00.000Z')
],
[
'response_item/message',
record(
'response_item',
paddedPayload('message', { role: 'user' }),
'2026-08-20T10:00:00.000Z'
)
],
[
'event_msg/user_message',
record('event_msg', paddedPayload('user_message'), '2026-08-20T10:00:00.000Z')
],
[
'event_msg/agent_message',
record('event_msg', paddedPayload('agent_message'), '2026-08-20T10:00:00.000Z')
],
[
'event_msg/item_completed',
record('event_msg', paddedPayload('item_completed'), '2026-08-20T10:00:00.000Z')
],
[
'event_msg/token_count',
record('event_msg', paddedPayload('token_count'), '2026-08-20T10:00:00.000Z')
]
])('keeps %s on the full parser', (_label, line) => {
expect(readCodexTimelineOnlyRecord(Buffer.from(line))).toBeNull()
})
it.each([
['compacted', record('compacted', { message: PAD }, '2026-08-20T10:00:00.000Z')],
[
'response_item/function_call_output',
record('response_item', paddedPayload('function_call_output'), '2026-08-20T10:00:00.000Z')
],
[
'response_item/image_generation_call',
record('response_item', paddedPayload('image_generation_call'), '2026-08-20T10:00:00.000Z')
],
[
'response_item/reasoning',
record('response_item', paddedPayload('reasoning'), '2026-08-20T10:00:00.000Z')
],
[
'event_msg/task_complete',
record('event_msg', paddedPayload('task_complete'), '2026-08-20T10:00:00.000Z')
],
[
'event_msg/exec_command_output_delta',
record('event_msg', paddedPayload('exec_command_output_delta'), '2026-08-20T10:00:00.000Z')
]
])('takes %s off the full parser', (_label, line) => {
expect(readCodexTimelineOnlyRecord(Buffer.from(line))).toEqual({
timestamp: '2026-08-20T10:00:00.000Z'
})
})
it('falls back for small, reordered, or prefix-ambiguous records', () => {
const small = record('compacted', { message: 'short' }, '2026-08-20T10:00:00.000Z')
expect(readCodexTimelineOnlyRecord(Buffer.from(small))).toBeNull()
const reordered = `${JSON.stringify({ type: 'compacted', timestamp: '2026-08-20T10:00:00.000Z', payload: { message: PAD } })}`
expect(readCodexTimelineOnlyRecord(Buffer.from(reordered))).toBeNull()
const lateType = `{"timestamp":"2026-08-20T10:00:00.000Z","type":"response_item","payload":{"pad":"${PAD}","type":"reasoning"}}`
expect(readCodexTimelineOnlyRecord(Buffer.from(lateType))).toBeNull()
})
})
describe('Codex resumable parser fast path', () => {
it('matches the one-shot parser without JSON-parsing proven irrelevant large records', async () => {
const skippedFiller = `skipped-${'x'.repeat(2 * 1024 * 1024)}`
@@ -225,32 +145,4 @@ describe('Codex resumable parser fast path', () => {
expect(session).toBeNull()
expect(stats.bytesRead).toBeLessThan((file.sizeBytes ?? 0) / 2)
})
it('never re-reads a worker transcript that later grew', async () => {
const file = await writeTranscript(
[
record(
'session_meta',
{ id: 'worker-session', thread_source: 'subagent' },
'2026-08-20T10:00:00.000Z'
),
record('compacted', { message: 'x'.repeat(1024 * 1024) }, '2026-08-20T10:00:01.000Z')
],
'rollout-2026-08-20T10-00-00-worker-grown.jsonl'
)
const candidate: SessionFileCandidate = { agent: 'codex', file, codexHome: null }
await parseAgentSessionFileCached(candidate, process.platform)
const grown = createSessionParseStats()
const session = await parseAgentSessionFileCached(
{ ...candidate, file: { ...file, mtimeMs: file.mtimeMs + 1, sizeBytes: 99_000_000 } },
process.platform,
grown
)
expect(session).toBeNull()
expect(grown.bytesRead).toBe(0)
// Early dismissal has its own counter so scan spans do not report a zero-byte incremental parse.
expect(grown).toMatchObject({ earlyStopped: 1, incremental: 0, fullParses: 0 })
})
})
@@ -1,348 +0,0 @@
import { mkdir, mkdtemp, rm, stat, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import {
createCodexSessionResumeState,
parseCodexSessionFile
} from './session-scanner-codex-parser'
import type { TranscriptMessage } from '../../transcripts/session-transcript-consumers'
let tempRoots: string[] = []
afterEach(async () => {
await Promise.all(tempRoots.map((root) => rm(root, { recursive: true, force: true })))
tempRoots = []
})
function jsonLines(records: unknown[]): string {
return records.map((record) => JSON.stringify(record)).join('\n')
}
describe('parseCodexSessionFile', () => {
it('publishes a paginated agent reply whose block is typed Text to transcript consumers', () => {
const timestamp = '2026-08-10T10:00:00.000Z'
const messages: TranscriptMessage[] = []
const state = createCodexSessionResumeState(
{ path: '/fixture/rollout.jsonl', mtimeMs: Date.parse(timestamp), modifiedAt: timestamp },
null,
{ active: true, push: (message) => messages.push(message) }
)
const consume = (type: string, payload: Record<string, unknown>) =>
state.consumeLineBytes!(Buffer.from(JSON.stringify({ timestamp, type, payload })))
consume('session_meta', { id: 'paginated-session', history_mode: 'paginated' })
consume('event_msg', {
type: 'item_completed',
item: { type: 'AgentMessage', content: [{ type: 'Text', text: 'the reply' }] }
})
expect(messages).toEqual([{ role: 'assistant', text: 'the reply', timestamp }])
})
it('uses completed user items for paginated session metadata', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-codex-paginated-'))
tempRoots.push(root)
const sessionPath = join(root, 'sessions', '2026', '08', '10', 'rollout-paginated.jsonl')
await mkdir(dirname(sessionPath), { recursive: true })
await writeFile(
sessionPath,
jsonLines([
{
timestamp: '2026-08-10T10:00:00.000Z',
type: 'session_meta',
payload: { id: 'paginated-session', history_mode: 'paginated', cwd: '/repo/app' }
},
{
timestamp: '2026-08-10T10:00:01.000Z',
type: 'response_item',
payload: {
type: 'message',
role: 'user',
content: [{ type: 'input_text', text: 'model-only prompt copy' }]
}
},
{
timestamp: '2026-08-10T10:00:02.000Z',
type: 'event_msg',
payload: {
type: 'item_completed',
item: {
type: 'UserMessage',
content: [{ type: 'text', text: 'Visible paginated prompt' }]
}
}
},
{
timestamp: '2026-08-10T10:00:03.000Z',
type: 'event_msg',
payload: {
type: 'item_completed',
item: {
type: 'AgentMessage',
content: [{ type: 'Text', text: 'Visible paginated response' }]
}
}
}
])
)
const sessionStat = await stat(sessionPath)
const session = await parseCodexSessionFile(
{
path: sessionPath,
mtimeMs: sessionStat.mtimeMs,
modifiedAt: sessionStat.mtime.toISOString()
},
'darwin',
root
)
expect(session).toMatchObject({
title: 'Visible paginated prompt',
lastUserPrompt: 'Visible paginated prompt',
messageCount: 2,
previewMessages: [
{ role: 'user', text: 'Visible paginated prompt' },
{ role: 'assistant', text: 'Visible paginated response' }
]
})
})
it("keeps a fork's own session_meta when its parent's follows it", async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-codex-fork-'))
tempRoots.push(root)
const sessionPath = join(root, 'sessions', '2026', '10', '07', 'rollout-fork.jsonl')
await mkdir(dirname(sessionPath), { recursive: true })
await writeFile(
sessionPath,
jsonLines([
{
timestamp: '2026-10-07T10:00:00.000Z',
type: 'session_meta',
payload: {
id: 'fork-session',
forked_from_id: 'parent-session',
cwd: '/repo/fork',
git: { branch: 'fork-branch' }
}
},
{
timestamp: '2026-10-07T09:00:00.000Z',
type: 'session_meta',
payload: {
id: 'parent-session',
title: 'Parent chat',
history_mode: 'paginated',
cwd: '/repo/parent',
git: { branch: 'parent-branch' }
}
},
{
timestamp: '2026-10-07T09:00:01.000Z',
type: 'response_item',
payload: {
type: 'message',
role: 'user',
content: [{ type: 'input_text', text: 'Copied prompt' }]
}
},
{
timestamp: '2026-10-07T09:00:02.000Z',
type: 'response_item',
payload: {
type: 'message',
role: 'assistant',
content: [{ type: 'output_text', text: 'Copied reply' }]
}
}
])
)
const sessionStat = await stat(sessionPath)
const session = await parseCodexSessionFile(
{
path: sessionPath,
mtimeMs: sessionStat.mtimeMs,
modifiedAt: sessionStat.mtime.toISOString()
},
'darwin',
root
)
expect(session).toMatchObject({
sessionId: 'fork-session',
cwd: '/repo/fork',
branch: 'fork-branch',
title: 'Copied prompt',
messageCount: 2
})
})
it('uses user-message events instead of later injected user-role records', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-codex-last-prompt-'))
tempRoots.push(root)
const sessionPath = join(root, 'sessions', '2026', '07', '21', 'rollout-last-prompt.jsonl')
await mkdir(dirname(sessionPath), { recursive: true })
await writeFile(
sessionPath,
jsonLines([
{
timestamp: '2026-07-21T10:00:00.000Z',
type: 'session_meta',
payload: { id: 'last-prompt-session', cwd: '/repo/app' }
},
{
timestamp: '2026-07-21T10:00:01.000Z',
type: 'event_msg',
payload: { type: 'user_message', message: 'Review the PR and fix real regressions' }
},
{
timestamp: '2026-07-21T10:00:02.000Z',
type: 'response_item',
payload: {
type: 'message',
role: 'user',
content: [{ type: 'input_text', text: '<skill>performance instructions</skill>' }]
}
}
])
)
const sessionStat = await stat(sessionPath)
const session = await parseCodexSessionFile(
{
path: sessionPath,
mtimeMs: sessionStat.mtimeMs,
modifiedAt: sessionStat.mtime.toISOString()
},
'darwin',
root
)
expect(session?.lastUserPrompt).toBe('Review the PR and fix real regressions')
// The first prompt only stands in for a name; an index thread name would replace it as 'named'.
expect(session?.titleKind).toBe('fallback')
})
it('does not double-count usage when token count formats switch', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-codex-token-switch-'))
tempRoots.push(root)
const sessionPath = join(root, 'sessions', '2026', '06', '18', 'rollout-token-switch.jsonl')
await mkdir(dirname(sessionPath), { recursive: true })
await writeFile(
sessionPath,
jsonLines([
{
timestamp: '2026-06-18T10:00:00.000Z',
type: 'session_meta',
payload: { id: 'token-format-switch', cwd: '/repo/app' }
},
{
timestamp: '2026-06-18T10:00:01.000Z',
type: 'response_item',
payload: {
type: 'message',
role: 'user',
content: [{ type: 'text', text: 'Measure Codex token totals' }]
}
},
{
timestamp: '2026-06-18T10:00:02.000Z',
type: 'event_msg',
payload: {
type: 'token_count',
info: {
last_token_usage: {
input_tokens: 70,
cached_input_tokens: 20,
output_tokens: 30,
total_tokens: 100
}
}
}
},
{
timestamp: '2026-06-18T10:00:03.000Z',
type: 'event_msg',
payload: {
type: 'token_count',
info: {
total_token_usage: {
input_tokens: 90,
cached_input_tokens: 25,
output_tokens: 60,
total_tokens: 150
}
}
}
}
])
)
const sessionStat = await stat(sessionPath)
const session = await parseCodexSessionFile(
{
path: sessionPath,
mtimeMs: sessionStat.mtimeMs,
modifiedAt: sessionStat.mtime.toISOString()
},
'darwin',
root
)
expect(session?.totalTokens).toBe(150)
})
it('extracts the model from turn context, latest turn winning', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-codex-model-'))
tempRoots.push(root)
const sessionPath = join(root, 'sessions', '2026', '07', '05', 'rollout-model.jsonl')
await mkdir(dirname(sessionPath), { recursive: true })
await writeFile(
sessionPath,
jsonLines([
{
timestamp: '2026-07-05T10:00:00.000Z',
type: 'session_meta',
payload: { id: 'model-session', cwd: '/repo/app' }
},
{
timestamp: '2026-07-05T10:00:01.000Z',
type: 'turn_context',
payload: { cwd: '/repo/app', model: 'gpt-5.1' }
},
{
timestamp: '2026-07-05T10:00:02.000Z',
type: 'response_item',
payload: {
type: 'message',
role: 'user',
content: [{ type: 'text', text: 'Switch the model' }]
}
},
{
timestamp: '2026-07-05T10:00:03.000Z',
type: 'turn_context',
payload: { cwd: '/repo/app', model: 'gpt-5.5' }
}
])
)
const sessionStat = await stat(sessionPath)
const session = await parseCodexSessionFile(
{
path: sessionPath,
mtimeMs: sessionStat.mtimeMs,
modifiedAt: sessionStat.mtime.toISOString()
},
'darwin',
root
)
expect(session?.model).toBe('gpt-5.5')
})
})
@@ -1,4 +1,4 @@
import { appendFile, mkdir, mkdtemp, rm, stat, utimes, writeFile } from 'node:fs/promises'
import { mkdir, mkdtemp, rm, stat, utimes, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -59,11 +59,9 @@ vi.mock('../../../native-chat/wsl-transcript-fs-access', async (importOriginal)
import type * as WslTranscriptFsAccess from '../../../native-chat/wsl-transcript-fs-access'
import {
cursorChatMetaPath,
readCursorChatMeta,
resetCursorChatMetaIndexCacheForTests,
withCursorChatMetaScan
} from './session-scanner-cursor-chat-meta'
import { parseCursorSessionContent } from './session-scanner-cursor-parser'
import {
isAiVaultScanCancelledError,
type AiVaultScanIssue,
@@ -81,16 +79,11 @@ import {
resetSessionParseCacheForTests,
getSessionParseCacheEntry,
lookupSessionScopeCwds,
resolveSessionScopeCwd,
scopeCwdStampOf,
peekSessionParseCacheEntry,
type PersistedSessionParseCacheEntry,
setSessionParseCacheColdTier
resolveSessionScopeCwd
} from '../../parse-cache/session-parse-cache-store'
import { isolatedScanRoots } from '../../session-scanner-test-fixtures'
import type { FileWithMtime } from '../../session-scanner-types'
import type { SessionSidecarStat } from '../../parse-cache/session-sidecar-stat'
// Mirror Cursor meta.json keys (2026-09).
type CursorMetaFixture = {
@@ -162,28 +155,7 @@ async function writeChatMeta(
return metaPath
}
function fileWithMtime(path: string): FileWithMtime {
return { path, mtimeMs: 1, modifiedAt: new Date(1).toISOString() }
}
describe('cursor chat meta', () => {
it('resolves the meta.json under the workspace hash that holds the chat id', async () => {
const cursorHome = await createCursorHome()
await writeChatMeta(cursorHome, 'aa37220647fb7ce5eb044aa4bda60807', 'other-chat')
const metaPath = await writeChatMeta(cursorHome, '96fa26ac0f433670ebec73ecef20b47b', 'chat-1', {
title: 'Shell Command Hostname'
})
const transcriptPath = await writeTranscript(cursorHome, 'private-tmp-workspace', 'chat-1', [])
expect(await cursorChatMetaPath(transcriptPath)).toBe(metaPath)
expect(await readCursorChatMeta(transcriptPath)).toEqual({
title: 'Shell Command Hostname',
cwd: '/private/tmp/workspace',
createdAt: new Date(CREATED_AT_MS).toISOString(),
updatedAt: new Date(UPDATED_AT_MS).toISOString()
})
})
it('re-indexes after a chat appears under an already indexed workspace', async () => {
const cursorHome = await createCursorHome()
await writeChatMeta(cursorHome, 'workspace-hash', 'chat-first')
@@ -199,56 +171,6 @@ describe('cursor chat meta', () => {
expect((await stat(workspacePath)).mtimeMs).not.toBe(1_000)
expect(await cursorChatMetaPath(laterTranscript)).toBe(laterMetaPath)
})
it('does not cache a metadata index whose build was refused by the WSL gate', async () => {
const cursorHome = await createCursorHome()
const metaPath = await writeChatMeta(cursorHome, 'workspace-hash', 'chat-refused')
const transcriptPath = await writeTranscript(cursorHome, 'slug', 'chat-refused', [])
failNextChatsReaddir = true
await expect(cursorChatMetaPath(transcriptPath)).resolves.toBeUndefined()
await expect(cursorChatMetaPath(transcriptPath)).resolves.toBe(metaPath)
})
it('validates the index once per scan, not once per transcript', async () => {
const cursorHome = await createCursorHome()
const transcripts: string[] = []
for (const chatId of ['chat-a', 'chat-b', 'chat-c']) {
await writeChatMeta(cursorHome, 'workspace-hash', chatId)
transcripts.push(await writeTranscript(cursorHome, 'slug', chatId, []))
}
chatsRootReads = 0
const inScan = await withCursorChatMetaScan(() =>
Promise.all(transcripts.map((path) => cursorChatMetaPath(path)))
)
expect(inScan.every(Boolean)).toBe(true)
expect(chatsRootReads).toBe(1)
// Outside a scan, each lookup must revalidate the index.
chatsRootReads = 0
await Promise.all(transcripts.map((path) => cursorChatMetaPath(path)))
expect(chatsRootReads).toBe(3)
})
it('yields nothing and does not throw when there is no chats tree', async () => {
const cursorHome = await createCursorHome()
const transcriptPath = await writeTranscript(cursorHome, 'slug', 'chat-orphan', [])
await expect(cursorChatMetaPath(transcriptPath)).resolves.toBeUndefined()
await expect(readCursorChatMeta(transcriptPath)).resolves.toBeNull()
await expect(readCursorChatMeta('/nowhere/near/cursor/chat.jsonl')).resolves.toBeNull()
})
it('yields nothing and does not throw when meta.json is malformed', async () => {
const cursorHome = await createCursorHome()
const chatDir = join(cursorHome, 'chats', 'workspace-hash', 'chat-bad')
await mkdir(chatDir, { recursive: true })
await writeFile(join(chatDir, 'meta.json'), '{ not json')
const transcriptPath = await writeTranscript(cursorHome, 'slug', 'chat-bad', [])
await expect(readCursorChatMeta(transcriptPath)).resolves.toBeNull()
})
})
async function cursorCandidate(cursorHome: string): Promise<FileWithMtime> {
@@ -301,94 +223,7 @@ async function writeCursorScanFixture(chatIds: string[]): Promise<{
}
}
describe('cursor discovery sidecar observation', () => {
it('records meta.json beside the transcript stat instead of folding it in', async () => {
const cursorHome = await createCursorHome()
const metaPath = await writeChatMeta(cursorHome, 'workspace-hash', 'chat-7')
const transcriptPath = await writeTranscript(cursorHome, 'slug', 'chat-7', [])
const before = await cursorCandidate(cursorHome)
const future = new Date(Date.now() + 10_000)
await utimes(metaPath, future, future)
const after = await cursorCandidate(cursorHome)
const transcriptStat = await stat(transcriptPath)
expect(after.mtimeMs).toBe(transcriptStat.mtimeMs)
expect(after.sizeBytes).toBe(transcriptStat.size)
expect(after.mtimeMs).toBe(before.mtimeMs)
expect(before.sidecar).toMatchObject({ path: metaPath })
expect(after.sidecar).toMatchObject({ path: metaPath })
expect((after.sidecar as SessionSidecarStat).mtimeMs).toBeGreaterThan(
(before.sidecar as SessionSidecarStat).mtimeMs
)
})
})
describe('cursor sidecar enrichment', () => {
it('fills cwd, timestamps and title from meta.json', async () => {
const cursorHome = await createCursorHome()
await writeChatMeta(cursorHome, 'workspace-hash', 'chat-2', { title: 'Named From Meta' })
await writeTranscript(cursorHome, 'slug', 'chat-2', [
JSON.stringify({ role: 'assistant', message: { content: 'hello' } })
])
resetSessionParseCacheForTests()
const { session } = await parseCursorCached(await cursorCandidate(cursorHome))
expect(session?.cwd).toBe('/private/tmp/workspace')
expect(session?.title).toBe('Named From Meta')
expect(session?.createdAt).toBe(new Date(CREATED_AT_MS).toISOString())
expect(session?.updatedAt).toBe(new Date(UPDATED_AT_MS).toISOString())
})
it('keeps a transcript title and timestamps over meta.json', async () => {
const cursorHome = await createCursorHome()
await writeChatMeta(cursorHome, 'workspace-hash', 'chat-3', { title: 'Meta Title' })
await writeTranscript(cursorHome, 'slug', 'chat-3', [
JSON.stringify({
role: 'user',
timestamp: '2026-01-01T00:00:00.000Z',
message: { content: 'transcript first prompt' }
})
])
resetSessionParseCacheForTests()
const { session } = await parseCursorCached(await cursorCandidate(cursorHome))
expect(session?.title).toBe('transcript first prompt')
expect(session?.createdAt).toBe('2026-01-01T00:00:00.000Z')
expect(session?.updatedAt).toBe('2026-01-01T00:00:00.000Z')
expect(session?.cwd).toBe('/private/tmp/workspace')
})
it('builds the resume command from the meta.json cwd', async () => {
const cursorHome = await createCursorHome()
await writeChatMeta(cursorHome, 'workspace-hash', 'chat-4', { cwd: '/repo/from-meta' })
await writeTranscript(cursorHome, 'slug', 'chat-4', [
JSON.stringify({ role: 'user', message: { content: 'hi' } })
])
resetSessionParseCacheForTests()
const { session } = await parseCursorCached(await cursorCandidate(cursorHome))
expect(session?.resumeCommand).toContain('/repo/from-meta')
})
it('leaves remote content parses to the transcript alone', async () => {
const cursorHome = await createCursorHome()
await writeChatMeta(cursorHome, 'workspace-hash', 'chat-5', { title: 'Meta Title' })
const transcriptPath = await writeTranscript(cursorHome, 'slug', 'chat-5', [])
const session = await parseCursorSessionContent(
fileWithMtime(transcriptPath),
`${JSON.stringify({ role: 'assistant', message: { content: 'remote' } })}\n`,
'linux'
)
expect(session?.cwd).toBeNull()
expect(session?.title).not.toBe('Meta Title')
})
it('re-enriches without a parse when only the sidecar is rewritten', async () => {
const cursorHome = await createCursorHome()
await writeChatMeta(cursorHome, 'workspace-hash', 'chat-8', { cwd: '/repo/first' })
@@ -447,31 +282,6 @@ describe('cursor sidecar enrichment', () => {
expect(stats.fullParses).toBe(0)
expect(session?.cwd).toBe('/repo/second')
})
it('treats a persisted entry with no sidecar as unknown and enriches once', async () => {
const cursorHome = await createCursorHome()
await writeChatMeta(cursorHome, 'workspace-hash', 'chat-9', { cwd: '/repo/persisted' })
await writeTranscript(cursorHome, 'slug', 'chat-9', [
JSON.stringify({ role: 'user', message: { content: 'hi' } })
])
resetSessionParseCacheForTests()
await parseCursorCached(await cursorCandidate(cursorHome))
// Simulate a persisted entry from before sidecar observations were stored.
const candidate = await cursorCandidate(cursorHome)
const {
resume: _resume,
foldSession: _fold,
sidecar: _sidecar,
...persisted
} = getSessionParseCacheEntry(candidate.path)!
resetSessionParseCacheForTests()
setSessionParseCacheColdTier({ read: () => persisted, stored: () => {}, deleted: () => {} })
const { session, stats } = await parseCursorCached(await cursorCandidate(cursorHome))
expect(stats.reused).toBe(0)
expect(session?.cwd).toBe('/repo/persisted')
})
})
describe('cursor chat meta scan failures', () => {
@@ -541,111 +351,6 @@ describe('cursor chat meta scan failures', () => {
'/tmp/ws-chat-a'
)
})
it('lists a cursor session whose meta.json stat is refused instead of dropping it', async () => {
const { scanOptions } = await writeCursorScanFixture(['chat-a'])
resetSessionParseCacheForTests()
failMetaJsonStats = true
const refused = await scanAiVaultSessions({ ...scanOptions, platform: 'darwin', limit: 20 })
expect(refused.sessions.filter((session) => session.agent === 'cursor')).toHaveLength(1)
expect(refused.issues).toHaveLength(1)
expect(refused.issues[0].agent).toBe('cursor')
failMetaJsonStats = false
const healed = await scanAiVaultSessions({ ...scanOptions, platform: 'darwin', limit: 20 })
expect(healed.issues).toEqual([])
expect(healed.sessions.find((session) => session.agent === 'cursor')?.cwd).toBe(
'/tmp/ws-chat-a'
)
})
it('reads the chats root once per scan across discovery and parse', async () => {
const { scanOptions } = await writeCursorScanFixture(['chat-a', 'chat-b', 'chat-c'])
resetSessionParseCacheForTests()
chatsRootReads = 0
const result = await scanAiVaultSessions({ ...scanOptions, platform: 'darwin', limit: 20 })
expect(result.sessions.filter((session) => session.agent === 'cursor')).toHaveLength(3)
expect(chatsRootReads).toBe(1)
})
it('resumes an appended transcript after a refused sidecar scan', async () => {
const cursorHome = await createCursorHome()
await writeChatMeta(cursorHome, 'workspace-hash', 'chat-r', { cwd: '/repo/resume' })
const transcriptPath = await writeTranscript(cursorHome, 'slug', 'chat-r', [
JSON.stringify({ role: 'user', message: { content: 'one' } })
])
resetSessionParseCacheForTests()
await parseCursorCached(await cursorCandidate(cursorHome))
await appendFile(
transcriptPath,
`${JSON.stringify({ role: 'user', message: { content: 'two' } })}\n`
)
failMetaJsonReads = true
const { stats: refusedStats } = await parseCursorCached(await cursorCandidate(cursorHome))
expect(refusedStats.incremental).toBe(1)
failMetaJsonReads = false
const { session, stats } = await parseCursorCached(await cursorCandidate(cursorHome))
expect(stats.reused).toBe(1)
expect(stats.fullParses).toBe(0)
expect(session?.cwd).toBe('/repo/resume')
})
})
it('recovers a cold Cursor session when its sidecar appears without a transcript change', async () => {
const cursorHome = await createCursorHome()
const path = await writeTranscript(cursorHome, 'slug', 'chat-1', [
JSON.stringify({ role: 'user', message: { content: 'Find the bug' } })
])
await utimes(path, 1, 1)
const file = await cursorCandidate(cursorHome)
const rows = new Map<string, PersistedSessionParseCacheEntry>()
const read = vi.fn((key: string) => rows.get(key))
const tier = {
read,
readScopeCwds: (paths: readonly string[]) => ({
found: new Map(
paths.flatMap((key) => {
const row = rows.get(key)
return row === undefined ? [] : [[key, { parsed: scopeCwdStampOf(row) }] as const]
})
),
parsed: true,
read: true
}),
stored: (key: string, row: PersistedSessionParseCacheEntry) => rows.set(key, row),
deleted: (key: string) => rows.delete(key)
}
setSessionParseCacheColdTier(tier)
expect((await parseCursorCached(file)).session?.cwd).toBeNull()
expect(rows.get(path)?.sidecar).toBe('none')
resetSessionParseCacheForTests()
setSessionParseCacheColdTier(tier)
read.mockClear()
for (const chatId of ['busy-1', 'busy-2']) {
await writeTranscript(cursorHome, 'slug', chatId, [
JSON.stringify({ role: 'user', message: { content: chatId } })
])
}
const scan = () =>
scanAiVaultSessions({
...isolatedScanRoots(join(cursorHome, '..')),
cursorProjectsDir: join(cursorHome, 'projects'),
platform: 'darwin',
limit: 1,
scopePaths: ['/repo']
})
expect((await scan()).sessions.some((row) => row.filePath === path)).toBe(false)
expect(peekSessionParseCacheEntry(path)).not.toHaveProperty('resume')
expect(read).toHaveBeenCalledWith(path)
await writeChatMeta(cursorHome, 'workspace-hash', 'chat-1', { cwd: '/repo' })
const found = (await scan()).sessions.filter((row) => row.filePath === path)
expect(found.map((row) => row.cwd)).toEqual(['/repo'])
expect(await stat(path)).toMatchObject({ mtimeMs: file.mtimeMs, size: file.sizeBytes })
})
it('lists a Cursor session once meta.json names the scope after a scan stored it as cwd-less', async () => {
@@ -5,15 +5,10 @@ import { afterEach, describe, expect, it } from 'vitest'
import SyncDatabase from '../../../sqlite/sync-database'
import { scanAiVaultSessions } from '../../session-scanner'
import {
devinSessionsDbDependencyPath,
devinSessionsDbPath,
devinSessionsIndexForSidecar,
resetDevinSessionsIndexCacheForTests
} from './session-scanner-devin-db'
import { parseDevinSessionContent } from './session-scanner-devin-parser'
import { enrichSessionFromSidecar } from '../../parse-cache/session-scanner-sidecar-enrichment'
import { isolatedScanRoots } from '../../session-scanner-test-fixtures'
import type { FileWithMtime, SessionFileCandidate } from '../../session-scanner-types'
import type { SessionSidecarStat } from '../../parse-cache/session-sidecar-stat'
// Mirror the Devin CLI 3000.10.x schema so every probed column exists.
@@ -93,104 +88,7 @@ async function sidecarOf(dbPath: string): Promise<SessionSidecarStat> {
return { path: dbPath, mtimeMs: fileStat.mtimeMs, sizeBytes: fileStat.size }
}
function devinCandidate(filePath: string, sidecar: FileWithMtime['sidecar']): SessionFileCandidate {
return {
agent: 'devin',
file: {
path: filePath,
mtimeMs: 1,
modifiedAt: new Date(1).toISOString(),
sidecar
},
codexHome: null
}
}
function devinFoldSession(filePath: string, record: Record<string, unknown>) {
return parseDevinSessionContent(
{ path: filePath, mtimeMs: 1, modifiedAt: new Date(1).toISOString() },
JSON.stringify(record),
'linux'
)
}
describe('devinSessionsDbPath', () => {
it('names the sessions.db beside the transcripts dir', () => {
expect(devinSessionsDbPath(join('cli', 'transcripts', 'apricot-houseboat.json'))).toBe(
join('cli', 'sessions.db')
)
})
})
describe('devinSessionsDbDependencyPath', () => {
it('points at sessions.db until a wal file appears beside it', async () => {
const dir = await tempDir('orca-devin-db-')
const cliDir = join(dir, 'cli')
const transcriptPath = join(cliDir, 'transcripts', 'apricot.json')
const dbPath = join(cliDir, 'sessions.db')
expect(await devinSessionsDbDependencyPath(transcriptPath)).toBe(dbPath)
await mkdir(cliDir, { recursive: true })
await writeFile(`${dbPath}-wal`, 'wal bytes')
expect(await devinSessionsDbDependencyPath(transcriptPath)).toBe(`${dbPath}-wal`)
})
})
describe('devinSessionsIndexForSidecar', () => {
it('reads rows keyed by session id with unix seconds as ISO strings', async () => {
const dir = await tempDir('orca-devin-db-')
const dbPath = join(dir, 'sessions.db')
writeDevinSessionsDb(dbPath, [
{
id: 'apricot-houseboat',
working_directory: 'D:\\work\\orca',
model: 'swe-1-6-fast',
title: 'Fix the vault',
created_at: DEVIN_CREATED_S,
last_activity_at: DEVIN_ACTIVITY_S,
hidden: 0
},
{ id: 'hidden-one', hidden: 1 }
])
const { index, unreadable } = devinSessionsIndexForSidecar(await sidecarOf(dbPath))
expect(unreadable).toBe(false)
const row = index?.get('apricot-houseboat')
expect(row).toEqual({
workingDirectory: 'D:\\work\\orca',
model: 'swe-1-6-fast',
title: 'Fix the vault',
createdAt: new Date(DEVIN_CREATED_S * 1000).toISOString(),
lastActivityAt: new Date(DEVIN_ACTIVITY_S * 1000).toISOString(),
hidden: false
})
expect(index?.get('hidden-one')?.hidden).toBe(true)
})
it('returns no index when discovery observed no db', () => {
expect(devinSessionsIndexForSidecar('none').index).toBeNull()
expect(devinSessionsIndexForSidecar(undefined).index).toBeNull()
})
it('marks a stat-refused db unreadable without opening it', () => {
const { index, unreadable } = devinSessionsIndexForSidecar('unknown')
expect(index).toBeNull()
expect(unreadable).toBe(true)
})
it('yields an empty index when the sessions table is absent', async () => {
const dir = await tempDir('orca-devin-db-')
const dbPath = join(dir, 'sessions.db')
const db = new SyncDatabase(dbPath)
try {
db.exec('CREATE TABLE other (id TEXT)')
} finally {
db.close()
}
const { index, unreadable } = devinSessionsIndexForSidecar(await sidecarOf(dbPath))
expect(unreadable).toBe(false)
expect(index?.size).toBe(0)
})
it('tolerates an older schema missing optional columns', async () => {
const dir = await tempDir('orca-devin-db-')
const dbPath = join(dir, 'sessions.db')
@@ -215,151 +113,6 @@ describe('devinSessionsIndexForSidecar', () => {
hidden: false
})
})
it('reports a corrupt db as unreadable rather than throwing', async () => {
const dir = await tempDir('orca-devin-db-')
const dbPath = join(dir, 'sessions.db')
await writeFile(dbPath, 'this is not sqlite')
const { index, unreadable } = devinSessionsIndexForSidecar(await sidecarOf(dbPath))
expect(index).toBeNull()
expect(unreadable).toBe(true)
})
it('invalidates when the observed file changes from db to wal with identical stats', async () => {
const dir = await tempDir('orca-devin-db-')
const dbPath = join(dir, 'sessions.db')
writeDevinSessionsDb(dbPath, [{ id: 'apricot', title: 'old' }])
const observation = await sidecarOf(dbPath)
expect(devinSessionsIndexForSidecar(observation).index?.get('apricot')?.title).toBe('old')
writeDevinSessionsDb(dbPath, [{ id: 'apricot', title: 'new' }])
const updated = devinSessionsIndexForSidecar({ ...observation, path: `${dbPath}-wal` })
expect(updated.index?.get('apricot')?.title).toBe('new')
})
it('opens the db for a wal observation and re-reads when the wal stat moves', async () => {
const dir = await tempDir('orca-devin-db-')
const dbPath = join(dir, 'sessions.db')
const walPath = `${dbPath}-wal`
writeDevinSessionsDb(dbPath, [{ id: 'apricot', title: 'old' }])
const dbStatBefore = await stat(dbPath)
await writeFile(walPath, 'wal-v1')
const first = devinSessionsIndexForSidecar(await sidecarOf(walPath))
expect(first.unreadable).toBe(false)
expect(first.index?.get('apricot')?.title).toBe('old')
// Restore database mtime to isolate WAL-only invalidation.
writeDevinSessionsDb(dbPath, [{ id: 'apricot', title: 'new' }])
await utimes(dbPath, dbStatBefore.atimeMs / 1000, dbStatBefore.mtimeMs / 1000)
await writeFile(walPath, 'wal-v2-longer')
const second = devinSessionsIndexForSidecar(await sidecarOf(walPath))
expect(second.unreadable).toBe(false)
expect(second.index?.get('apricot')?.title).toBe('new')
})
})
describe('enrichSessionFromSidecar for devin', () => {
it('fills cwd, generated title, model and timestamps from the db row', async () => {
const dir = await tempDir('orca-devin-db-')
const cliDir = join(dir, 'cli')
const transcriptsDir = join(cliDir, 'transcripts')
await mkdir(transcriptsDir, { recursive: true })
const filePath = join(transcriptsDir, 'apricot.json')
const dbPath = join(cliDir, 'sessions.db')
writeDevinSessionsDb(dbPath, [
{
id: 'apricot',
working_directory: '/srv/work',
model: 'swe-1-6-fast',
title: 'Db title',
created_at: DEVIN_CREATED_S,
last_activity_at: DEVIN_ACTIVITY_S
}
])
const fold = devinFoldSession(filePath, {
session_id: 'apricot',
steps: []
})
expect(fold?.cwd).toBeNull()
const { session, refused } = await enrichSessionFromSidecar(
devinCandidate(filePath, await sidecarOf(dbPath)),
fold,
'linux'
)
expect(refused).toBe(false)
expect(session?.cwd).toBe('/srv/work')
expect(session?.title).toBe('Db title')
expect(session?.model).toBe('swe-1-6-fast')
expect(session?.createdAt).toBe(new Date(DEVIN_CREATED_S * 1000).toISOString())
expect(session?.updatedAt).toBe(new Date(DEVIN_ACTIVITY_S * 1000).toISOString())
expect(session?.resumeCommand).toContain('/srv/work')
})
it('keeps transcript-derived fields over the db row', async () => {
const dir = await tempDir('orca-devin-db-')
const cliDir = join(dir, 'cli')
const transcriptsDir = join(cliDir, 'transcripts')
await mkdir(transcriptsDir, { recursive: true })
const filePath = join(transcriptsDir, 'apricot.json')
const dbPath = join(cliDir, 'sessions.db')
writeDevinSessionsDb(dbPath, [
{
id: 'apricot',
working_directory: '/srv/db-cwd',
model: 'db-model',
title: 'Db title',
created_at: DEVIN_CREATED_S
}
])
const fold = devinFoldSession(filePath, {
session_id: 'apricot',
working_directory: '/srv/transcript-cwd',
agent: { model_name: 'transcript-model' },
steps: [
{
metadata: {
created_at: '2026-05-01T10:00:00.000Z',
is_user_input: true
},
text: 'Transcript title'
}
]
})
const { session } = await enrichSessionFromSidecar(
devinCandidate(filePath, await sidecarOf(dbPath)),
fold,
'linux'
)
expect(session?.cwd).toBe('/srv/transcript-cwd')
expect(session?.title).toBe('Transcript title')
expect(session?.model).toBe('transcript-model')
expect(session?.createdAt).toBe('2026-05-01T10:00:00.000Z')
})
it('drops a session the user hid in Devin', async () => {
const dir = await tempDir('orca-devin-db-')
const cliDir = join(dir, 'cli')
const transcriptsDir = join(cliDir, 'transcripts')
await mkdir(transcriptsDir, { recursive: true })
const filePath = join(transcriptsDir, 'apricot.json')
const dbPath = join(cliDir, 'sessions.db')
writeDevinSessionsDb(dbPath, [{ id: 'apricot', hidden: 1 }])
const fold = devinFoldSession(filePath, {
session_id: 'apricot',
steps: []
})
const { session, refused } = await enrichSessionFromSidecar(
devinCandidate(filePath, await sidecarOf(dbPath)),
fold,
'linux'
)
expect(session).toBeNull()
expect(refused).toBe(false)
})
})
describe('devin sessions.db through the scan', () => {
@@ -411,27 +164,6 @@ describe('devin sessions.db through the scan', () => {
}
)
it('still lists sessions when sessions.db is absent', async () => {
const root = await tempDir('orca-devin-scan-')
const transcriptsDir = join(root, 'devin-cli', 'transcripts')
await mkdir(transcriptsDir, { recursive: true })
await writeFile(
join(transcriptsDir, 'bare.json'),
JSON.stringify({
session_id: 'bare',
working_directory: '/srv/bare',
steps: []
})
)
const result = await scanAiVaultSessions({
...isolatedScanRoots(root),
devinTranscriptsDir: transcriptsDir
})
const devin = result.sessions.filter((session) => session.agent === 'devin')
expect(devin.map((session) => session.sessionId)).toEqual(['bare'])
expect(devin[0]?.cwd).toBe('/srv/bare')
})
it('picks up db-only changes on a rescan without the transcript moving', async () => {
const root = await tempDir('orca-devin-scan-')
const { transcriptsDir, dbPath } = await writeDevinVault(root)
@@ -14,51 +14,6 @@ afterEach(async () => {
})
describe('parseDevinSessionFile', () => {
it.each([
{
payloadKind: 'message array',
fields: (text: string) => ({ message: [], content: [{ type: 'text', text }] })
},
{
payloadKind: 'wrapped content',
fields: (text: string) => ({ message: { content: '' }, text })
},
{
payloadKind: 'text',
fields: (text: string) => ({ text: '', content: [{ type: 'text', text }] })
}
])('falls back from empty $payloadKind without shortening content', async ({ fields }) => {
const dir = await mkdtemp(join(tmpdir(), 'orca-devin-fallback-'))
tempDirs.push(dir)
const path = join(dir, 'fallback.json')
const text = `actual request\n${'x'.repeat(5000)}`
await writeFile(
path,
JSON.stringify({
session_id: 'fallback',
steps: ['user', 'agent'].map((source) => ({
source,
...fields(text)
}))
})
)
const messages: TranscriptMessage[] = []
const session = await withFullFirstUserPromptCapture(() =>
parseDevinSessionFile({ path, mtimeMs: 1, modifiedAt: '2026-05-01T00:00:00.000Z' }, 'linux', {
active: true,
push: (message) => messages.push(message)
})
)
expect(messages).toEqual([
{ role: 'user', text, timestamp: null },
{ role: 'assistant', text, timestamp: null }
])
expect(session?.firstUserPrompt).toBe(text)
expect(session?.title).toMatch(/^actual request /)
expect(session?.previewMessages.map((message) => message.text.length)).toEqual([220, 220])
})
it.each(
[
{ payloadKind: 'string', fields: (text: string) => ({ message: text }) },
@@ -119,203 +74,4 @@ describe('parseDevinSessionFile', () => {
expect(session?.previewMessages.map((message) => message.text.length)).toEqual([220, 220])
}
)
it('parses minimal ATIF transcript fixture', async () => {
const dir = await mkdtemp(join(tmpdir(), 'orca-devin-parser-'))
tempDirs.push(dir)
const path = join(dir, 'abc.json')
const mtimeMs = Date.now()
await writeFile(
path,
JSON.stringify({
session_id: 'abc',
agent: { model_name: 'swe-1-6-fast' },
steps: [
{
metadata: {
created_at: '2026-01-01T00:00:00Z',
is_user_input: true,
metrics: { input_tokens: 1, output_tokens: 2 }
},
text: 'Hello Devin'
}
]
})
)
const session = await parseDevinSessionFile({
path,
mtimeMs,
modifiedAt: new Date(mtimeMs).toISOString()
})
expect(session).not.toBeNull()
expect(session?.sessionId).toBe('abc')
expect(session?.model).toBe('swe-1-6-fast')
expect(session?.totalTokens).toBe(3)
expect(session?.messageCount).toBe(1)
expect(session?.title).toBe('Hello Devin')
})
it('parses current ATIF token and model fields', async () => {
const dir = await mkdtemp(join(tmpdir(), 'orca-devin-parser-'))
tempDirs.push(dir)
const path = join(dir, 'current.json')
const mtimeMs = Date.now()
await writeFile(
path,
JSON.stringify({
session_id: 'current',
agent: {},
steps: [
{
role: 'assistant',
metadata: {
created_at: '2026-05-26T00:00:00Z',
generation_model: 'swe-1-6',
total_input_tokens: 10,
output_tokens: 4,
cache_read_tokens: 3,
cache_creation_tokens: 2
},
message: {
content: 'Done'
}
}
]
})
)
const session = await parseDevinSessionFile({
path,
mtimeMs,
modifiedAt: new Date(mtimeMs).toISOString()
})
expect(session?.model).toBe('swe-1-6')
expect(session?.totalTokens).toBe(19)
expect(session?.messageCount).toBe(1)
expect(session?.previewMessages[0]).toMatchObject({
role: 'assistant',
text: 'Done'
})
})
it('extracts text from an array-valued ATIF message', async () => {
const dir = await mkdtemp(join(tmpdir(), 'orca-devin-parser-'))
tempDirs.push(dir)
const path = join(dir, 'array-message.json')
const mtimeMs = Date.now()
await writeFile(
path,
JSON.stringify({
session_id: 'array-message',
agent: {},
steps: [
{
timestamp: '2026-05-26T00:00:00Z',
source: 'user',
message: [{ text: 'First part' }, { text: 'second part' }]
}
]
})
)
const session = await parseDevinSessionFile({
path,
mtimeMs,
modifiedAt: new Date(mtimeMs).toISOString()
})
expect(session?.messageCount).toBe(1)
expect(session?.title).toBe('First part second part')
expect(session?.previewMessages[0]).toMatchObject({
role: 'user',
text: 'First part second part'
})
})
it('parses a real ATIF-v1.7 transcript', async () => {
const dir = await mkdtemp(join(tmpdir(), 'orca-devin-parser-'))
tempDirs.push(dir)
const path = join(dir, 'apricot-houseboat.json')
const mtimeMs = Date.now()
await writeFile(
path,
JSON.stringify({
schema_version: 'ATIF-v1.7',
session_id: 'apricot-houseboat',
agent: {
name: 'devin',
version: '3000.10.27',
model_name: 'SWE-2 High',
tool_definitions: []
},
steps: [
{
step_id: 8,
timestamp: '2026-09-16T09:50:40.000000000+00:00',
source: 'system',
message: 'You are Devin, an AI software engineer.'
},
{
step_id: 9,
timestamp: '2026-09-16T09:50:55.745112900+00:00',
source: 'user',
message: 'fix toàn bộ các lỗi này đi',
extra: { telemetry: { source: 'user', operation: 'unknown' } }
},
{
step_id: 10,
timestamp: '2026-09-16T09:51:02.1+00:00',
source: 'agent',
message: '# Báo cáo\n\nĐã sửa xong.',
tool_calls: [],
model_name: 'swe-2-high',
metrics: { prompt_tokens: 174988, completion_tokens: 2061, cached_tokens: 170575 },
extra: {
generation_model: 'swe-2-high',
telemetry: { source: 'assistant', operation: 'inference' }
}
},
{
step_id: 11,
timestamp: '2026-09-16T09:51:30.0+00:00',
source: 'agent',
message: 'All checks pass.',
metrics: { prompt_tokens: 100, completion_tokens: 10, cached_tokens: 50 },
extra: { telemetry: { source: 'assistant', operation: 'inference' } }
}
],
final_metrics: {
total_prompt_tokens: 175088,
total_completion_tokens: 2071,
total_cached_tokens: 170625,
total_steps: 11
}
})
)
const session = await parseDevinSessionFile({
path,
mtimeMs,
modifiedAt: new Date(mtimeMs).toISOString()
})
expect(session).not.toBeNull()
expect(session?.sessionId).toBe('apricot-houseboat')
expect(session?.model).toBe('SWE-2 High')
expect(session?.title).toBe('fix toàn bộ các lỗi này đi')
expect(session?.messageCount).toBe(3)
// prompt + completion per step; cached_tokens is already inside prompt_tokens.
expect(session?.totalTokens).toBe(177159)
expect(session?.updatedAt).toBe('2026-09-16T09:51:30.000Z')
expect(session?.previewMessages.length).toBeGreaterThan(0)
for (const preview of session?.previewMessages ?? []) {
expect(['user', 'assistant']).toContain(preview.role)
expect(preview.text).toBeTruthy()
}
expect(session?.previewMessages.some((preview) => preview.role === 'user')).toBe(true)
expect(session?.previewMessages.some((preview) => preview.role === 'assistant')).toBe(true)
})
})
@@ -3,12 +3,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { parseKimiSessionFile } from './session-scanner-kimi-parser'
import {
clearKimiSessionIndexCache,
hasKimiSessionIndexCacheEntryForTests,
readKimiWorkDirBySessionId
} from './session-scanner-kimi-paths'
import { KIMI_WORK_DIR_CACHE_MAX_INDEX_PATHS } from './session-scanner-kimi-index-cache'
import { clearKimiSessionIndexCache } from './session-scanner-kimi-paths'
import type { FileWithMtime } from '../../session-scanner-types'
import type { TranscriptMessage } from '../../transcripts/session-transcript-consumers'
@@ -131,56 +126,6 @@ async function writeKimiSession(args: {
}
describe('parseKimiSessionFile', () => {
it('returns null for malformed state.json', async () => {
const { file } = await writeKimiSession({})
await writeFile(file.path, '{not-json')
await expect(parseKimiSessionFile(file, 'darwin')).resolves.toBeNull()
})
it('parses a full session from state.json + index + wire transcript', async () => {
const { file } = await writeKimiSession({})
const session = await parseKimiSessionFile(file, 'darwin')
expect(session).not.toBeNull()
expect(session?.agent).toBe('kimi')
expect(session?.sessionId).toBe(SESSION_ID)
expect(session?.title).toBe('Please explain this project briefly')
expect(session?.cwd).toBe('/private/tmp/kimi-test-proj')
expect(session?.model).toBe('mock-model')
expect(session?.totalTokens).toBe(30)
expect(session?.messageCount).toBe(2)
expect(session?.previewMessages).toEqual([
{ role: 'user', text: 'Please explain this project briefly', timestamp: null },
{ role: 'assistant', text: 'Hello! This is a mock response.', timestamp: null }
])
expect(session?.createdAt).toBe('2026-06-19T07:19:19.118Z')
expect(session?.updatedAt).toBe('2026-06-19T07:19:19.161Z')
})
it('builds a work-dir-scoped resume command', async () => {
const { file } = await writeKimiSession({})
const session = await parseKimiSessionFile(file, 'darwin')
expect(session?.resumeCommand).toBe(
`cd '/private/tmp/kimi-test-proj' && kimi --session '${SESSION_ID}'`
)
})
it('still lists a metadata-only session with no transcript yet', async () => {
const { file } = await writeKimiSession({ wireLines: null })
const session = await parseKimiSessionFile(file, 'darwin')
expect(session?.title).toBe('Please explain this project briefly')
expect(session?.messageCount).toBe(0)
expect(session?.model).toBeNull()
})
it('lists a session even when the index (work dir) is missing', async () => {
const { file } = await writeKimiSession({ workDir: null })
const session = await parseKimiSessionFile(file, 'darwin')
expect(session?.cwd).toBeNull()
expect(session?.resumeCommand).toBe(`kimi --session '${SESSION_ID}'`)
})
it.each([300, 256 * 1024 + 1])(
'publishes %i-character Kimi turns independently of the preview cap',
async (length) => {
@@ -225,49 +170,4 @@ describe('parseKimiSessionFile', () => {
)
}
)
it('falls back to lastPrompt when the title is empty', async () => {
const { file } = await writeKimiSession({
state: {
createdAt: '2026-06-19T07:19:19.118Z',
updatedAt: '2026-06-19T07:19:19.161Z',
title: '',
lastPrompt: 'do the thing',
agents: {}
},
wireLines: []
})
const session = await parseKimiSessionFile(file, 'darwin')
expect(session?.title).toBe('do the thing')
})
it('caps cached session index maps by recent index path', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-kimi-cache-'))
tempDirs.push(root)
const indexPaths: string[] = []
for (let index = 0; index <= KIMI_WORK_DIR_CACHE_MAX_INDEX_PATHS; index += 1) {
const home = join(root, `home-${index}`)
await mkdir(home, { recursive: true })
const indexPath = join(home, 'session_index.jsonl')
await writeFile(
indexPath,
`${JSON.stringify({ sessionId: `session_${index}`, workDir: `/tmp/kimi-${index}` })}\n`
)
indexPaths.push(indexPath)
}
for (const indexPath of indexPaths.slice(0, KIMI_WORK_DIR_CACHE_MAX_INDEX_PATHS)) {
await readKimiWorkDirBySessionId(indexPath)
}
const refreshedFirst = await readKimiWorkDirBySessionId(indexPaths[0])
expect(refreshedFirst.get('session_0')).toBe('/tmp/kimi-0')
await readKimiWorkDirBySessionId(indexPaths[KIMI_WORK_DIR_CACHE_MAX_INDEX_PATHS])
expect(hasKimiSessionIndexCacheEntryForTests(indexPaths[0])).toBe(true)
expect(hasKimiSessionIndexCacheEntryForTests(indexPaths[1])).toBe(false)
expect(
hasKimiSessionIndexCacheEntryForTests(indexPaths[KIMI_WORK_DIR_CACHE_MAX_INDEX_PATHS])
).toBe(true)
})
})
@@ -2,7 +2,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { NODE_RUNTIME_ASSETS } from '../../../../../shared/node-runtime-pin'
import { runProcess } from '@orca/process-host'
import type * as preparationModule from './opencode-wsl-runtime-preparation'
@@ -72,69 +71,6 @@ async function prepared() {
}
describe('WSL SQLite runtime preparation', () => {
it('returns immediately, coalesces distro aliases, and requests the guest SQLite probe', async () => {
let release: (value: ReturnType<typeof success>) => void = () => {}
mocks.run.mockReturnValueOnce(
new Promise((resolve) => {
release = resolve
})
)
expect(await prepare([home, String.raw`\\wsl$\ubuntu\home\ada`])).toHaveLength(1)
await vi.waitFor(() => expect(mocks.run).toHaveBeenCalledOnce())
expect((await prepare([home]))[0]?.error).toContain('Preparing')
expect(mocks.run).toHaveBeenCalledOnce()
release(success('present'))
expect(await prepared()).toEqual([
{ distro: 'ubuntu', executable: '/usr/bin/node', readerPath: '/mnt/c/reader.cjs' }
])
expect(mocks.run).toHaveBeenCalledWith(
expect.objectContaining({
program: 'node',
loginPath: 'preferred',
args: ['-e', expect.stringMatching(/require\('node:sqlite'\).*backup/)]
})
)
expect(mocks.bundles.mock.calls.map(([platform]) => platform)).toEqual(['wsl'])
expect(mocks.download).not.toHaveBeenCalled()
})
it('does not start a stopped distro and retries a failed preparation after cooldown', async () => {
let now = 10_000
vi.spyOn(Date, 'now').mockImplementation(() => now)
mocks.running.mockResolvedValue([])
await prepare([home])
await vi.waitFor(async () => expect((await prepare([home]))[0]?.error).toContain('not running'))
expect(mocks.run).not.toHaveBeenCalled()
mocks.running.mockImplementation(async (paths) => [...paths])
expect((await prepare([home]))[0]?.error).toContain('not running')
now += 30_001
expect((await prepared())[0]?.executable).toBe('/usr/bin/node')
})
it('keeps a working reader during revalidation and prunes completed removed distros', async () => {
let now = 10_000
vi.spyOn(Date, 'now').mockImplementation(() => now)
const ready = await prepared()
now += 600_001
let release: (value: ReturnType<typeof success>) => void = () => {}
mocks.run.mockReturnValueOnce(
new Promise((resolve) => {
release = resolve
})
)
expect(await prepare([home])).toEqual(ready)
await vi.waitFor(() => expect(mocks.run).toHaveBeenCalledTimes(4))
expect(await prepare([home])).toEqual(ready)
mocks.run.mockResolvedValueOnce(success('/mnt/c/repaired-reader.cjs'))
release(success('present'))
await vi.waitFor(async () =>
expect((await prepare([home]))[0]?.readerPath).toBe('/mnt/c/repaired-reader.cjs')
)
expect(await prepare([])).toEqual([])
expect((await prepare([home]))[0]?.error).toContain('Preparing')
await prepared()
})
it('checks the generated SQLite probe against missing API and stderr warnings locally', async () => {
await prepared()
const probe = mocks.run.mock.calls.find(([spec]) => spec.program === 'node')?.[0]
@@ -168,122 +104,6 @@ describe('WSL SQLite runtime preparation', () => {
}
})
it('requests pinned runtime verification and preserves literal argv', async () => {
const expected = NODE_RUNTIME_ASSETS['linux-arm64-musl'].executableSha256
mocks.run.mockImplementation(async (spec) => {
if (spec.script?.startsWith('data=')) {
return success('present')
}
if (spec.program === 'node') {
return { ...success(''), code: 1, stderr: 'no sqlite' }
}
if (spec.program === 'uname') {
return success('aarch64')
}
if (spec.program === 'wslpath') {
return success(
`/mnt/c/${spec.args.at(-1).includes('.tar.gz') ? 'node $literal.tar.gz' : 'reader $literal.cjs'}`
)
}
if (
spec.script?.includes('getconf GNU_LIBC_VERSION') ||
spec.script?.includes('ldd --version')
) {
return success('')
}
if (spec.script?.includes('/lib/ld-musl-')) {
return success('musl libc (aarch64)\nVersion 1.2.5')
}
if (spec.script?.startsWith('printf')) {
return success('/home/ada $literal')
}
if (spec.script?.includes('ORCA_NODE_RUNTIME_EXTRACT_FAILED')) {
return success('ORCA_NODE_RUNTIME_READY')
}
return success(
spec.script?.includes('ORCA_NODE_RUNTIME_MISSING') ? 'ORCA_NODE_RUNTIME_MISSING' : ''
)
})
const result = await prepared()
expect(mocks.download).toHaveBeenCalledWith(
'linux-arm64-musl',
expect.any(String),
expect.objectContaining({ signal: expect.any(AbortSignal) })
)
expect(result[0]).toEqual({
distro: 'Ubuntu',
executable: `/home/ada $literal/.cache/orca/runtimes/node-${expected}/bin/node`,
readerPath: '/mnt/c/reader $literal.cjs'
})
const install = mocks.run.mock.calls
.map(([spec]) => spec)
.find((spec) => spec.script?.includes('ORCA_NODE_RUNTIME_EXTRACT_FAILED'))
expect(install).toMatchObject({ args: ['/mnt/c/node $literal.tar.gz'], loginPath: 'none' })
expect(install.script).toContain(expected)
expect(install.timeoutMs).toBeLessThanOrEqual(120_000)
expect(
mocks.run.mock.calls.every(
([spec]) => (spec === install || spec.timeoutMs <= 15_000) && spec.maxOutputBytes === 16_384
)
).toBe(true)
})
it('rechecks running state after downloading before it copies a runtime', async () => {
mocks.run.mockImplementation(async (spec) => {
if (spec.script?.startsWith('data=')) {
return success('present')
}
if (spec.program === 'node') {
return { ...success(''), code: 1 }
}
if (spec.program === 'uname') {
return success('x86_64')
}
if (spec.program === 'wslpath') {
return success('/mnt/c/reader.cjs')
}
if (spec.script?.includes('getconf GNU_LIBC_VERSION')) {
return success('glibc 2.31')
}
if (spec.script?.startsWith('printf')) {
return success('/home/ada')
}
return success('')
})
mocks.download.mockImplementationOnce(async () => {
mocks.running.mockResolvedValue([])
return 'C:\\cache\\node.tar.gz'
})
await prepare([home])
await vi.waitFor(async () => expect((await prepare([home]))[0]?.error).toContain('not running'))
expect(mocks.download).toHaveBeenCalledOnce()
expect(mocks.run.mock.calls.some(([spec]) => spec.script?.includes('mv -f'))).toBe(false)
})
it('ignores native roots and does no work outside Windows', async () => {
expect(await prepare(['C:\\Users\\ada'])).toEqual([])
vi.spyOn(process, 'platform', 'get').mockReturnValue('linux')
expect(await prepare([home])).toEqual([])
expect(mocks.run).not.toHaveBeenCalled()
})
it('skips runtime setup without a database and rechecks soon after OpenCode starts', async () => {
let now = 10_000
vi.spyOn(Date, 'now').mockImplementation(() => now)
mocks.run.mockResolvedValueOnce(success(''))
await prepare([home])
await vi.waitFor(async () =>
expect((await prepare([home]))[0]?.error).toContain('No OpenCode or ZCode database')
)
expect(mocks.run).toHaveBeenCalledOnce()
expect(mocks.download).not.toHaveBeenCalled()
expect(mocks.run.mock.calls[0]?.[0].script).toContain('OPENCODE_DB')
expect(mocks.run.mock.calls[0]?.[0].script).toContain('XDG_DATA_HOME')
now += 30_001
expect((await prepared())[0]?.executable).toBe('/usr/bin/node')
expect(mocks.running).toHaveBeenCalledWith(expect.any(Array), { requireConfirmed: true })
})
it.skipIf(process.platform === 'win32').each(['opencode', 'zcode'] as const)(
'presence script finds %s-only data despite unrelated OpenCode overrides',
async (agent) => {
@@ -245,36 +245,4 @@ describe('OpenCode SQLite process retirement', () => {
})
// A WSL reader dies with its distro; the client reports that so the respawn re-checks the distro.
it('reports an unexpected child exit, but not its own retirement', async () => {
const onUnexpectedExit = vi.fn()
const dying = createOpenCodeSqliteProcessClient({
executable,
args: ['-e', 'process.exit(3)'],
onUnexpectedExit
})
try {
await dying.list({ dbPaths: [dbPath], limit: 1, issues: [] })
await vi.waitFor(() => expect(onUnexpectedExit).toHaveBeenCalled())
} finally {
dying.dispose()
}
const spawn = vi.spyOn(processRunner, 'spawnProcess')
const retiredExit = vi.fn()
const healthy = createOpenCodeSqliteProcessClient({
executable,
args: [entry],
onUnexpectedExit: retiredExit
})
try {
await healthy.list({ dbPaths: [dbPath], limit: 1, issues: [] })
const child = spawn.mock.results[0]?.value
const exited = new Promise((resolve) => child?.once('exit', resolve))
healthy.dispose()
await exited
expect(retiredExit).not.toHaveBeenCalled()
} finally {
spawn.mockRestore()
}
})
})
@@ -1,404 +0,0 @@
import type { Worker } from 'node:worker_threads'
import { describe, expect, it, vi } from 'vitest'
import {
IDLE_TEARDOWN_MS,
LIST_TIMEOUT_MS,
MAX_CONSECUTIVE_DEATHS,
OpenCodeSqliteWorkerClient,
PARSE_TIMEOUT_MS
} from './session-scanner-opencode-sqlite-worker-client'
import type {
OpenCodeSqliteWorkerRequest,
OpenCodeSqliteWorkerResponse
} from './session-scanner-opencode-sqlite-worker-protocol'
import type { AiVaultScanIssue } from '../../../../../shared/ai-vault/contracts/ai-vault-types'
import { withOpenCodeSqliteScanScope } from '../sqlite/session-scanner-opencode-sqlite-scan-scope'
class FakeWorker {
postedRequests: OpenCodeSqliteWorkerRequest[] = []
terminated = false
unrefed = false
private listeners = new Map<string, Set<(arg?: unknown) => void>>()
on(event: string, listener: (arg?: unknown) => void): this {
const set = this.listeners.get(event) ?? new Set()
set.add(listener)
this.listeners.set(event, set)
return this
}
off(event: string, listener: (arg?: unknown) => void): this {
this.listeners.get(event)?.delete(listener)
return this
}
removeAllListeners(): void {
this.listeners.clear()
}
unref(): void {
this.unrefed = true
}
async terminate(): Promise<number> {
this.terminated = true
return 1
}
postMessage(request: OpenCodeSqliteWorkerRequest): void {
this.postedRequests.push(request)
}
emit(event: string, arg?: unknown): void {
// Copy first: the client removes its listeners synchronously during a fault.
for (const listener of Array.from(this.listeners.get(event) ?? [])) {
listener(arg)
}
}
lastId(): number {
const last = this.postedRequests.at(-1)
if (!last) {
throw new Error('no request posted to fake worker')
}
return last.id
}
}
function makeFactory(workers: FakeWorker[]): () => Worker {
return () => {
const worker = new FakeWorker()
workers.push(worker)
return worker as unknown as Worker
}
}
describe('OpenCodeSqliteWorkerClient', () => {
it('expires a scan in the FIFO without cancelling ordinary reads or a later scan', async () => {
vi.useFakeTimers()
const workers: FakeWorker[] = []
const client = new OpenCodeSqliteWorkerClient({ workerFactory: makeFactory(workers), log() {} })
const issues: AiVaultScanIssue[] = []
try {
const ordinary = [1, 2].map((id) =>
client.list({
dbPaths: [`/ordinary-${id}.db`],
limit: 1,
issues: []
})
)
const scan = withOpenCodeSqliteScanScope(() =>
client.list({
dbPaths: ['/scan.db'],
limit: 1,
issues
})
)
await vi.advanceTimersByTimeAsync(25_000)
workers[0].emit('message', {
id: workers[0].lastId(),
ok: true,
value: { candidates: [], issues: [] }
})
await vi.advanceTimersByTimeAsync(20_000)
await expect(scan).resolves.toEqual([])
expect(issues).toEqual([
expect.objectContaining({
kind: 'scope',
message: expect.stringContaining('45s work budget')
})
])
expect(workers[0].postedRequests).toHaveLength(2)
expect(workers[0].terminated).toBe(false)
workers[0].emit('message', {
id: workers[0].lastId(),
ok: true,
value: { candidates: [], issues: [] }
})
await expect(Promise.all(ordinary)).resolves.toEqual([[], []])
const next = withOpenCodeSqliteScanScope(() =>
client.list({ dbPaths: ['/next.db'], limit: 1, issues: [] })
)
workers[0].emit('message', {
id: workers[0].lastId(),
ok: true,
value: { candidates: [], issues: [] }
})
await expect(next).resolves.toEqual([])
} finally {
client.dispose()
vi.useRealTimers()
}
})
it('correlates responses by id and ignores stale ids', async () => {
const workers: FakeWorker[] = []
const client = new OpenCodeSqliteWorkerClient({ workerFactory: makeFactory(workers), log() {} })
const parsePromise = client.parse({ dbPath: '/db#a', sessionId: 'a', platform: 'darwin' })
const worker = workers[0]
expect(worker).toBeDefined()
expect(worker!.unrefed).toBe(true)
worker!.emit('message', {
id: 999,
ok: true,
value: null
} satisfies OpenCodeSqliteWorkerResponse)
worker!.emit('message', {
id: worker!.lastId(),
ok: true,
value: { sessionId: 'a' }
} satisfies OpenCodeSqliteWorkerResponse)
await expect(parsePromise).resolves.toEqual({ sessionId: 'a' })
})
it('dispatches one request at a time in FIFO order', async () => {
const workers: FakeWorker[] = []
const client = new OpenCodeSqliteWorkerClient({ workerFactory: makeFactory(workers), log() {} })
const first = client.parse({ dbPath: '/db#a', sessionId: 'a', platform: 'darwin' })
const second = client.parse({ dbPath: '/db#b', sessionId: 'b', platform: 'darwin' })
const worker = workers[0]!
expect(worker.postedRequests).toHaveLength(1)
expect(worker.postedRequests[0]).toMatchObject({ kind: 'parse', sessionId: 'a' })
worker.emit('message', { id: worker.postedRequests[0]!.id, ok: true, value: 'A' })
await first
expect(worker.postedRequests).toHaveLength(2)
expect(worker.postedRequests[1]).toMatchObject({ kind: 'parse', sessionId: 'b' })
worker.emit('message', { id: worker.postedRequests[1]!.id, ok: true, value: 'B' })
await expect(second).resolves.toBe('B')
expect(workers).toHaveLength(1)
})
it('times out only the active call, then respawns and drains the queue', async () => {
vi.useFakeTimers()
try {
const workers: FakeWorker[] = []
const client = new OpenCodeSqliteWorkerClient({
workerFactory: makeFactory(workers),
log() {}
})
const active = client.parse({ dbPath: '/db#a', sessionId: 'a', platform: 'darwin' })
const queued = client.parse({ dbPath: '/db#b', sessionId: 'b', platform: 'darwin' })
const activeAssertion = expect(active).rejects.toThrow(
`OpenCode SQLite worker timed out after ${PARSE_TIMEOUT_MS}ms`
)
// Queued calls must not spend their timeout before dispatch.
await vi.advanceTimersByTimeAsync(PARSE_TIMEOUT_MS)
await activeAssertion
expect(workers).toHaveLength(2)
const respawned = workers[1]!
expect(respawned.postedRequests).toHaveLength(1)
expect(respawned.postedRequests[0]).toMatchObject({ sessionId: 'b' })
respawned.emit('message', { id: respawned.lastId(), ok: true, value: 'B' })
await expect(queued).resolves.toBe('B')
} finally {
vi.useRealTimers()
}
})
it('rejects only the active call on a worker crash and respawns for the queue', async () => {
const workers: FakeWorker[] = []
const client = new OpenCodeSqliteWorkerClient({ workerFactory: makeFactory(workers), log() {} })
const active = client.parse({ dbPath: '/db#a', sessionId: 'a', platform: 'darwin' })
const queued = client.parse({ dbPath: '/db#b', sessionId: 'b', platform: 'darwin' })
const activeAssertion = expect(active).rejects.toThrow(
'OpenCode SQLite worker exited with code 1'
)
workers[0]!.emit('exit', 1)
await activeAssertion
expect(workers[0]!.terminated).toBe(true)
expect(workers).toHaveLength(2)
const respawned = workers[1]!
respawned.emit('message', { id: respawned.lastId(), ok: true, value: 'B' })
await expect(queued).resolves.toBe('B')
})
it('fails closed instead of running SQLite on the main thread when spawn fails', async () => {
const client = new OpenCodeSqliteWorkerClient({
workerFactory() {
throw new Error('no worker bundle')
},
log() {}
})
const listIssues: AiVaultScanIssue[] = []
await expect(
client.list({ dbPaths: ['/tmp/opencode.db'], limit: 10, issues: listIssues })
).resolves.toEqual([])
expect(
listIssues.some((issue) => issue.message.includes('background scanner could not start'))
).toBe(true)
await expect(
client.parse({ dbPath: '/tmp/opencode.db', sessionId: 'ses_skipped', platform: 'darwin' })
).rejects.toThrow(/background scanner could not start/)
})
it('stops respawning after the consecutive-death cap and fails the rest to issues', async () => {
const workers: FakeWorker[] = []
const client = new OpenCodeSqliteWorkerClient({ workerFactory: makeFactory(workers), log() {} })
const pending = Array.from({ length: MAX_CONSECUTIVE_DEATHS + 2 }, (_, i) =>
client.parse({ dbPath: `/db#${i}`, sessionId: `s${i}`, platform: 'darwin' })
)
// Preserve the final crash reason when failing the remaining queue.
const settled = pending.map((promise) => expect(promise).rejects.toThrow(/crash \d/))
for (let i = 0; i < MAX_CONSECUTIVE_DEATHS; i++) {
expect(workers[i]).toBeDefined()
workers[i]!.emit('error', new Error(`crash ${i}`))
}
await Promise.all(settled)
expect(workers).toHaveLength(MAX_CONSECUTIVE_DEATHS)
})
it('surfaces a list-leg timeout as a scan issue and returns no candidates', async () => {
vi.useFakeTimers()
try {
const workers: FakeWorker[] = []
const client = new OpenCodeSqliteWorkerClient({
workerFactory: makeFactory(workers),
log() {}
})
const issues: AiVaultScanIssue[] = []
const listPromise = client.list({
dbPaths: ['/tmp/opencode.db'],
limit: 10,
issues
})
await vi.advanceTimersByTimeAsync(LIST_TIMEOUT_MS)
await expect(listPromise).resolves.toEqual([])
expect(issues).toHaveLength(1)
expect(issues[0]!.agent).toBe('opencode')
expect(issues[0]!.message).toMatch(/did not complete/)
} finally {
vi.useRealTimers()
}
})
it('self-heals after repeated spawn failures instead of latching unavailable', async () => {
const workers: FakeWorker[] = []
let failSpawns = true
const client = new OpenCodeSqliteWorkerClient({
workerFactory() {
if (failSpawns) {
throw new Error('spawn down')
}
const worker = new FakeWorker()
workers.push(worker)
return worker as unknown as Worker
},
log() {}
})
// A missing worker must fail closed for this scan without latching failure across future scans.
const firstIssues: AiVaultScanIssue[] = []
const first = await client.list({ dbPaths: ['/db'], limit: 10, issues: firstIssues })
expect(first).toEqual([])
expect(
firstIssues.some((issue) => issue.message.includes('background scanner could not start'))
).toBe(true)
await expect(
client.parse({ dbPath: '/db', sessionId: 'ses_heal', platform: 'darwin' })
).rejects.toThrow(/background scanner could not start/)
expect(workers).toHaveLength(0)
failSpawns = false
const secondIssues: AiVaultScanIssue[] = []
const secondPromise = client.list({ dbPaths: ['/db'], limit: 10, issues: secondIssues })
const worker = workers[0]
expect(worker).toBeDefined()
worker!.emit('message', {
id: worker!.lastId(),
ok: true,
value: { candidates: [], issues: [] }
} satisfies OpenCodeSqliteWorkerResponse)
await expect(secondPromise).resolves.toEqual([])
expect(secondIssues).toHaveLength(0)
})
it('drops a cleanly exited idle worker and respawns on the next request', async () => {
const workers: FakeWorker[] = []
const client = new OpenCodeSqliteWorkerClient({ workerFactory: makeFactory(workers), log() {} })
const first = client.parse({ dbPath: '/db#a', sessionId: 'a', platform: 'darwin' })
workers[0]!.emit('message', { id: workers[0]!.lastId(), ok: true, value: 'A' })
await expect(first).resolves.toBe('A')
workers[0]!.emit('exit', 0)
const second = client.parse({ dbPath: '/db#b', sessionId: 'b', platform: 'darwin' })
expect(workers).toHaveLength(2)
workers[1]!.emit('message', { id: workers[1]!.lastId(), ok: true, value: 'B' })
await expect(second).resolves.toBe('B')
})
it('terminates an idle worker and respawns on later work', async () => {
vi.useFakeTimers()
try {
const workers: FakeWorker[] = []
const client = new OpenCodeSqliteWorkerClient({
workerFactory: makeFactory(workers),
log() {}
})
const first = client.parse({ dbPath: '/db#a', sessionId: 'a', platform: 'darwin' })
workers[0]!.emit('message', { id: workers[0]!.lastId(), ok: true, value: 'A' })
await expect(first).resolves.toBe('A')
await vi.advanceTimersByTimeAsync(IDLE_TEARDOWN_MS)
expect(workers[0]!.terminated).toBe(true)
const second = client.parse({ dbPath: '/db#b', sessionId: 'b', platform: 'darwin' })
expect(workers).toHaveLength(2)
workers[1]!.emit('message', { id: workers[1]!.lastId(), ok: true, value: 'B' })
await expect(second).resolves.toBe('B')
} finally {
vi.useRealTimers()
}
})
it('does not carry a worker death from a prior burst into the next scan cap', async () => {
const workers: FakeWorker[] = []
const client = new OpenCodeSqliteWorkerClient({ workerFactory: makeFactory(workers), log() {} })
// End the first burst after one death without a successful response to reset the counter.
const first = client.parse({ dbPath: '/db#a', sessionId: 'a', platform: 'darwin' })
const firstAssertion = expect(first).rejects.toThrow(/exited with code/)
workers[0]!.emit('exit', 1)
await firstAssertion
// A fresh idle-to-active burst gets the full death budget despite the earlier failed burst.
const pending = Array.from({ length: MAX_CONSECUTIVE_DEATHS }, (_, i) =>
client.parse({ dbPath: `/db#b${i}`, sessionId: `b${i}`, platform: 'darwin' })
)
const settled = pending.map((promise) => expect(promise).rejects.toThrow())
for (let i = 0; i < MAX_CONSECUTIVE_DEATHS; i++) {
workers.at(-1)!.emit('error', new Error(`b-crash ${i}`))
}
await Promise.all(settled)
expect(workers).toHaveLength(1 + MAX_CONSECUTIVE_DEATHS)
})
it('reuses the warm worker across a burst without respawning', async () => {
const workers: FakeWorker[] = []
const client = new OpenCodeSqliteWorkerClient({ workerFactory: makeFactory(workers), log() {} })
for (let i = 0; i < 3; i++) {
const promise = client.parse({ dbPath: `/db#${i}`, sessionId: `s${i}`, platform: 'darwin' })
const worker = workers[0]!
worker.emit('message', { id: worker.lastId(), ok: true, value: `v${i}` })
await expect(promise).resolves.toBe(`v${i}`)
}
expect(workers).toHaveLength(1)
})
})
@@ -116,37 +116,6 @@ function insertMessageWithPart(
}
describe('listOpenCodeSqliteSessions — LIMIT-first discovery', () => {
it('returns only the newest `limit` sessions by time_updated', async () => {
const { db, path } = createTempDb()
applySchema(db)
for (let i = 0; i < 5; i++) {
insertSession(db, `ses_${i}`, 1_777_634_000_000 + i * 1000)
}
db.close()
const candidates = await listOpenCodeSqliteSessions({ dbPaths: [path], limit: 2, issues: [] })
expect(candidates.map((c) => c.file.path)).toEqual([
buildOpenCodeSqliteCandidatePath(path, 'ses_4'),
buildOpenCodeSqliteCandidatePath(path, 'ses_3')
])
})
it('omits the SQL limit for an Unlimited scan', async () => {
const { db, path } = createTempDb()
applySchema(db)
for (let i = 0; i < 5; i++) {
insertSession(db, `ses_${i}`, 1_777_634_000_000 + i * 1000)
}
db.close()
const candidates = await listOpenCodeSqliteSessions({
dbPaths: [path],
limit: Number.POSITIVE_INFINITY,
issues: []
})
expect(candidates).toHaveLength(5)
})
it('uses time_created recency when time_updated is not positive', async () => {
const { db, path } = createTempDb()
applySchema(db)
@@ -6,11 +6,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import type { AiVaultScanIssue } from '../../../../../shared/ai-vault/contracts/ai-vault-types'
import Database from '../../../../sqlite/sync-database'
import { listOpenCodeSqliteSessions } from './session-scanner-opencode-sqlite-list'
import {
openCodeBusyTimeoutMs,
openCodeDatabaseScanIssue,
readOpenCodeDatabase
} from './session-scanner-opencode-sqlite-open'
import { readOpenCodeDatabase } from './session-scanner-opencode-sqlite-open'
// A writer lock previously failed immediately and emptied both scan scopes (#15036).
@@ -178,25 +174,6 @@ describe('readOpenCodeDatabase', () => {
}
})
it('preserves the setup error when closing also fails', () => {
const path = seededDatabase('opencode.db', 'session-a')
const setupError = new Error('query_only setup failed')
const closeError = new Error('close failed')
const originalClose = Database.prototype.close
vi.spyOn(Database.prototype, 'pragma').mockImplementationOnce(() => {
throw setupError
})
vi.spyOn(Database.prototype, 'close').mockImplementationOnce(function (this: Database) {
originalClose.call(this)
throw closeError
})
const read = vi.fn()
expect(() => readOpenCodeDatabase({ dbPath: path, read })).toThrow(setupError)
expect(Database.prototype.close).toHaveBeenCalledOnce()
expect(read).not.toHaveBeenCalled()
})
it('keeps the query-only guard enabled for successful reads', () => {
const path = seededDatabase('opencode.db', 'session-a')
readOpenCodeDatabase({
@@ -225,68 +202,3 @@ describe('readOpenCodeDatabase', () => {
expect(() => captured!.prepare('SELECT 1')).toThrow(/not open/i)
})
})
describe('openCodeBusyTimeoutMs', () => {
// WSL-share lock failures persist across timeouts; observed waits can also exceed the requested duration.
it('does not wait on a share where the wait provably cannot succeed', () => {
expect(openCodeBusyTimeoutMs('\\\\wsl.localhost\\Ubuntu\\home\\ada\\opencode.db')).toBe(0)
expect(openCodeBusyTimeoutMs('\\\\wsl$\\Ubuntu\\home\\ada\\opencode.db')).toBe(0)
})
it('still waits on a path where a writer really can be holding the lock', () => {
expect(openCodeBusyTimeoutMs('C:\\Users\\ada\\opencode.db')).toBe(1_500)
expect(openCodeBusyTimeoutMs('/home/ada/.local/share/opencode/opencode.db')).toBe(1_500)
})
})
describe('openCodeDatabaseScanIssue', () => {
const cantOpen = Object.assign(new Error('unable to open database file'), { errcode: 14 })
it('states the WSL share as a known limitation rather than an error to act on', () => {
const dbPath = '\\\\wsl.localhost\\Ubuntu\\home\\ada\\.local\\share\\opencode\\opencode.db'
const issue = openCodeDatabaseScanIssue(dbPath, cantOpen)
expect(issue.kind).toBe('scope')
expect(issue.path).toBe(dbPath)
expect(issue.message).toBe("OpenCode sessions inside WSL can't be searched from Windows yet.")
// Checkpointing cannot fix WSL-share locking; the diagnostic must not suggest flushing the WAL.
expect(issue.message).not.toContain('write-ahead log')
})
it('keeps the advice generic for a non-WSL path', () => {
const issue = openCodeDatabaseScanIssue('/home/ada/.local/share/opencode/opencode.db', cantOpen)
expect(issue.message).not.toContain('wsl.localhost')
expect(issue.message).toContain('write-ahead log')
})
// Real WSL-share reads fail even for idle non-WAL databases whose bytes open successfully on local disk.
it('does not blame a live writer for a lock-family error over a WSL share', () => {
const busy = Object.assign(new Error('database is locked'), { errcode: 5 })
const issue = openCodeDatabaseScanIssue(
'\\\\wsl.localhost\\Ubuntu\\home\\ada\\.local\\share\\opencode\\opencode.db',
busy
)
expect(issue.message).not.toContain('is writing to')
expect(issue.message).toBe("OpenCode sessions inside WSL can't be searched from Windows yet.")
})
it('still blames a live writer for the same error on a local path', () => {
const busy = Object.assign(new Error('database is locked'), { errcode: 5 })
const issue = openCodeDatabaseScanIssue('/home/ada/.local/share/opencode/opencode.db', busy)
expect(issue.message).toContain('is writing to')
})
it('reports anything else with its underlying cause', () => {
const issue = openCodeDatabaseScanIssue(
'/home/ada/.local/share/opencode/opencode.db',
Object.assign(new Error('database disk image is malformed'), { errcode: 11 })
)
expect(issue.kind).toBe('scope')
expect(issue.message).not.toContain('write-ahead log')
expect(issue.message).toContain('database disk image is malformed')
})
})
@@ -191,37 +191,6 @@ function insertPart(
).run(args.id, args.messageId, args.sessionId, args.timeCreated, args.timeCreated, data)
}
describe('listOpenCodeSqliteSessions', () => {
it('returns candidates sorted by time_updated desc via the synthesized mtimeMs', async () => {
const { db, path } = createTempDb()
applyOpenCodeSchema(db)
insertSession(db, {
id: 'ses_old',
title: 'Old',
timeCreated: 1_777_634_000_000,
timeUpdated: 1_777_634_001_000
})
insertSession(db, {
id: 'ses_new',
title: 'New',
timeCreated: 1_777_634_002_000,
timeUpdated: 1_777_634_003_000
})
db.close()
const issues: AiVaultScanIssue[] = []
const candidates = await listOpenCodeSqliteSessions({
dbPaths: [path],
limit: 10,
issues
})
expect(issues).toEqual([])
expect(candidates).toHaveLength(2)
expect(candidates[0].agent).toBe('opencode')
expect(candidates[0].file.mtimeMs).toBe(1_777_634_003_000)
expect(candidates[0].file.path).toBe(buildOpenCodeSqliteCandidatePath(path, 'ses_new'))
expect(candidates[1].file.path).toBe(buildOpenCodeSqliteCandidatePath(path, 'ses_old'))
})
it('lists in-scope sessions past a newer out-of-scope one when scoped', async () => {
const { db, path } = createTempDb()
applyOpenCodeSchema(db)
@@ -311,31 +280,6 @@ describe('listOpenCodeSqliteSessions', () => {
])
})
it('returns [] when the session table is missing (legacy install)', async () => {
const { db, path } = createTempDb()
db.exec('CREATE TABLE other (id TEXT)')
db.close()
const candidates = await listOpenCodeSqliteSessions({
dbPaths: [path],
limit: 10,
issues: []
})
expect(candidates).toEqual([])
})
it('records an issue when the DB file does not exist', async () => {
const issues: AiVaultScanIssue[] = []
const candidates = await listOpenCodeSqliteSessions({
dbPaths: ['/nonexistent/opencode.db'],
limit: 10,
issues
})
expect(candidates).toEqual([])
expect(issues).toHaveLength(1)
expect(issues[0].agent).toBe('opencode')
expect(issues[0].path).toBe('/nonexistent/opencode.db')
})
it('lists sessions from a minimal readable session table', async () => {
const { db, path } = createTempDb()
applyMinimalOpenCodeSchema(db)
@@ -355,137 +299,6 @@ describe('listOpenCodeSqliteSessions', () => {
})
describe('parseOpenCodeSqliteSession', () => {
it('builds an AiVaultSession with title, cwd, model, tokens, and resume command', async () => {
const { db, path } = createTempDb()
applyOpenCodeSchema(db)
insertSession(db, {
id: 'ses_1',
title: 'OpenCode title',
directory: '/tmp/opencode',
timeCreated: 1_777_634_000_000,
timeUpdated: 1_777_634_001_000,
tokensInput: 100,
tokensOutput: 40,
tokensReasoning: 10,
tokensCacheRead: 5,
cost: 0.01
})
insertMessage(db, {
id: 'msg_1',
sessionId: 'ses_1',
role: 'user',
timeCreated: 1_777_634_000_500,
summaryTitle: 'OpenCode title'
})
insertPart(db, {
id: 'prt_1',
messageId: 'msg_1',
sessionId: 'ses_1',
timeCreated: 1_777_634_000_500,
text: 'Plan the work'
})
insertMessage(db, {
id: 'msg_2',
sessionId: 'ses_1',
role: 'assistant',
timeCreated: 1_777_634_000_900
})
insertPart(db, {
id: 'prt_2',
messageId: 'msg_2',
sessionId: 'ses_1',
timeCreated: 1_777_634_001_000,
text: 'Done'
})
db.close()
const session = await parseOpenCodeSqliteSession({
dbPath: path,
sessionId: 'ses_1',
platform: 'darwin'
})
expect(session).not.toBeNull()
expect(session!.agent).toBe('opencode')
expect(session!.sessionId).toBe('ses_1')
expect(session!.filePath).toBe(path)
expect(session!.title).toBe('OpenCode title')
expect(session!.cwd).toBe('/tmp/opencode')
expect(session!.model).toBe('glm-5.2')
expect(session!.totalTokens).toBe(150)
expect(session!.messageCount).toBe(2)
expect(session!.createdAt).toBe(new Date(1_777_634_000_000).toISOString())
expect(session!.updatedAt).toBe(new Date(1_777_634_001_000).toISOString())
expect(session!.resumeCommand).toBe("cd '/tmp/opencode' && opencode --session 'ses_1'")
expect(session!.previewMessages).toHaveLength(2)
expect(session!.previewMessages[0].text).toBe('Plan the work')
expect(session!.previewMessages[0].role).toBe('user')
expect(session!.previewMessages[1].text).toBe('Done')
expect(session!.previewMessages[1].role).toBe('assistant')
})
it('falls back to summary.body for title when session.title is empty', async () => {
const { db, path } = createTempDb()
applyOpenCodeSchema(db)
insertSession(db, {
id: 'ses_2',
title: '',
timeCreated: 1_777_634_000_000,
timeUpdated: 1_777_634_001_000
})
insertMessage(db, {
id: 'msg_1',
sessionId: 'ses_2',
role: 'user',
timeCreated: 1_777_634_000_500,
summaryBody: 'fallback title from summary'
})
insertPart(db, {
id: 'prt_1',
messageId: 'msg_1',
sessionId: 'ses_2',
timeCreated: 1_777_634_000_500,
text: 'hello'
})
db.close()
const session = await parseOpenCodeSqliteSession({
dbPath: path,
sessionId: 'ses_2',
platform: 'darwin'
})
expect(session).not.toBeNull()
expect(session!.title).toBe('fallback title from summary')
})
it('returns null when the session id is not found', async () => {
const { db, path } = createTempDb()
applyOpenCodeSchema(db)
insertSession(db, {
id: 'ses_real',
timeCreated: 1_777_634_000_000,
timeUpdated: 1_777_634_001_000
})
db.close()
const session = await parseOpenCodeSqliteSession({
dbPath: path,
sessionId: 'ses_missing',
platform: 'darwin'
})
expect(session).toBeNull()
})
it('returns null when the DB has no session table', async () => {
const { db, path } = createTempDb()
db.exec('CREATE TABLE other (id TEXT)')
db.close()
const session = await parseOpenCodeSqliteSession({
dbPath: path,
sessionId: 'ses_1',
platform: 'darwin'
})
expect(session).toBeNull()
})
it('parses a minimal readable session table without optional columns or messages', async () => {
const { db, path } = createTempDb()
applyMinimalOpenCodeSchema(db)
@@ -520,25 +333,6 @@ describe('parseOpenCodeSqliteSession', () => {
).rejects.toThrow(/unreadable message-part schema/)
})
it('extracts model from older modelID schema', async () => {
const { db, path } = createTempDb()
applyOpenCodeSchema(db)
insertSession(db, {
id: 'ses_3',
timeCreated: 1_777_634_000_000,
timeUpdated: 1_777_634_001_000,
model: JSON.stringify({ modelID: 'claude-sonnet-4-5' })
})
db.close()
const session = await parseOpenCodeSqliteSession({
dbPath: path,
sessionId: 'ses_3',
platform: 'darwin'
})
expect(session).not.toBeNull()
expect(session!.model).toBe('claude-sonnet-4-5')
})
it('captures every text part of the earliest user message and no later turn', async () => {
const { db, path } = createTempDb()
applyOpenCodeSchema(db)
@@ -9,7 +9,6 @@ import {
parseOpenCode2SqliteSession,
captureOpenCode2SqliteSession
} from './session-scanner-opencode2-sqlite'
import { withFullFirstUserPromptCapture } from '../../session-scanner-first-user-prompt-capture'
import type { AiVaultScanIssue } from '../../../../shared/ai-vault/contracts/ai-vault-types'
let tempDirs: string[] = []
@@ -206,171 +205,4 @@ describe('listOpenCode2SqliteSessions', () => {
])
expect(candidates[0]!.agent).toBe('opencode2')
})
it('skips databases without the session_v2 table', async () => {
const { db, path } = createTempDb()
db.exec(`CREATE TABLE unrelated (id TEXT PRIMARY KEY)`)
db.close()
const candidates = await listOpenCode2SqliteSessions({
dbPaths: [path],
limit: 25,
issues
})
expect(candidates).toEqual([])
})
})
describe('parseOpenCode2SqliteSession', () => {
it('parses session metadata and preview messages', async () => {
const { db, path } = createTempDb()
applyOpenCode2Schema(db)
insertSession(db, {
id: 'session_1',
directory: '/repo',
title: 'Fix login',
timeCreated: 1_777_634_000_000,
timeUpdated: 1_777_634_001_000
})
db.prepare(
`UPDATE session_v2 SET model = ?, tokens_input = 10, tokens_output = 20, tokens_reasoning = 5, cost = 0.5 WHERE id = 'session_1'`
).run('{"id":"glm-5.2","providerID":"zai"}')
insertMessage(db, {
id: 'msg_1',
sessionId: 'session_1',
type: 'user',
seq: 1,
timeCreated: 1_777_634_000_500,
data: JSON.stringify({
id: 'msg_1',
text: 'Add login flow',
time: { created: 1_777_634_000_500 }
})
})
insertMessage(db, {
id: 'msg_2',
sessionId: 'session_1',
type: 'assistant',
seq: 2,
timeCreated: 1_777_634_000_900,
data: JSON.stringify({
id: 'msg_2',
type: 'assistant',
content: [{ type: 'text', text: 'Done.' }],
time: { created: 1_777_634_000_900 }
})
})
db.close()
const session = await withFullFirstUserPromptCapture(() =>
parseOpenCode2SqliteSession({
dbPath: path,
sessionId: 'session_1',
platform: 'darwin'
})
)
expect(session).not.toBeNull()
expect(session!.agent).toBe('opencode2')
expect(session!.sessionId).toBe('session_1')
expect(session!.filePath).toBe(path)
expect(session!.title).toBe('Fix login')
expect(session?.firstUserPrompt).toBe('Add login flow')
expect(session!.cwd).toBe('/repo')
expect(session!.model).toBe('glm-5.2')
expect(session!.totalTokens).toBe(35)
expect(session!.messageCount).toBe(2)
expect(session!.previewMessages).toEqual([
{
role: 'user',
text: 'Add login flow',
timestamp: new Date(1_777_634_000_500).toISOString()
},
{
role: 'assistant',
text: 'Done.',
timestamp: new Date(1_777_634_000_900).toISOString()
}
])
expect(session!.resumeCommand).toBe(
"cd '/repo' && opencode2 --standalone --session 'session_1'"
)
})
it('extracts assistant text from content arrays and falls back to raw model ids', async () => {
const { db, path } = createTempDb()
applyOpenCode2Schema(db)
insertSession(db, {
id: 'session_2',
directory: '/repo',
title: null,
timeCreated: 1_777_634_000_000,
timeUpdated: 1_777_634_000_000
})
db.prepare(`UPDATE session_v2 SET model = ? WHERE id = 'session_2'`).run(
'anthropic/claude-sonnet'
)
insertMessage(db, {
id: 'msg_1',
sessionId: 'session_2',
type: 'assistant',
seq: 1,
timeCreated: 1_777_634_000_500,
data: JSON.stringify({
id: 'msg_1',
type: 'assistant',
content: [
{ type: 'reasoning', text: 'hidden' },
{ type: 'text', text: 'Visible answer' }
],
time: { created: 1_777_634_000_500 }
})
})
db.close()
const session = await parseOpenCode2SqliteSession({
dbPath: path,
sessionId: 'session_2',
platform: 'darwin'
})
expect(session).not.toBeNull()
expect(session!.model).toBe('anthropic/claude-sonnet')
expect(session!.previewMessages).toEqual([
{
role: 'assistant',
text: 'Visible answer',
timestamp: new Date(1_777_634_000_500).toISOString()
}
])
})
it('fails soft when the session_v2 table is missing', async () => {
const { db, path } = createTempDb()
db.exec(`CREATE TABLE session_v1 (id TEXT PRIMARY KEY)`)
db.close()
const session = await parseOpenCode2SqliteSession({
dbPath: path,
sessionId: 'session_1',
platform: 'darwin'
})
expect(session).toBeNull()
})
it('fails soft when the session does not exist', async () => {
const { db, path } = createTempDb()
applyOpenCode2Schema(db)
db.close()
const session = await parseOpenCode2SqliteSession({
dbPath: path,
sessionId: 'missing',
platform: 'darwin'
})
expect(session).toBeNull()
})
})
@@ -3,25 +3,9 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { handleOpenCodeSqliteRequest } from '../opencode/reader-transport/session-scanner-opencode-sqlite-dispatch'
import { splitOpenCodeSqliteCandidate } from '../../../../shared/opencode-sqlite-session-path'
import { writeOpenCodeSqliteDatabase } from '../opencode/sqlite/session-scanner-opencode-sqlite-fixture'
import SyncDatabase from '../../../sqlite/sync-database'
function readCandidates(value: unknown): { agent: string; path: string }[] {
if (typeof value !== 'object' || value === null || !('candidates' in value)) {
throw new Error('expected a listing payload with candidates')
}
const { candidates } = value
if (!Array.isArray(candidates)) {
throw new Error('expected candidates to be an array')
}
return candidates.map((candidate) => {
const agent = readStringField(candidate, 'agent')
const file = isRecord(candidate) ? candidate['file'] : null
return { agent, path: readStringField(file, 'path') }
})
}
function readMessageTexts(value: unknown): { text: string }[] {
if (typeof value !== 'object' || value === null || !('messages' in value)) {
throw new Error('expected a capture payload with messages')
@@ -170,76 +154,6 @@ describe('ZCode AI Vault SQLite worker', () => {
])
})
it('lists, parses, and captures ZCode sessions without labelling them OpenCode', async () => {
const directory = mkdtempSync(join(tmpdir(), 'orca-zcode-ai-vault-'))
directories.push(directory)
const dbPath = join(directory, 'db.sqlite')
writeOpenCodeSqliteDatabase(dbPath, [
{
id: 'zcode-session',
directory: '/repo',
title: 'ZCode task',
turns: [
{ role: 'user', parts: ['Fix the import'] },
{ role: 'assistant', parts: ['Import fixed'] }
]
}
])
const listed = await handleOpenCodeSqliteRequest({
id: 1,
kind: 'list',
agent: 'zcode',
dbPaths: [dbPath],
limit: 10
})
expect(listed.ok).toBe(true)
if (!listed.ok) {
return
}
const candidates = readCandidates(listed.value)
expect(candidates).toHaveLength(1)
expect(candidates[0]?.agent).toBe('zcode')
expect(splitOpenCodeSqliteCandidate(candidates[0]!.path, 'zcode')).toEqual({
dbPath,
sessionId: 'zcode-session'
})
expect(splitOpenCodeSqliteCandidate(candidates[0]!.path)).toBeNull()
const parsed = await handleOpenCodeSqliteRequest({
id: 2,
kind: 'parse',
agent: 'zcode',
dbPath,
sessionId: 'zcode-session',
platform: 'darwin'
})
expect(parsed).toMatchObject({
ok: true,
value: {
agent: 'zcode',
title: 'ZCode task',
resumeCommand: "cd '/repo' && zcode --resume 'zcode-session'"
}
})
const captured = await handleOpenCodeSqliteRequest({
id: 3,
kind: 'capture',
agent: 'zcode',
dbPath,
sessionId: 'zcode-session',
platform: 'darwin'
})
expect(captured).toMatchObject({ ok: true, value: { session: { agent: 'zcode' } } })
if (!captured.ok) {
return
}
expect(readMessageTexts(captured.value)).toEqual(
expect.arrayContaining([expect.objectContaining({ text: 'Fix the import' })])
)
})
it('excludes ZCode hidden transcript messages from preview and search', async () => {
const directory = mkdtempSync(join(tmpdir(), 'orca-zcode-ai-vault-'))
directories.push(directory)
@@ -1,466 +0,0 @@
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { validateAiVaultSessionDeleteTarget } from './session-delete-target'
// Inject roots so validation never depends on the user's home.
const HOME = join('/tmp', 'orca-ai-vault-delete-fixture-home')
const GEMINI_ROOT = join(HOME, '.gemini', 'tmp')
const CURSOR_ROOT = join(HOME, '.cursor', 'projects')
const HERMES_ROOT = join(HOME, '.hermes', 'sessions')
const OPENCLAW_ROOT = join(HOME, '.openclaw')
const COPILOT_ROOT = join(HOME, '.copilot', 'session-state')
const DEVIN_ROOT = join(HOME, '.local', 'share', 'devin', 'cli', 'transcripts')
const PI_ROOT = join(HOME, '.pi', 'agent', 'sessions')
const OMP_ROOT = join(HOME, '.omp', 'agent', 'sessions')
const CLAUDE_ROOT = join(HOME, '.claude', 'projects')
const CLAUDE_SESSION_ENV_ROOT = join(HOME, '.claude', 'session-env')
const ROVO_ROOT = join(HOME, '.rovodev', 'sessions')
const GROK_ROOT = join(HOME, '.grok', 'sessions')
describe('validateAiVaultSessionDeleteTarget', () => {
it('plans whole session-directory removal for a canonical Cline manifest', () => {
const root = join('/tmp', 'cline-sessions')
const sessionId = '1786466194549_xrzrl'
const sessionDir = join(root, sessionId)
const result = validateAiVaultSessionDeleteTarget({
agent: 'cline',
filePath: join(sessionDir, `${sessionId}.json`),
executionHostId: 'local',
rootOptions: { clineSessionsDir: root }
})
expect(result).toMatchObject({
allowed: true,
agent: 'cline',
removals: [{ path: sessionDir, kind: 'directory' }]
})
})
it('rejects a Cline messages companion as an undiscoverable delete target', () => {
const root = join('/tmp', 'cline-sessions')
const sessionId = '1786466194549_xrzrl'
const result = validateAiVaultSessionDeleteTarget({
agent: 'cline',
filePath: join(root, sessionId, `${sessionId}.messages.json`),
executionHostId: 'local',
rootOptions: { clineSessionsDir: root }
})
expect(result).toEqual({ allowed: false, agent: 'cline', reason: 'undiscoverable-path' })
})
it('allows a supported agent whose file resolves inside its known root', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'gemini',
filePath: join(GEMINI_ROOT, 'project-a', 'session-1.json'),
executionHostId: 'local',
rootOptions: { geminiSessionsDir: GEMINI_ROOT }
})
expect(result).toEqual({
allowed: true,
agent: 'gemini',
resolvedPath: join(GEMINI_ROOT, 'project-a', 'session-1.json'),
removals: [
{
path: join(GEMINI_ROOT, 'project-a', 'session-1.json'),
kind: 'file',
roots: [GEMINI_ROOT]
}
]
})
})
it('allows gemini .jsonl files too, since discovery accepts both extensions', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'gemini',
filePath: join(GEMINI_ROOT, 'project-a', 'session-1.jsonl'),
executionHostId: 'local',
rootOptions: { geminiSessionsDir: GEMINI_ROOT }
})
expect(result.allowed).toBe(true)
})
it('rejects a path that escapes its root via ..', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'gemini',
filePath: join(GEMINI_ROOT, '..', '..', '..', 'etc', 'passwd.json'),
executionHostId: 'local',
rootOptions: { geminiSessionsDir: GEMINI_ROOT }
})
expect(result).toEqual({ allowed: false, agent: 'gemini', reason: 'path-outside-known-roots' })
})
it('rejects a path entirely outside the known roots', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'gemini',
filePath: join(HOME, 'Documents', 'notes.json'),
executionHostId: 'local',
rootOptions: { geminiSessionsDir: GEMINI_ROOT }
})
expect(result).toEqual({ allowed: false, agent: 'gemini', reason: 'path-outside-known-roots' })
})
it('rejects a file whose extension the agent never discovers', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'cursor',
filePath: join(CURSOR_ROOT, 'proj', 'agent-transcripts', 'session-1.txt'),
executionHostId: 'local',
rootOptions: { cursorProjectsDir: CURSOR_ROOT }
})
expect(result).toEqual({ allowed: false, agent: 'cursor', reason: 'undiscoverable-path' })
})
it('rejects a cursor path missing the agent-transcripts segment', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'cursor',
filePath: join(CURSOR_ROOT, 'proj', 'session-1.jsonl'),
executionHostId: 'local',
rootOptions: { cursorProjectsDir: CURSOR_ROOT }
})
expect(result).toEqual({ allowed: false, agent: 'cursor', reason: 'undiscoverable-path' })
})
it('allows a cursor path that does carry the agent-transcripts segment', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'cursor',
filePath: join(CURSOR_ROOT, 'proj', 'agent-transcripts', 'session-1.jsonl'),
executionHostId: 'local',
rootOptions: { cursorProjectsDir: CURSOR_ROOT }
})
expect(result.allowed).toBe(true)
})
it('rejects a hermes file whose basename is missing the session_ prefix', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'hermes',
filePath: join(HERMES_ROOT, 'not-a-session.json'),
executionHostId: 'local',
rootOptions: { hermesSessionsDir: HERMES_ROOT }
})
expect(result).toEqual({ allowed: false, agent: 'hermes', reason: 'undiscoverable-path' })
})
it('allows a hermes file whose basename carries the session_ prefix', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'hermes',
filePath: join(HERMES_ROOT, 'session_abc123.json'),
executionHostId: 'local',
rootOptions: { hermesSessionsDir: HERMES_ROOT }
})
expect(result.allowed).toBe(true)
})
it('allows an openclaw path under <stateDir>/agents/.../sessions/...', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'openclaw',
filePath: join(OPENCLAW_ROOT, 'agents', 'agent-1', 'sessions', 'session-1.jsonl'),
executionHostId: 'local',
rootOptions: { openclawStateDir: OPENCLAW_ROOT }
})
expect(result.allowed).toBe(true)
})
it('rejects an openclaw path missing the sessions segment', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'openclaw',
filePath: join(OPENCLAW_ROOT, 'agents', 'agent-1', 'session-1.jsonl'),
executionHostId: 'local',
rootOptions: { openclawStateDir: OPENCLAW_ROOT }
})
expect(result).toEqual({ allowed: false, agent: 'openclaw', reason: 'undiscoverable-path' })
})
it('rejects an agent whose own registry would keep a dangling entry (codex)', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'codex',
filePath: join(HOME, '.codex', 'sessions', 'rollout-1.jsonl'),
executionHostId: 'local'
})
expect(result).toEqual({ allowed: false, agent: 'codex', reason: 'unsupported-agent' })
})
it('rejects a non-local execution host', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'gemini',
filePath: join(GEMINI_ROOT, 'project-a', 'session-1.json'),
executionHostId: 'ssh:some-host',
rootOptions: { geminiSessionsDir: GEMINI_ROOT }
})
expect(result).toEqual({ allowed: false, agent: 'gemini', reason: 'non-local-host' })
})
it('rejects a real opencode session as an unsupported agent', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'opencode',
filePath: join(HOME, '.local', 'share', 'opencode', 'db.sqlite#session-1'),
executionHostId: 'local'
})
expect(result).toEqual({ allowed: false, agent: 'opencode', reason: 'unsupported-agent' })
})
it('rejects a deletable-agent path bearing a synthetic # marker', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'gemini',
filePath: join(GEMINI_ROOT, 'project-a', 'db.sqlite#session-1'),
executionHostId: 'local',
rootOptions: { geminiSessionsDir: GEMINI_ROOT }
})
expect(result).toEqual({ allowed: false, agent: 'gemini', reason: 'synthetic-path' })
})
it('rejects a blank filePath', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'gemini',
filePath: ' ',
executionHostId: 'local',
rootOptions: { geminiSessionsDir: GEMINI_ROOT }
})
expect(result).toEqual({ allowed: false, agent: 'gemini', reason: 'invalid-path' })
})
it('allows a droid path under either of its .factory roots', () => {
const sessionsRoot = join(HOME, '.factory', 'sessions')
const projectsRoot = join(HOME, '.factory', 'projects')
const underSessions = validateAiVaultSessionDeleteTarget({
agent: 'droid',
filePath: join(sessionsRoot, 'session-1.jsonl'),
executionHostId: 'local',
rootOptions: { droidSessionsDir: sessionsRoot, droidProjectsDir: projectsRoot }
})
expect(underSessions.allowed).toBe(true)
const underProjects = validateAiVaultSessionDeleteTarget({
agent: 'droid',
filePath: join(projectsRoot, 'proj-a', 'session-2.jsonl'),
executionHostId: 'local',
rootOptions: { droidSessionsDir: sessionsRoot, droidProjectsDir: projectsRoot }
})
expect(underProjects.allowed).toBe(true)
})
it('allows a copilot .jsonl file under its known root', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'copilot',
filePath: join(COPILOT_ROOT, 'session-1.jsonl'),
executionHostId: 'local',
rootOptions: { copilotSessionsDir: COPILOT_ROOT }
})
expect(result.allowed).toBe(true)
})
it('allows a devin .json file under its known root', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'devin',
filePath: join(DEVIN_ROOT, 'session-1.json'),
executionHostId: 'local',
rootOptions: { devinTranscriptsDir: DEVIN_ROOT }
})
expect(result.allowed).toBe(true)
})
it('allows a pi .jsonl file under its known root', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'pi',
filePath: join(PI_ROOT, 'session-1.jsonl'),
executionHostId: 'local',
rootOptions: { piSessionsDir: PI_ROOT }
})
expect(result.allowed).toBe(true)
})
it('allows an omp .jsonl file under its known root', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'omp',
filePath: join(OMP_ROOT, 'session-1.jsonl'),
executionHostId: 'local',
rootOptions: { ompSessionsDir: OMP_ROOT }
})
expect(result.allowed).toBe(true)
})
it('allows an omp row the Pi walk labelled from under the Pi root', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'omp',
filePath: join(PI_ROOT, '-repo-app', 'session-1.jsonl'),
executionHostId: 'local',
rootOptions: { piSessionsDir: PI_ROOT, ompSessionsDir: OMP_ROOT }
})
expect(result.allowed).toBe(true)
})
it('allows an uppercase extension since discovery folds extension case', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'gemini',
filePath: join(GEMINI_ROOT, 'project-a', 'session-1.JSON'),
executionHostId: 'local',
rootOptions: { geminiSessionsDir: GEMINI_ROOT }
})
expect(result.allowed).toBe(true)
})
it('allows a gemini file under a WSL-expanded root', () => {
const wslHome = join('/tmp', 'orca-ai-vault-delete-fixture-wsl-home')
const result = validateAiVaultSessionDeleteTarget({
agent: 'gemini',
filePath: join(wslHome, '.gemini', 'tmp', 'project-a', 'session-1.json'),
executionHostId: 'local',
wslHomeDirs: [wslHome],
rootOptions: { geminiSessionsDir: GEMINI_ROOT }
})
expect(result.allowed).toBe(true)
})
it('allows an openclaw path whose stateDir already ends in agents', () => {
const agentsRoot = join(OPENCLAW_ROOT, 'agents')
const result = validateAiVaultSessionDeleteTarget({
agent: 'openclaw',
filePath: join(agentsRoot, 'agent-1', 'sessions', 'session-1.jsonl'),
executionHostId: 'local',
rootOptions: { openclawStateDir: agentsRoot }
})
expect(result.allowed).toBe(true)
})
})
describe('directory-shaped agents', () => {
it('plans claude companions before the transcript', () => {
const filePath = join(CLAUDE_ROOT, '-proj', 'sess-1.jsonl')
const result = validateAiVaultSessionDeleteTarget({
agent: 'claude',
filePath,
executionHostId: 'local',
rootOptions: { claudeProjectsDir: CLAUDE_ROOT }
})
expect(result).toEqual({
allowed: true,
agent: 'claude',
resolvedPath: filePath,
removals: [
{
path: join(CLAUDE_ROOT, '-proj', 'sess-1'),
kind: 'directory',
roots: [CLAUDE_ROOT]
},
{
path: join(CLAUDE_SESSION_ENV_ROOT, 'sess-1'),
kind: 'directory',
roots: [CLAUDE_SESSION_ENV_ROOT]
},
{ path: filePath, kind: 'file', roots: [CLAUDE_ROOT] }
]
})
})
it("never plans file-history, the rewind buffer for the user's own files", () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'claude',
filePath: join(CLAUDE_ROOT, '-proj', 'sess-1.jsonl'),
executionHostId: 'local',
rootOptions: { claudeProjectsDir: CLAUDE_ROOT }
})
expect(result.allowed).toBe(true)
expect(
result.allowed && result.removals.some((removal) => removal.path.includes('file-history'))
).toBe(false)
})
it("pairs a WSL-home claude session with that distro's session-env, not the local one", () => {
const wslHome = join('/tmp', 'orca-wsl-home')
const filePath = join(wslHome, '.claude', 'projects', '-proj', 'sess-2.jsonl')
const result = validateAiVaultSessionDeleteTarget({
agent: 'claude',
filePath,
executionHostId: 'local',
wslHomeDirs: [wslHome],
rootOptions: { claudeProjectsDir: CLAUDE_ROOT }
})
expect(result.allowed && result.removals[1]).toEqual({
path: join(wslHome, '.claude', 'session-env', 'sess-2'),
kind: 'directory',
roots: [join(wslHome, '.claude', 'session-env')]
})
})
it('refuses a transcript whose stem would resolve to the project dir itself', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'claude',
filePath: join(CLAUDE_ROOT, '-proj', '..jsonl'),
executionHostId: 'local',
rootOptions: { claudeProjectsDir: CLAUDE_ROOT }
})
expect(result).toEqual({
allowed: false,
agent: 'claude',
reason: 'no-session-directory'
})
})
it('rejects a Task subagent transcript, which is only ever removed with its parent', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'claude',
filePath: join(CLAUDE_ROOT, '-proj', 'sess-1', 'subagents', 'agent-abc.jsonl'),
executionHostId: 'local',
rootOptions: { claudeProjectsDir: CLAUDE_ROOT }
})
expect(result).toEqual({
allowed: false,
agent: 'claude',
reason: 'undiscoverable-path'
})
})
it("plans removal of rovo's whole session directory", () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'rovo',
filePath: join(ROVO_ROOT, 'sess-1', 'metadata.json'),
executionHostId: 'local',
rootOptions: { rovoSessionsDir: ROVO_ROOT }
})
expect(result).toEqual({
allowed: true,
agent: 'rovo',
resolvedPath: join(ROVO_ROOT, 'sess-1', 'metadata.json'),
removals: [{ path: join(ROVO_ROOT, 'sess-1'), kind: 'directory', roots: [ROVO_ROOT] }]
})
})
it("plans removal of grok's session directory under its encoded-cwd group", () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'grok',
filePath: join(GROK_ROOT, '-Users-me-proj', 'sess-1', 'summary.json'),
executionHostId: 'local',
rootOptions: { grokSessionsDir: GROK_ROOT }
})
expect(result.allowed && result.removals).toEqual([
{ path: join(GROK_ROOT, '-Users-me-proj', 'sess-1'), kind: 'directory', roots: [GROK_ROOT] }
])
})
it("rejects grok's chat_history.jsonl — only summary.json names a session", () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'grok',
filePath: join(GROK_ROOT, 'group', 'sess-1', 'chat_history.jsonl'),
executionHostId: 'local',
rootOptions: { grokSessionsDir: GROK_ROOT }
})
expect(result).toEqual({ allowed: false, agent: 'grok', reason: 'undiscoverable-path' })
})
it('refuses a metadata.json sitting in the sessions root, which would trash every session', () => {
const result = validateAiVaultSessionDeleteTarget({
agent: 'rovo',
filePath: join(ROVO_ROOT, 'metadata.json'),
executionHostId: 'local',
rootOptions: { rovoSessionsDir: ROVO_ROOT }
})
expect(result).toEqual({ allowed: false, agent: 'rovo', reason: 'no-session-directory' })
})
})
-299
View File
@@ -1,299 +0,0 @@
import { join, resolve } from 'node:path'
import { describe, expect, it, vi, beforeEach } from 'vitest'
const {
lstatMock,
realpathMock,
trashItemMock,
tryDeleteWslUncPathMock,
WslDeleteValidationErrorMock
} = vi.hoisted(() => ({
lstatMock: vi.fn(),
realpathMock: vi.fn(),
trashItemMock: vi.fn(),
tryDeleteWslUncPathMock: vi.fn(),
WslDeleteValidationErrorMock: class extends Error {
constructor(readonly reason: 'path-outside-known-roots' | 'unexpected-target-kind') {
super(reason)
}
}
}))
vi.mock('node:fs/promises', () => ({
lstat: lstatMock,
realpath: realpathMock
}))
vi.mock('../wsl/filesystem/wsl-unc-delete', () => ({
tryDeleteWslUncPath: tryDeleteWslUncPathMock,
WslDeleteValidationError: WslDeleteValidationErrorMock
}))
import { deleteAiVaultSessionFile as deleteWithRemover } from './session-delete'
// The desktop's Trash remover; the executor itself is remover-agnostic.
const deleteAiVaultSessionFile = (args: Parameters<typeof deleteWithRemover>[0]) =>
deleteWithRemover(args, (removal) => trashItemMock(removal.path))
const HOME = join('/tmp', 'orca-ai-vault-delete-exec-fixture-home')
const GEMINI_ROOT = join(HOME, '.gemini', 'tmp')
const CLAUDE_ROOT = join(HOME, '.claude', 'projects')
const ROVO_ROOT = join(HOME, '.rovodev', 'sessions')
function enoent(): NodeJS.ErrnoException {
const error = new Error('not found') as NodeJS.ErrnoException
error.code = 'ENOENT'
return error
}
function baseArgs(filePath: string) {
return {
agent: 'gemini' as const,
filePath,
executionHostId: 'local' as const,
rootOptions: { geminiSessionsDir: GEMINI_ROOT }
}
}
describe('deleteAiVaultSessionFile', () => {
beforeEach(() => {
vi.clearAllMocks()
tryDeleteWslUncPathMock.mockResolvedValue(false)
})
it('trashes a regular file whose realpath matches the resolved path', async () => {
const filePath = join(GEMINI_ROOT, 'project-a', 'session-1.json')
lstatMock.mockResolvedValue({ isFile: () => true })
realpathMock.mockResolvedValue(filePath)
trashItemMock.mockResolvedValue(undefined)
const result = await deleteAiVaultSessionFile(baseArgs(filePath))
expect(result).toEqual({ outcome: 'deleted' })
expect(trashItemMock).toHaveBeenCalledWith(filePath)
})
it('rejects a directory instead of trashing it', async () => {
const filePath = join(GEMINI_ROOT, 'project-a', 'session-1.json')
lstatMock.mockResolvedValue({ isFile: () => false })
const result = await deleteAiVaultSessionFile(baseArgs(filePath))
expect(result).toEqual({
outcome: 'rejected',
agent: 'gemini',
reason: 'unexpected-target-kind'
})
expect(trashItemMock).not.toHaveBeenCalled()
})
it('rejects a regular file whose realpath escapes the known roots', async () => {
const filePath = join(GEMINI_ROOT, 'project-a', 'session-1.json')
const escaped = join(HOME, 'Documents', 'escaped.json')
lstatMock.mockResolvedValue({ isFile: () => true })
realpathMock.mockImplementation((p: string) => Promise.resolve(p === filePath ? escaped : p))
const result = await deleteAiVaultSessionFile(baseArgs(filePath))
expect(result).toEqual({
outcome: 'rejected',
agent: 'gemini',
reason: 'path-outside-known-roots'
})
expect(trashItemMock).not.toHaveBeenCalled()
})
it('accepts a session under a symlinked root by realpath-resolving the roots too', async () => {
const filePath = join(GEMINI_ROOT, 'project-a', 'session-1.json')
const realRoot = join('/real', '.gemini', 'tmp')
const realFile = join(realRoot, 'project-a', 'session-1.json')
lstatMock.mockResolvedValue({ isFile: () => true })
realpathMock.mockImplementation((p: string) =>
Promise.resolve(p === GEMINI_ROOT ? realRoot : p === filePath ? realFile : p)
)
trashItemMock.mockResolvedValue(undefined)
const result = await deleteAiVaultSessionFile(baseArgs(filePath))
expect(result).toEqual({ outcome: 'deleted' })
expect(trashItemMock).toHaveBeenCalledWith(filePath)
})
it('treats ENOENT from lstat as an idempotent success', async () => {
const filePath = join(GEMINI_ROOT, 'project-a', 'session-1.json')
lstatMock.mockRejectedValue(enoent())
const result = await deleteAiVaultSessionFile(baseArgs(filePath))
expect(result).toEqual({ outcome: 'deleted' })
expect(trashItemMock).not.toHaveBeenCalled()
})
it('treats ENOENT from trashItem as an idempotent success (race with an external delete)', async () => {
const filePath = join(GEMINI_ROOT, 'project-a', 'session-1.json')
lstatMock.mockResolvedValue({ isFile: () => true })
realpathMock.mockResolvedValue(filePath)
trashItemMock.mockRejectedValue(enoent())
const result = await deleteAiVaultSessionFile(baseArgs(filePath))
expect(result).toEqual({ outcome: 'deleted' })
})
it('returns a failure result when trashItem throws a non-ENOENT error', async () => {
const filePath = join(GEMINI_ROOT, 'project-a', 'session-1.json')
lstatMock.mockResolvedValue({ isFile: () => true })
realpathMock.mockResolvedValue(filePath)
trashItemMock.mockRejectedValue(new Error('permission denied'))
const result = await deleteAiVaultSessionFile(baseArgs(filePath))
expect(result).toEqual({ outcome: 'failed', agent: 'gemini', error: 'permission denied' })
})
it('short-circuits a rejected validation (unsupported agent) before touching the filesystem', async () => {
const filePath = join(HOME, '.codex', 'sessions', 'rollout-1.jsonl')
const result = await deleteAiVaultSessionFile({
agent: 'codex',
filePath,
executionHostId: 'local'
})
expect(result).toEqual({ outcome: 'rejected', agent: 'codex', reason: 'unsupported-agent' })
expect(lstatMock).not.toHaveBeenCalled()
expect(realpathMock).not.toHaveBeenCalled()
expect(trashItemMock).not.toHaveBeenCalled()
expect(tryDeleteWslUncPathMock).not.toHaveBeenCalled()
})
it('uses a successful WSL-helper result before local file trash', async () => {
const filePath = join(GEMINI_ROOT, 'project-a', 'session-1.json')
tryDeleteWslUncPathMock.mockResolvedValue(true)
const result = await deleteAiVaultSessionFile(baseArgs(filePath))
expect(result).toEqual({ outcome: 'deleted' })
expect(tryDeleteWslUncPathMock).toHaveBeenCalledWith(resolve(filePath), {
recursive: false,
approvedRoots: [resolve(GEMINI_ROOT)]
})
expect(lstatMock).not.toHaveBeenCalled()
expect(trashItemMock).not.toHaveBeenCalled()
})
it('requests recursive helper removal for a directory-shaped session', async () => {
// WSL UNC volumes cannot use Trash and may give unreliable 9P stats.
tryDeleteWslUncPathMock.mockResolvedValue(true)
const result = await deleteAiVaultSessionFile({
agent: 'rovo',
filePath: join(ROVO_ROOT, 'sess-1', 'metadata.json'),
executionHostId: 'local',
rootOptions: { rovoSessionsDir: ROVO_ROOT }
})
expect(result).toEqual({ outcome: 'deleted' })
expect(tryDeleteWslUncPathMock).toHaveBeenCalledWith(resolve(ROVO_ROOT, 'sess-1'), {
recursive: true,
approvedRoots: [resolve(ROVO_ROOT)]
})
expect(lstatMock).not.toHaveBeenCalled()
expect(trashItemMock).not.toHaveBeenCalled()
})
it('maps a WSL containment rejection to a delete rejection', async () => {
const filePath = join(GEMINI_ROOT, 'project-a', 'session-1.json')
tryDeleteWslUncPathMock.mockRejectedValue(
new WslDeleteValidationErrorMock('path-outside-known-roots')
)
const result = await deleteAiVaultSessionFile(baseArgs(filePath))
expect(result).toEqual({
outcome: 'rejected',
agent: 'gemini',
reason: 'path-outside-known-roots'
})
expect(lstatMock).not.toHaveBeenCalled()
expect(trashItemMock).not.toHaveBeenCalled()
})
describe('directory-shaped agents', () => {
const claudeArgs = {
agent: 'claude' as const,
filePath: join(CLAUDE_ROOT, '-proj', 'sess-1.jsonl'),
executionHostId: 'local' as const,
rootOptions: { claudeProjectsDir: CLAUDE_ROOT }
}
it('trashes the subagents and session-env dirs before the transcript', async () => {
lstatMock.mockImplementation((path: string) =>
Promise.resolve(
path.endsWith('.jsonl') ? { isFile: () => true } : { isDirectory: () => true }
)
)
realpathMock.mockImplementation((path: string) => Promise.resolve(path))
trashItemMock.mockResolvedValue(undefined)
const result = await deleteAiVaultSessionFile(claudeArgs)
expect(result).toEqual({ outcome: 'deleted' })
expect(trashItemMock.mock.calls.map(([path]) => path)).toEqual([
join(CLAUDE_ROOT, '-proj', 'sess-1'),
join(HOME, '.claude', 'session-env', 'sess-1'),
claudeArgs.filePath
])
})
it('still deletes when a companion is absent — most sessions spawn no subagent', async () => {
lstatMock.mockImplementation((path: string) =>
path.endsWith('.jsonl') ? Promise.resolve({ isFile: () => true }) : Promise.reject(enoent())
)
realpathMock.mockImplementation((path: string) => Promise.resolve(path))
trashItemMock.mockResolvedValue(undefined)
const result = await deleteAiVaultSessionFile(claudeArgs)
expect(result).toEqual({ outcome: 'deleted' })
expect(trashItemMock.mock.calls.map(([path]) => path)).toEqual([claudeArgs.filePath])
})
it('leaves the transcript in place when a companion removal is rejected', async () => {
lstatMock.mockImplementation((path: string) =>
Promise.resolve(
path === join(CLAUDE_ROOT, '-proj', 'sess-1')
? { isFile: () => true, isDirectory: () => false }
: { isFile: () => true, isDirectory: () => true }
)
)
realpathMock.mockImplementation((path: string) => Promise.resolve(path))
const result = await deleteAiVaultSessionFile(claudeArgs)
expect(result).toEqual({
outcome: 'rejected',
agent: 'claude',
reason: 'unexpected-target-kind'
})
expect(trashItemMock).not.toHaveBeenCalled()
})
it("trashes rovo's session directory rather than the metadata file", async () => {
const sessionDir = join(ROVO_ROOT, 'sess-1')
lstatMock.mockResolvedValue({ isDirectory: () => true })
realpathMock.mockImplementation((path: string) => Promise.resolve(path))
trashItemMock.mockResolvedValue(undefined)
const result = await deleteAiVaultSessionFile({
agent: 'rovo',
filePath: join(sessionDir, 'metadata.json'),
executionHostId: 'local',
rootOptions: { rovoSessionsDir: ROVO_ROOT }
})
expect(result).toEqual({ outcome: 'deleted' })
expect(trashItemMock).toHaveBeenCalledWith(sessionDir)
})
})
})
@@ -168,13 +168,6 @@ afterEach(async () => {
})
describe('Kimi session parse against a stalled WSL transcript', () => {
it('refuses a stalled state.json read instead of reporting no session', async () => {
const state = uncPath('KimiState', ...KIMI_HOME, 'state.json')
mocks.readFile.mockImplementation(stalls<string>)
await expectRefusal(candidate('kimi', state))
})
it('refuses a stalled wire read, then caches the full session once it recovers', async () => {
const state = uncPath('KimiWire', ...KIMI_HOME, 'state.json')
mocks.readFile.mockResolvedValue(KIMI_STATE)
@@ -188,16 +181,6 @@ describe('Kimi session parse against a stalled WSL transcript', () => {
expect(recovered?.messageCount).toBe(1)
})
it('still returns a metadata-only session when the wire file is simply missing', async () => {
const state = uncPath('KimiMissing', ...KIMI_HOME, 'state.json')
mocks.readFile.mockResolvedValue(KIMI_STATE)
mocks.open.mockRejectedValue(missing())
const session = await parseAgentSessionFileCached(candidate('kimi', state), 'linux')
expect(session).toMatchObject({ agent: 'kimi', title: 'Kimi session', messageCount: 0 })
})
})
describe('Grok session parse against a stalled WSL transcript', () => {
@@ -216,20 +199,6 @@ describe('Grok session parse against a stalled WSL transcript', () => {
expect.objectContaining({ role: 'user', text: 'ship it' })
])
})
it('still returns the summary-only session when chat_history is missing', async () => {
const file = uncPath('GrokMissing', ...GROK_DIR, 'session.json')
mocks.readFile.mockResolvedValue(GROK_SESSION)
mocks.open.mockRejectedValue(missing())
const session = await parseAgentSessionFileCached(candidate('grok', file), 'linux')
expect(session).toMatchObject({
agent: 'grok',
title: 'Grok session',
previewMessages: []
})
})
})
describe('OpenCode session parse against a stalled WSL transcript', () => {
@@ -237,13 +206,6 @@ describe('OpenCode session parse against a stalled WSL transcript', () => {
return uncPath(distro, ...OPENCODE_ROOT, 'session', 'prj', 'ses-1.json')
}
it('refuses a stalled message-directory listing instead of an empty transcript', async () => {
mocks.readFile.mockResolvedValue(OPENCODE_SESSION)
mocks.readdir.mockImplementation(stalls<unknown[]>)
await expectRefusal(candidate('opencode', sessionPath('OpenCodeDir')))
})
it('refuses a stalled per-message read instead of a partial transcript', async () => {
const file = sessionPath('OpenCodeMessage')
mocks.readdir.mockResolvedValue([dirent('msg-1.json')])
@@ -261,16 +223,4 @@ describe('OpenCode session parse against a stalled WSL transcript', () => {
expect(recovered?.messageCount).toBe(1)
})
it('still returns the session when a live process left a half-written message', async () => {
const file = sessionPath('OpenCodeHalfWritten')
mocks.readdir.mockResolvedValue([dirent('msg-1.json')])
mocks.readFile.mockImplementation((path: string) =>
Promise.resolve(path === file ? OPENCODE_SESSION : '{"role":"user",')
)
const session = await parseAgentSessionFileCached(candidate('opencode', file), 'linux')
expect(session).toMatchObject({ agent: 'opencode', title: 'OpenCode session', messageCount: 0 })
})
})
@@ -80,52 +80,6 @@ describe('fresh discovery pipeline', () => {
expect((await scan()).files).toHaveLength(60)
})
it('formats timestamps only for retained files while still reading every candidate', async () => {
await createFiles(root, 35)
fsMocks.stat.mockImplementation(async (path: string) =>
Object.assign(await fs.stat(path), { mtimeMs: 1_000 })
)
const format = vi.spyOn(Date.prototype, 'toISOString')
expect((await scan(root, [], 3)).files).toHaveLength(3)
expect(format).toHaveBeenCalledTimes(3)
expect(fsMocks.stat).toHaveBeenCalledTimes(35)
format.mockClear()
expect((await scan(root, [], 0)).files).toEqual([])
expect(format).not.toHaveBeenCalled()
expect(fsMocks.stat).toHaveBeenCalledTimes(70)
expect((await scan(root, [], Infinity)).files).toHaveLength(35)
expect(format).toHaveBeenCalledTimes(35)
})
it('reports invalid timestamps even for empty requests, after unavailable sidecar issues', async () => {
const [file] = await createFiles(root, 1)
fsMocks.stat.mockImplementation(async (path: string) => {
if (path.endsWith('.meta')) {
throw Object.assign(new Error('metadata refused'), { code: 'EACCES' })
}
return Object.assign(await fs.stat(path), { mtimeMs: Infinity })
})
const issues: AiVaultScanIssue[] = []
const discovery = await discoverFiles({
rootDir: root,
issues,
limit: 0,
agent: 'claude',
extensions: ['.jsonl'],
contentDependencyPath: (path) => `${path}.meta`
})
expect(discovery.files).toEqual([])
expect(issues).toEqual([
{
agent: 'claude',
path: `${file}.meta`,
message: 'Session metadata could not be read this scan.',
messageCode: 'sessionMetadataUnreadable'
},
{ agent: 'claude', path: file, message: expect.stringMatching(/Invalid (?:time value|Date)/) }
])
})
it('preserves traversal ties when later metadata completes first, including the partial batch', async () => {
const paths = await createFiles(root, 131)
let releaseFirst = () => {}
@@ -216,73 +170,6 @@ describe('fresh discovery pipeline', () => {
expect((await discoverFiles(args)).files.map((entry) => entry.path)).not.toContain(file)
})
it('keeps issue ordering at the cap despite reversed metadata failures', async () => {
const paths = await createFiles(root, 65)
let releaseFirst = () => {}
const blocked = new Promise<void>((resolve) => {
releaseFirst = resolve
})
let reachedLater = () => {}
const later = new Promise<void>((resolve) => {
reachedLater = resolve
})
fsMocks.stat.mockImplementation(async (path: string) => {
if (path === paths[0]) {
await blocked
}
if (path === paths[15]) {
reachedLater()
}
throw new Error(`unreadable ${path}`)
})
const issues: AiVaultScanIssue[] = Array.from({ length: 498 }, (_, index) => ({
agent: 'claude',
path: `previous-${index}`,
message: 'previous issue'
}))
const discovery = scan(root, issues)
try {
await later
} finally {
releaseFirst()
}
expect((await discovery).files).toEqual([])
expect(issues).toHaveLength(500)
expect(issues[498]?.path).toBe(paths[0])
expect(issues[499]?.kind).toBe('notice')
})
it('reports one unavailable sidecar in traversal order and distinguishes missing metadata', async () => {
const paths = await createFiles(root, 5)
fsMocks.stat.mockImplementation(async (path: string) => {
if (path.endsWith('.meta')) {
throw Object.assign(new Error('metadata refused'), {
code: path === `${paths[0]}.meta` ? 'ENOENT' : 'EACCES'
})
}
return fs.stat(path)
})
const issues: AiVaultScanIssue[] = []
const discovery = await discoverFiles({
rootDir: root,
issues,
limit: 100,
agent: 'claude',
extensions: ['.jsonl'],
contentDependencyPath: (path) => `${path}.meta`
})
expect(discovery.files.find((entry) => entry.path === paths[0])?.sidecar).toBe('none')
expect(discovery.files.filter((entry) => entry.sidecar === 'unknown')).toHaveLength(4)
expect(issues).toEqual([
{
agent: 'claude',
path: `${paths[1]}.meta`,
message: 'Session metadata could not be read this scan.',
messageCode: 'sessionMetadataUnreadable'
}
])
})
it.skipIf(process.platform === 'win32')(
'reads retargeted and retargeted-back roots from disk',
async () => {
@@ -31,126 +31,6 @@ afterEach(() => {
vi.restoreAllMocks()
})
it('decodes a single owned unterminated tail without concatenation or cursor advancement', async () => {
const tail = JSON.stringify({ text: 'é😀 growing final record' })
const prefix = '\r\nmalformed\n{"type":"user"}\r\n'
const content = prefix + tail
source.chunks = [Buffer.from(content)]
const original = Buffer.concat
let copiedBytes = 0
vi.spyOn(Buffer, 'concat').mockImplementation((parts, total) => {
copiedBytes += parts.reduce((sum, part) => sum + part.length, 0)
return original(parts, total)
})
for (let index = 0; index < 20; index += 1) {
const lines: string[] = []
const result = await consumeCompleteJsonlLines({
path: '/log',
start: 41,
onLine: (line) => lines.push(line)
})
expect(lines).toEqual(['', 'malformed', '{"type":"user"}'])
expect(result).toEqual({
consumedThrough: 41 + Buffer.byteLength(prefix),
trailingPartialLine: tail,
bytesRead: Buffer.byteLength(content),
skippedRecords: []
})
expect(source.closed).toBe(true)
}
expect(copiedBytes).toBe(0)
})
it('still joins an unterminated multi-part UTF-8 tail exactly once', async () => {
const tail = JSON.stringify({ text: 'é😀'.repeat(20_000) })
const bytes = Buffer.from(tail)
const cut = bytes.indexOf(Buffer.from('😀')) + 2
source.chunks = [bytes.subarray(0, cut), bytes.subarray(cut)]
const original = Buffer.concat
const copiedBytes: number[] = []
vi.spyOn(Buffer, 'concat').mockImplementation((parts, total) => {
copiedBytes.push(parts.reduce((sum, part) => sum + part.length, 0))
return original(parts, total)
})
const onLine = vi.fn()
expect(await consumeCompleteJsonlLines({ path: '/log', start: 41, onLine })).toEqual({
consumedThrough: 41,
trailingPartialLine: tail,
bytesRead: bytes.length,
skippedRecords: []
})
expect(onLine).not.toHaveBeenCalled()
expect(source.closed).toBe(true)
expect(copiedBytes).toEqual([bytes.length])
})
it('bounds concatenation when the next chunk contains many complete lines', async () => {
source.chunks = Array.from({ length: 100 }, () => Buffer.from(`${'a\n'.repeat(1000)}x`))
const original = Buffer.concat
let copied = 0
const concat = vi.spyOn(Buffer, 'concat').mockImplementation((chunks, total) => {
copied += total ?? chunks.reduce((sum, chunk) => sum + chunk.length, 0)
return original(chunks, total)
})
let lines = 0
let result: Awaited<ReturnType<typeof consumeCompleteJsonlLines>>
try {
result = await consumeCompleteJsonlLines({
path: '/log',
start: 0,
onLine: () => {
lines += 1
}
})
} finally {
concat.mockRestore()
}
expect(lines).toBe(100000)
expect(result!).toEqual({
consumedThrough: 200099,
trailingPartialLine: 'x',
bytesRead: 200100,
skippedRecords: []
})
expect(copied).toBeLessThan(1000)
})
it('preserves UTF-8/CRLF carry, byte callbacks and stop offsets', async () => {
source.chunks = [Buffer.from('ab\r'), Buffer.from('\ncd\npartial')]
const lines: string[] = []
expect(
await consumeCompleteJsonlLines({
path: '/log',
start: 5,
onLine: () => {},
onLineBytes: (line) => lines.push(line.toString())
})
).toEqual({
consumedThrough: 12,
trailingPartialLine: 'partial',
bytesRead: 14,
skippedRecords: []
})
expect(lines).toEqual(['ab', 'cd'])
let stopped = false
expect(
await consumeCompleteJsonlLines({
path: '/log',
start: 5,
onLine: () => {
stopped = true
},
shouldStop: () => stopped
})
).toEqual({ consumedThrough: 9, trailingPartialLine: null, bytesRead: 14, skippedRecords: [] })
const unicode = Buffer.from('🦀\n')
source.chunks = [unicode.subarray(0, 2), unicode.subarray(2)]
const onLine = vi.fn()
await consumeCompleteJsonlLines({ path: '/log', start: 0, onLine })
expect(onLine).toHaveBeenCalledWith('🦀')
})
// Arbitrary chunk cuts must preserve UTF-8, CRLF boundaries and byte-accurate resume offsets.
it('yields identical lines and resume offsets for every single-byte chunk split', async () => {
const bigRecord = `{"d":${'"'.padEnd(2000, 'z')}"}`
@@ -280,42 +160,6 @@ it('leaves the cursor before an unterminated oversized tail and skips it once te
})
})
it('skips back-to-back oversized records without losing the cursor', async () => {
const buffer = Buffer.from(`${OVERSIZED}\n${OVERSIZED}\n{"a":1}\n`, 'utf-8')
source.chunks = chunksAt(buffer, 1, OVERSIZED.length + 1, OVERSIZED.length * 2 + 2)
const lines: string[] = []
const result = await consumeCompleteJsonlLines({
path: '/log',
start: 0,
onLine: (line) => lines.push(line)
})
expect(lines).toEqual(['{"a":1}'])
expect(result.consumedThrough).toBe(buffer.length)
expect(result.skippedRecords).toEqual([
{ byteOffset: 0, approximateBytes: OVERSIZED.length },
{ byteOffset: OVERSIZED.length + 1, approximateBytes: OVERSIZED.length }
])
})
it('accepts records exactly at the byte cap and a larger file of separate records', async () => {
const line = Buffer.alloc(MAX_SESSION_TRANSCRIPT_RECORD_BYTES, 'x')
source.chunks = [line, Buffer.from('\n'), line, Buffer.from('\n'), line]
const lengths: number[] = []
const result = await consumeCompleteJsonlLines({
path: '/log',
start: 41,
onLine: () => {},
onLineBytes: (bytes) => lengths.push(bytes.length)
})
expect(lengths).toEqual([line.length, line.length])
expect({ ...result, trailingPartialLine: result.trailingPartialLine?.length }).toEqual({
consumedThrough: 41 + 2 * (line.length + 1),
trailingPartialLine: line.length,
bytesRead: 3 * line.length + 2,
skippedRecords: []
})
})
it('counts UTF-8 bytes instead of decoded characters at the record cap', async () => {
const chars = Math.floor(MAX_SESSION_TRANSCRIPT_RECORD_BYTES / 3)
source.chunks = [Buffer.from('界'.repeat(chars)), Buffer.from('界\n{"a":1}\n')]
@@ -330,21 +174,6 @@ it('counts UTF-8 bytes instead of decoded characters at the record cap', async (
expect(result.consumedThrough).toBe(3 * (chars + 1) + 1 + 8)
})
it('never opens the transcript once the scan is cancelled', async () => {
source.chunks = [Buffer.from('{"a":1}\n')]
source.opens = 0
const onLine = vi.fn()
const read = consumeCompleteJsonlLines({
path: '/log',
start: 0,
onLine,
signal: AbortSignal.abort()
})
await expect(read).rejects.toSatisfy(isAiVaultScanCancelledError)
expect(source.opens).toBe(0)
expect(onLine).not.toHaveBeenCalled()
})
it('stops between chunks on cancel and releases the stream', async () => {
source.chunks = [Buffer.from('{"a":1}\n'), Buffer.from('{"b":2}\n'), Buffer.from('{"c":3}\n')]
const controller = new AbortController()
@@ -1,11 +1,10 @@
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { isAiVaultSessionRecoverableEmpty } from '../../shared/ai-vault/contracts/ai-vault-types'
import { scanAiVaultSessions } from './session-scanner'
import { parseClaudeSessionContent } from './scanners/claude/session-scanner-primary-parsers'
import { countSubagentTranscripts } from './scanners/claude/session-scanner-subagent-transcripts'
import { isolatedScanRoots, writeJsonlFile } from './session-scanner-test-fixtures'
let tempRoots: string[] = []
@@ -76,91 +75,6 @@ describe('recoverable-but-empty Claude sessions', () => {
expect(isAiVaultSessionRecoverableEmpty(session!)).toBe(true)
})
it('reports no recoverable signal for a plain metadata-only session', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-plain-empty-'))
tempRoots.push(root)
const roots = isolatedScanRoots(root)
const sessionId = 'plain-empty-session'
await writeJsonlFile(join(roots.claudeProjectsDir, 'project', `${sessionId}.jsonl`), [
{ type: 'mode', mode: 'default', sessionId },
{ type: 'permission-mode', permissionMode: 'default', sessionId }
])
const result = await scanAiVaultSessions({ ...roots, platform: 'darwin' })
const session = result.sessions.find((entry) => entry.sessionId === sessionId)
expect(session).toBeDefined()
expect(session?.messageCount).toBe(0)
expect(session?.queuedMessageCount).toBe(0)
expect(session?.subagentTranscriptCount).toBe(0)
expect(isAiVaultSessionRecoverableEmpty(session!)).toBe(false)
})
it('counts subagent transcripts for a session that has real turns without flagging it recoverable', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-nonempty-'))
tempRoots.push(root)
const roots = isolatedScanRoots(root)
const sessionId = 'conversation-session'
await writeJsonlFile(join(roots.claudeProjectsDir, 'project', `${sessionId}.jsonl`), [
{
type: 'user',
sessionId,
message: { role: 'user', content: 'Do the thing' }
}
])
await writeJsonlFile(
join(roots.claudeProjectsDir, 'project', sessionId, 'subagents', 'agent-x.jsonl'),
[
{
type: 'user',
sessionId,
message: { role: 'user', content: 'Subtask' }
}
]
)
const result = await scanAiVaultSessions({ ...roots, platform: 'darwin' })
const session = result.sessions.find((entry) => entry.sessionId === sessionId)
expect(session?.messageCount).toBe(1)
expect(session?.subagentTranscriptCount).toBe(1)
expect(isAiVaultSessionRecoverableEmpty(session!)).toBe(false)
})
it('counts queued messages net of remove and dequeue operations', async () => {
const sessionId = 'net-queue-session'
const content = [
{ type: 'mode', mode: 'default', sessionId },
...[1, 2, 3].map((n) => ({
type: 'queue-operation',
operation: 'enqueue',
sessionId,
content: `queued prompt ${n}`
})),
{ type: 'queue-operation', operation: 'dequeue', sessionId },
{
type: 'queue-operation',
operation: 'remove',
sessionId,
content: null
}
]
.map((line) => JSON.stringify(line))
.join('\n')
const file = {
path: `/tmp/${sessionId}.jsonl`,
mtimeMs: 0,
modifiedAt: '2026-07-08T16:30:00.000Z'
}
const session = await parseClaudeSessionContent(file, content, 'darwin', {
executionHostId: 'ssh:host'
})
expect(session?.queuedMessageCount).toBe(1)
})
it('picks up subagent transcripts written after the parent transcript last changed', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-late-sub-'))
tempRoots.push(root)
@@ -218,36 +132,3 @@ describe('recoverable-but-empty Claude sessions', () => {
expect(local?.subagentTranscriptCount).toBe(1)
})
})
describe('countSubagentTranscripts', () => {
it('returns 0 when the sibling subagents directory is absent', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-nosub-'))
tempRoots.push(root)
expect(await countSubagentTranscripts(join(root, 'session.jsonl'))).toBe(0)
})
it('counts only .jsonl transcripts, excluding meta sidecars', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-sub-count-'))
tempRoots.push(root)
const transcriptPath = join(root, 'session.jsonl')
const subagentsDir = join(root, 'session', 'subagents')
await writeJsonlFile(join(subagentsDir, 'agent-a.jsonl'), [{ type: 'user' }])
await writeJsonlFile(join(subagentsDir, 'agent-b.jsonl'), [{ type: 'user' }])
await writeFile(join(subagentsDir, 'agent-a.meta.json'), '{}')
expect(await countSubagentTranscripts(transcriptPath)).toBe(2)
})
it('excludes non-agent .jsonl files and directories named like transcripts', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-sub-predicate-'))
tempRoots.push(root)
const transcriptPath = join(root, 'session.jsonl')
const subagentsDir = join(root, 'session', 'subagents')
await writeJsonlFile(join(subagentsDir, 'agent-a.jsonl'), [{ type: 'user' }])
// The badge and on-demand lister must both exclude unrelated files and directories.
await writeFile(join(subagentsDir, 'notes.jsonl'), '{}')
await mkdir(join(subagentsDir, 'agent-x.jsonl'))
expect(await countSubagentTranscripts(transcriptPath)).toBe(1)
})
})
@@ -7,10 +7,6 @@ import type { AiVaultListResult } from '../../shared/ai-vault/contracts/ai-vault
import { parseSessionCandidates } from './session-scanner-candidate-parse'
import {
MAX_UNLISTED_ENTRIES,
scopeCwdStampOf,
peekSessionParseCacheEntry,
setSessionParseCacheColdTier,
type PersistedSessionParseCacheEntry,
storeSessionParseCacheEntry,
storeSessionScopeCwd,
resetSessionParseCacheForTests
@@ -281,66 +277,6 @@ it('delivers cancellation while traversing unchanged cached candidates', async (
}
})
it('uses a cold parsed latest Codex cwd after its unlisted row is evicted', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-scope-cold-cwd-'))
tempRoots.push(root)
const roots = isolatedScanRoots(root)
const path = join(roots.codexSessionsDir, 'rollout-cold-cwd.jsonl')
const content = [{ type: 'text', text: 'Find me' }]
await writeJsonlFile(path, [
{ type: 'session_meta', payload: { id: 'cold-cwd', cwd: '/elsewhere' } },
{ type: 'turn_context', payload: { cwd: '/repo' } },
{ type: 'response_item', payload: { type: 'message', role: 'user', content } }
])
await utimes(path, 1, 1)
for (const day of ['14', '15']) {
await writeRollout(roots.codexSessionsDir, `busy-${day}`, '/elsewhere', day)
}
const { mtimeMs, size: sizeBytes, mtime } = await stat(path)
const file = { path, mtimeMs, sizeBytes, modifiedAt: mtime.toISOString() }
const rows = new Map<string, PersistedSessionParseCacheEntry>()
const read = vi.fn((key: string) => rows.get(key))
setSessionParseCacheColdTier({
read,
readScopeCwds: (paths) => ({
found: new Map(
paths.flatMap((key) => {
const row = rows.get(key)
return row === undefined ? [] : [[key, { parsed: scopeCwdStampOf(row) }] as const]
})
),
parsed: true,
read: true
}),
stored: (key, row) => rows.set(key, row),
deleted: (key) => rows.delete(key)
})
const scan = () =>
scanAiVaultSessions({ ...roots, platform: 'linux', limit: 1, scopePaths: ['/repo'] })
expect((await scan()).sessions.some((row) => row.filePath === path)).toBe(false)
const parsed = await parseAgentSessionFileCached(
{ agent: 'codex', file, codexHome: null },
'linux'
)
expect(rows.get(path)?.session?.cwd).toBe('/repo')
for (let index = 0; index <= MAX_UNLISTED_ENTRIES; index++) {
storeSessionParseCacheEntry(`search-${index}`, {
mtimeMs: mtimeMs + 1,
sizeBytes: null,
platform: 'linux',
session: null,
resume: null
})
}
expect(peekSessionParseCacheEntry(path)).not.toHaveProperty('resume')
read.mockClear()
const found = (await scan()).sessions.filter((row) => row.filePath === path)
expect(found.map((row) => row.cwd)).toEqual(['/repo'])
expect(read).toHaveBeenCalledWith(path)
expect(peekSessionParseCacheEntry(path)?.session).toBe(parsed)
expect(await stat(path)).toMatchObject({ mtimeMs, size: sizeBytes })
})
it('walks a history larger than the spread-argument limit', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-scope-huge-'))
tempRoots.push(root)
-451
View File
@@ -2,11 +2,8 @@ import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { AI_VAULT_AGENTS } from '../../shared/ai-vault/contracts/ai-vault-types'
import { scanAiVaultSessions } from './session-scanner'
import { isolatedScanRoots, jsonLines } from './session-scanner-test-fixtures'
import { KIRO_FIXTURE_SESSION_ID } from './scanners/kiro/session-scanner-kiro-fixtures'
import { writeEveryAgentVault } from './session-scanner-every-agent-fixture'
// Use synchronous SQLite implementations because worker bundles are absent in the test runtime.
vi.mock(
@@ -48,177 +45,6 @@ afterEach(async () => {
})
describe('scanAiVaultSessions', () => {
it('indexes Claude and Codex transcripts with resume commands', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-'))
tempRoots.push(root)
const roots = isolatedScanRoots(root)
const claudeRoot = roots.claudeProjectsDir
const codexRoot = roots.codexSessionsDir
await mkdir(join(claudeRoot, 'project'), { recursive: true })
await mkdir(join(codexRoot, '2026', '05', '01'), { recursive: true })
await writeFile(
join(claudeRoot, 'project', 'claude-session.jsonl'),
[
JSON.stringify({
type: 'user',
sessionId: 'claude-session',
timestamp: '2026-05-01T10:00:00.000Z',
cwd: '/repo/app',
gitBranch: 'feature/vault',
isMeta: false,
message: { role: 'user', content: 'Implement the vault panel' }
}),
JSON.stringify({
type: 'assistant',
sessionId: 'claude-session',
timestamp: '2026-05-01T10:02:00.000Z',
cwd: '/repo/app',
gitBranch: 'feature/vault',
message: {
model: 'claude-sonnet-4-5',
usage: {
input_tokens: 100,
output_tokens: 40,
cache_read_input_tokens: 10,
cache_creation_input_tokens: 5
}
}
}),
JSON.stringify({
type: 'custom-title',
sessionId: 'claude-session',
timestamp: '2026-05-01T10:03:00.000Z',
customTitle: 'Vault polish pass'
})
].join('\n')
)
await writeFile(
join(
codexRoot,
'2026',
'05',
'01',
'rollout-2026-05-01T10-00-00-019f0000-1111-7222-8333-444444444444.jsonl'
),
[
JSON.stringify({
timestamp: '2026-05-01T11:00:00.000Z',
type: 'session_meta',
payload: {
id: '019f0000-1111-7222-8333-444444444444',
cwd: '/repo/app/packages/web',
git: { branch: 'feature/codex-vault' }
}
}),
JSON.stringify({
timestamp: '2026-05-01T11:00:01.000Z',
type: 'response_item',
payload: {
type: 'message',
role: 'user',
content: [
{ type: 'text', text: '# AGENTS.md instructions\n\n<INSTRUCTIONS>repo policy' }
]
}
}),
JSON.stringify({
timestamp: '2026-05-01T11:00:02.000Z',
type: 'response_item',
payload: {
type: 'message',
role: 'user',
content: [{ type: 'text', text: 'Fix the resume picker filters' }]
}
}),
JSON.stringify({
timestamp: '2026-05-01T11:00:03.000Z',
type: 'turn_context',
payload: { cwd: '/repo/app/packages/web', model: 'gpt-5.3-codex' }
}),
JSON.stringify({
timestamp: '2026-05-01T11:00:04.000Z',
type: 'event_msg',
payload: {
type: 'token_count',
info: {
total_token_usage: {
input_tokens: 500,
cached_input_tokens: 100,
output_tokens: 125,
reasoning_output_tokens: 25,
total_tokens: 625
}
}
}
}),
JSON.stringify({
timestamp: '2026-05-01T11:00:05.000Z',
type: 'event_msg',
payload: {
type: 'token_count',
info: {
total_token_usage: {
input_tokens: 500,
cached_input_tokens: 100,
output_tokens: 125,
reasoning_output_tokens: 25,
total_tokens: 625
}
}
}
})
].join('\n')
)
await writeFile(
join(root, 'session_index.jsonl'),
jsonLines([
{
id: '019f0000-1111-7222-8333-444444444444',
thread_name: 'Indexed Codex resume picker title'
}
])
)
const result = await scanAiVaultSessions({
...roots,
platform: 'darwin',
limit: 1,
unlimited: true
})
expect(result.issues).toEqual([])
expect(result.sessions).toHaveLength(2)
expect(result.sessions.map((session) => session.title).sort()).toEqual([
'Indexed Codex resume picker title',
'Vault polish pass'
])
const claude = result.sessions.find((session) => session.agent === 'claude')
expect(claude).toMatchObject({
sessionId: 'claude-session',
cwd: '/repo/app',
branch: 'feature/vault',
model: 'claude-sonnet-4-5',
messageCount: 2,
totalTokens: 155,
resumeCommand: "cd '/repo/app' && claude --resume 'claude-session'"
})
expect(claude?.firstUserPrompt).toBeUndefined()
const codex = result.sessions.find((session) => session.agent === 'codex')
expect(codex).toMatchObject({
sessionId: '019f0000-1111-7222-8333-444444444444',
cwd: '/repo/app/packages/web',
branch: 'feature/codex-vault',
model: 'gpt-5.3-codex',
messageCount: 2,
totalTokens: 625,
resumeCommand: `cd '/repo/app/packages/web' && CODEX_HOME='${root}' codex resume '019f0000-1111-7222-8333-444444444444'`
})
expect(codex?.firstUserPrompt).toBeUndefined()
})
it('indexes Codex sessions from Orca runtime homes with resumable commands', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-codex-runtime-'))
tempRoots.push(root)
@@ -272,281 +98,4 @@ describe('scanAiVaultSessions', () => {
resumeCommand: `cd '/Users/nwparker/orca/workspaces/orca/mem4' && CODEX_HOME='${runtimeHome}' codex resume '019e9693-64fc-7370-9c18-7e625c595d0f'`
})
})
it('indexes WSL home session roots', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-wsl-'))
tempRoots.push(root)
const roots = isolatedScanRoots(root)
const wslHome = join(root, 'wsl', 'Ubuntu', 'home', 'ada')
await mkdir(join(wslHome, '.claude', 'projects', 'repo'), { recursive: true })
await mkdir(
join(wslHome, '.local', 'share', 'orca', 'codex-runtime-home', 'home', 'sessions'),
{
recursive: true
}
)
await writeFile(
join(wslHome, '.claude', 'projects', 'repo', 'claude-wsl.jsonl'),
jsonLines([
{
type: 'user',
sessionId: 'claude-wsl',
timestamp: '2026-06-10T10:00:00.000Z',
cwd: '/home/ada/repo',
message: { role: 'user', content: 'Claude WSL title' }
}
])
)
await writeFile(
join(
wslHome,
'.local',
'share',
'orca',
'codex-runtime-home',
'home',
'sessions',
'codex-wsl.jsonl'
),
jsonLines([
{
timestamp: '2026-06-10T10:01:00.000Z',
type: 'session_meta',
payload: { id: 'codex-wsl', cwd: '/home/ada/repo' }
},
{
timestamp: '2026-06-10T10:01:01.000Z',
type: 'response_item',
payload: {
type: 'message',
role: 'user',
content: [{ type: 'text', text: 'Codex WSL title' }]
}
}
])
)
const result = await scanAiVaultSessions({
...roots,
wslHomeDirs: [wslHome],
platform: 'win32'
})
expect(result.issues).toEqual([])
expect(result.sessions.map((session) => session.title).sort()).toEqual([
'Claude WSL title',
'Codex WSL title'
])
expect(result.sessions.find((session) => session.agent === 'codex')?.codexHome).toBe(
join(wslHome, '.local', 'share', 'orca', 'codex-runtime-home', 'home')
)
})
it('skips hidden Codex context blocks when choosing session titles', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-codex-hidden-context-'))
tempRoots.push(root)
const roots = isolatedScanRoots(root)
await mkdir(join(roots.codexSessionsDir, '2026', '06', '11'), { recursive: true })
await writeFile(
join(roots.codexSessionsDir, '2026', '06', '11', 'rollout-hidden-context.jsonl'),
jsonLines([
{
timestamp: '2026-06-11T10:00:00.000Z',
type: 'session_meta',
payload: { id: 'hidden-context-session', cwd: '/repo/app' }
},
{
timestamp: '2026-06-11T10:00:01.000Z',
type: 'response_item',
payload: {
type: 'message',
role: 'user',
content: [
{
type: 'text',
text: '<codex_internal_context source="goal">\\nKeep going\\n</codex_internal_context>'
}
]
}
},
{
timestamp: '2026-06-11T10:00:02.000Z',
type: 'response_item',
payload: {
type: 'message',
role: 'user',
content: [{ type: 'text', text: 'Fix the title shown in the session list' }]
}
}
])
)
const result = await scanAiVaultSessions({
...roots,
platform: 'darwin'
})
expect(result.issues).toEqual([])
expect(result.sessions).toHaveLength(1)
expect(result.sessions[0]?.title).toBe('Fix the title shown in the session list')
expect(result.sessions[0]?.previewMessages.map((message) => message.text)).toEqual([
'Fix the title shown in the session list'
])
})
it('indexes every supported agent transcript format with native resume commands', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-all-agents-'))
tempRoots.push(root)
const { roots, antigravitySessionId, ompSessionFile, primeAgentSessionFile } =
await writeEveryAgentVault(root)
// Allow multiple fixtures per agent without evicting another agent under the recency cap.
const result = await scanAiVaultSessions({
...roots,
platform: 'darwin',
limit: AI_VAULT_AGENTS.length * 2
})
expect(result.issues).toEqual([])
expect(new Set(result.sessions.map((session) => session.agent))).toEqual(
new Set(AI_VAULT_AGENTS)
)
const commandByAgent = new Map(
result.sessions.map((session) => [session.agent, session.resumeCommand])
)
expect(commandByAgent.get('claude')).toBe(
"cd '/tmp/claude' && claude --resume 'claude-session'"
)
expect(commandByAgent.get('codex')).toBe(
`cd '/tmp/codex' && CODEX_HOME='${root}' codex resume 'codex-session'`
)
expect(commandByAgent.get('gemini')).toBe("gemini --resume 'gemini-session'")
expect(commandByAgent.get('antigravity')).toBe(`agy --conversation '${antigravitySessionId}'`)
expect(commandByAgent.get('copilot')).toBe(
"cd '/tmp/copilot' && copilot --resume='copilot-session'"
)
expect(commandByAgent.get('cursor')).toBe("cursor-agent --resume 'cursor-session'")
expect(commandByAgent.get('opencode')).toBe(
"cd '/tmp/opencode' && opencode --session 'opencode-session'"
)
expect(commandByAgent.get('opencode2')).toBe(
"cd '/tmp/opencode2' && opencode2 --standalone --session 'opencode2-session'"
)
expect(commandByAgent.get('zcode')).toBe("cd '/tmp/zcode' && zcode --resume 'zcode-session'")
expect(commandByAgent.get('grok')).toBe("cd '/tmp/grok' && grok --resume 'grok-session'")
expect(commandByAgent.get('hermes')).toBe(
"cd '/tmp/hermes' && hermes --resume 'hermes-session'"
)
expect(commandByAgent.get('rovo')).toBe(
"cd '/tmp/rovo' && acli rovodev run --restore 'rovo-session'"
)
expect(commandByAgent.get('openclaw')).toBe(
"cd '/tmp/openclaw' && openclaw --resume 'openclaw-session'"
)
expect(commandByAgent.get('pi')).toBe("cd '/tmp/pi' && pi --session 'pi-session'")
expect(commandByAgent.get('omp')).toBe(`cd '/tmp/omp' && omp --resume '${ompSessionFile}'`)
expect(commandByAgent.get('prime-agent')).toBe(
`cd '/tmp/prime-agent' && prime-agent --resume '${primeAgentSessionFile}'`
)
expect(commandByAgent.get('cline')).toBe("cd '/tmp/cline' && cline --id 'cline-session'")
expect(commandByAgent.get('devin')).toBe("cd '/tmp/devin' && devin --resume 'devin-session'")
expect(commandByAgent.get('droid')).toBe("cd '/tmp/droid' && droid --resume 'droid-session'")
expect(commandByAgent.get('muse')).toBe("cd '/tmp/muse' && muse resume 'muse-session'")
expect(commandByAgent.get('kimi')).toBe(
"cd '/tmp/kimi' && kimi --session 'session_kimi-session'"
)
expect(commandByAgent.get('jcode')).toBe(
"cd '/tmp/jcode' && jcode --resume 'session_jcode-session'"
)
expect(commandByAgent.get('kiro')).toBe(
`cd '/tmp/kiro' && kiro-cli chat --tui --resume-id '${KIRO_FIXTURE_SESSION_ID}'`
)
expect(result.sessions.find((session) => session.agent === 'rovo')).toMatchObject({
filePath: join(roots.rovoSessionsDir, 'rovo-session', 'metadata.json'),
messageCount: 1,
previewMessages: [expect.objectContaining({ text: 'Rovo title' })]
})
const ompSession = result.sessions.find((session) => session.agent === 'omp')
expect(ompSession?.model).toBe('gpt-5.4-mini')
expect(ompSession?.totalTokens).toBe(160)
const primeAgentSession = result.sessions.find((session) => session.agent === 'prime-agent')
expect(primeAgentSession?.model).toBe('inference/big-model')
expect(primeAgentSession?.title).toBe('Prime Agent title')
})
it('captures an in-progress OMP model from model_change before any assistant reply', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-omp-mc-'))
tempRoots.push(root)
const roots = isolatedScanRoots(root)
await mkdir(roots.ompSessionsDir, { recursive: true })
await writeFile(
join(roots.ompSessionsDir, 'omp-in-progress.jsonl'),
jsonLines([
{
type: 'session',
id: 'omp-in-progress',
timestamp: '2026-05-01T10:00:00.000Z',
cwd: '/tmp/omp'
},
{ type: 'model_change', model: 'omp-mc-only-model', timestamp: '2026-05-01T10:00:01.000Z' },
{
type: 'message',
timestamp: '2026-05-01T10:00:02.000Z',
message: { role: 'user', content: [{ type: 'text', text: 'first prompt' }] }
}
])
)
const result = await scanAiVaultSessions({ ...roots, platform: 'darwin', limit: 5 })
const session = result.sessions.find((s) => s.agent === 'omp')
expect(session?.model).toBe('omp-mc-only-model')
})
it('strips newline-heavy Grok user_query envelopes without regex matching', async () => {
const matchSpy = vi.spyOn(String.prototype, 'match')
const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-grok-large-'))
tempRoots.push(root)
const roots = isolatedScanRoots(root)
const sessionDir = join(roots.grokSessionsDir, encodeURIComponent('/tmp/grok'), 'large-session')
const requestText = 'Grok large title\n'.repeat(300)
await mkdir(sessionDir, { recursive: true })
await writeFile(
join(sessionDir, 'summary.json'),
JSON.stringify({
info: { id: 'large-session', cwd: '/tmp/grok' },
created_at: '2026-05-01T10:04:00.000Z'
})
)
await writeFile(
join(sessionDir, 'chat_history.jsonl'),
jsonLines([
{
type: 'user',
content: `<USER_INFO>context</USER_INFO><USER_QUERY>\n${requestText}</USER_QUERY>`
}
])
)
const result = await scanAiVaultSessions({
...roots,
platform: 'darwin',
limit: 5
})
expect(result.issues).toEqual([])
expect(result.sessions[0]?.title).toContain('Grok large title')
expect(result.sessions[0]?.title).not.toContain('USER_QUERY')
const usedGrokWrapperMatch = matchSpy.mock.calls.some(
([pattern]) =>
pattern instanceof RegExp &&
pattern.source.includes('<user_query>') &&
pattern.source.includes('[\\s\\S]')
)
expect(usedGrokWrapperMatch).toBe(false)
})
})
@@ -11,7 +11,6 @@ import { setStructuredAgentSessionHost } from '../native-chat/agent-session-wire
import { prepareStructuredChatCliFork } from './structured-chat-cli-fork'
import { structuredAgentRuntimeRegistration } from '../runtime/agent-session/installation/structured-agent-runtime-registrations'
import { prepareLegacySharedCodexSessionResume } from '../codex/history/resume/codex-legacy-session-resume'
import { AiVaultPrepareSessionResumeParams } from '../../shared/rpc-contract/ai-vault-params'
let root: string | undefined
const request = {
@@ -143,35 +142,6 @@ it.runIf(process.platform === 'win32')(
}
)
it('copies OpenCode directly from the selected record and preserves its typed account and copy id', async () => {
root = await mkdtemp(join(tmpdir(), 'chat-cli-fork-'))
const record = agentSessionRecordFixture()
record.provider = 'opencode'
record.accountHome = { kind: 'opencode', locator: { kind: 'unmanaged' } }
record.providerHandleChain = [
{
...record.providerHandleChain[0]!,
handle: { agent: 'opencode', transport: 'acp', nativeId: 'ses_source' }
}
]
const copy = vi.fn(async () => ({ sessionId: 'ses_copy' }))
install(record, copy)
const result = await prepareStructuredChatCliFork(request, prepare)
expect(copy).toHaveBeenCalledWith(
expect.objectContaining({
accountHome: record.accountHome,
providerSessionId: 'ses_source',
identity: expect.objectContaining({ sessionId: record.sessionId })
})
)
expect(result.cliForkSource).toMatchObject({
agent: 'opencode',
sourceAgent: 'opencode2',
sessionId: 'ses_copy'
})
expect(prepare).not.toHaveBeenCalled()
})
it('uses the Pi file handle and refuses a mismatched saved header or missing handle', async () => {
root = await mkdtemp(join(tmpdir(), 'chat-cli-fork-'))
const filePath = join(root, '2026-10-15_12345678-abcd-1234-abcd-123456789abc.jsonl')
@@ -231,25 +201,3 @@ it('uses the Pi file handle and refuses a mismatched saved header or missing han
'no saved conversation'
)
})
it('refuses a foreign workspace or WSL record and rejects mixed chat/row requests', async () => {
root = await mkdtemp(join(tmpdir(), 'chat-cli-fork-'))
const record = agentSessionRecordFixture()
install(record)
await expect(
prepareStructuredChatCliFork(
{ ...request, sourceChat: { ...request.sourceChat, workspaceId: 'other' } },
prepare
)
).rejects.toThrow('on this host')
record.location.wslDistro = 'Ubuntu'
await expect(prepareStructuredChatCliFork(request, prepare)).rejects.toThrow('on this host')
expect(
AiVaultPrepareSessionResumeParams.safeParse({
...request,
agent: 'claude',
filePath: '/foreign'
}).success
).toBe(false)
expect(prepare).not.toHaveBeenCalled()
})
@@ -1,414 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { z } from 'zod'
import { readAcpFixture } from '../acp/acp-timeline-fixture.test-support'
import type { AgentSessionProviderHandle } from '../../shared/agent-session/lifecycle/agent-session-provider-handle'
import type { AiVaultAgent } from '../../shared/ai-vault/contracts/ai-vault-types'
import { setStructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-registry'
import {
assertLegacyAiVaultResumeAllowed,
assertLegacyAiVaultResumeCommandAllowed,
OPENS_EVERY_STRUCTURED_CHAT,
projectStructuredAiVaultSessions
} from './structured-session-ownership'
import { installOwnership, listResult } from './structured-session-ownership.test-support'
import { STRUCTURED_AGENT_RUNTIME_REGISTRATIONS } from '../runtime/agent-session/installation/structured-agent-runtime-registrations'
const OPENCODE_ID = 'ses_2f9aB3cD4eF5gH6iJ7kL8mN9oP'
const GROK_ID = '019fd600-1a2b-7c3d-8e4f-5a6b7c8d9e0f'
const OMP_ID = '019fd611-2b3c-7d4e-9f50-6b7c8d9e0f1a'
const PI_ID = '019fd622-3c4d-7e5f-a061-7c8d9e0f1a2b'
const OTHER_UUID = '019fd633-4d5e-7f60-b172-8d9e0f1a2b3c'
const OMP_FILE = `/Users/me/.omp/agent/sessions/--Users-me-repo--/2026-10-09T10-00-00-000Z_${OMP_ID}.jsonl`
const PI_FILE = `/Users/me/.pi/agent/sessions/--Users-me-repo--/2026-10-09T10-00-00-000Z_${PI_ID}.jsonl`
const acp = (
agent: 'opencode' | 'opencode2' | 'grok' | 'omp',
nativeId: string
): AgentSessionProviderHandle => ({
transport: 'acp',
agent,
nativeId
})
const PI_HANDLE: AgentSessionProviderHandle = {
transport: 'jsonl-rpc',
agent: 'pi',
nativeId: PI_FILE
}
const allowed = (command: string) =>
expect(
assertLegacyAiVaultResumeCommandAllowed(command, async () => undefined)
).resolves.toBeUndefined()
const refused = (command: string) =>
expect(assertLegacyAiVaultResumeCommandAllowed(command, async () => undefined)).rejects.toThrow(
'agent_session_conflict'
)
function ownedRow(
agent: AiVaultAgent,
sessionId: string,
filePath: string,
title = 'First prompt'
) {
const result = listResult()
result.sessions = [
{
...result.sessions[0]!,
agent,
sessionId,
filePath,
title
}
]
return projectStructuredAiVaultSessions(result, OPENS_EVERY_STRUCTURED_CHAT).sessions[0]
}
afterEach(() => setStructuredAgentSessionHost(null))
describe('Session History rows owned by OpenCode, Grok, OMP and Pi chats', () => {
it.each([
{
handle: acp('opencode', OPENCODE_ID),
rowAgent: 'opencode' as const,
sessionId: OPENCODE_ID,
filePath: `/Users/me/.local/share/opencode/opencode.db#${OPENCODE_ID}`
},
{
handle: acp('opencode', OPENCODE_ID),
rowAgent: 'opencode2' as const,
sessionId: OPENCODE_ID,
filePath: `/Users/me/.local/share/opencode/opencode.db#${OPENCODE_ID}`
},
// Upgraded OpenCode databases can retain both history formats under one conversation id.
{
handle: acp('opencode2', OPENCODE_ID),
rowAgent: 'opencode2' as const,
sessionId: OPENCODE_ID,
filePath: `/Users/me/.local/share/opencode/opencode.db#${OPENCODE_ID}`
},
{
handle: acp('opencode2', OPENCODE_ID),
rowAgent: 'opencode' as const,
sessionId: OPENCODE_ID,
filePath: `/Users/me/.local/share/opencode/opencode.db#${OPENCODE_ID}`
},
{
handle: acp('grok', GROK_ID),
rowAgent: 'grok' as const,
sessionId: GROK_ID,
filePath: `/Users/me/.grok/sessions/%2FUsers%2Fme%2Frepo/${GROK_ID}/summary.json`
},
{
handle: acp('omp', OMP_ID),
rowAgent: 'omp' as const,
sessionId: OMP_ID,
filePath: OMP_FILE
},
{
handle: PI_HANDLE,
rowAgent: 'pi' as const,
sessionId: PI_ID,
filePath: PI_FILE
}
])(
'owns the $rowAgent row of a $handle.agent chat under the chat name and refuses preparing its resume',
({ handle, rowAgent, sessionId, filePath }) => {
// An unnamed chat's row keeps the CLI's title; once named, the row shows the chat's name.
installOwnership({ handle })
expect(ownedRow(rowAgent, sessionId, filePath)).toMatchObject({ title: 'First prompt' })
installOwnership({ handle, conversationName: 'Quokka harbor chat' })
expect(ownedRow(rowAgent, sessionId, filePath)).toMatchObject({
title: 'Quokka harbor chat',
structuredSession: {
sessionId: 'session-alpha',
workspaceId: 'workspace-1'
}
})
expect(
ownedRow(rowAgent, OTHER_UUID, filePath.replace(sessionId, OTHER_UUID))
).not.toHaveProperty('structuredSession')
expect(() =>
assertLegacyAiVaultResumeAllowed({
agent: rowAgent,
sessionId,
filePath,
codexHome: null,
executionHostId: 'local'
})
).toThrow('agent_session_conflict')
}
)
it('does not own a row of one agent for a chat of another with the same id', () => {
installOwnership({ handle: acp('omp', OMP_ID) })
expect(ownedRow('pi', OMP_ID, OMP_FILE)).not.toHaveProperty('structuredSession')
})
})
it('shows the saved native name over a recorded OMP provider title, retaining that title while unnamed', async () => {
// Scrubbed OMP 17.0.5 ACP output already replayed by acp-structured-omp-recordings.test.ts.
const frames = await readAcpFixture('omp-v17-reply-after-thought')
const info = frames.flatMap((frame) => {
const parsed = z
.object({
sessionId: z.string(),
update: z.object({ sessionUpdate: z.literal('session_info_update'), title: z.string() })
})
.safeParse(frame.message.params)
return frame.direction === 'in' && frame.message.method === 'session/update' && parsed.success
? [parsed.data]
: []
})[0]
if (!info) {
throw new Error('Recorded OMP session title missing')
}
const handle = acp('omp', info.sessionId)
const row = () =>
ownedRow('omp', info.sessionId, '/recording/omp-session.jsonl', info.update.title)
installOwnership({ handle })
expect(row()).toMatchObject({
title: info.update.title,
structuredSession: { sessionId: 'session-alpha' }
})
installOwnership({ handle, conversationName: 'My saved OMP name' })
expect(row()).toMatchObject({
title: 'My saved OMP name',
structuredSession: { sessionId: 'session-alpha' }
})
})
describe('terminal resumes of a conversation an OpenCode chat owns', () => {
it.each([
`opencode --session ${OPENCODE_ID}`,
`opencode -s ${OPENCODE_ID}`,
`opencode --session=${OPENCODE_ID}`,
`opencode2 --standalone --session '${OPENCODE_ID}'`,
`cd '/Users/me/repo' && opencode run -s ${OPENCODE_ID} "keep going"`,
`opencode -c`,
`opencode --continue`,
`opencode --session`,
`opencode --session ${OPENCODE_ID.toLowerCase()}`,
// After `--` the flag is prompt text, so the session is resumed, not forked.
`opencode -s ${OPENCODE_ID} -- --fork`
])('refuses %s', async (command) => {
installOwnership({ handle: acp('opencode', OPENCODE_ID) })
await refused(command)
})
it.each([
`opencode --session ses_otherSession123`,
`opencode --session ${OPENCODE_ID} --fork`,
`opencode -c --fork`,
`opencode`,
`opencode export ${OPENCODE_ID}`,
`cd /Users/me/src/opencode && bash -c 'make'`
])('allows %s', async (command) => {
installOwnership({ handle: acp('opencode', OPENCODE_ID) })
await allowed(command)
})
it.each([
`opencode --session ${OPENCODE_ID}`,
`opencode2 --standalone --session '${OPENCODE_ID}'`
])('refuses %s while an OpenCode 2 chat owns it', async (command) => {
installOwnership({ handle: acp('opencode2', OPENCODE_ID) })
await refused(command)
})
})
describe('terminal resumes of a conversation a Grok chat owns', () => {
it.each([
`grok --resume ${GROK_ID}`,
`grok -r ${GROK_ID.toUpperCase()}`,
`grok --resume=${GROK_ID}`,
`grok --load=${GROK_ID}`,
`grok -p "continue" --resume "${GROK_ID}"`,
`grok --resume`,
`grok -r --minimal`,
`grok -c`,
`grok --continue`,
// A non-UUID value is a title, which may name the owned session.
`grok --resume "auth refactor"`,
`grok --resume ${GROK_ID} -- --fork-session`
])('refuses %s', async (command) => {
installOwnership({ handle: acp('grok', GROK_ID) })
await refused(command)
})
it.each([
`grok --resume ${OTHER_UUID}`,
`grok --resume ${GROK_ID} --fork-session`,
`grok -c --fork-session`,
`grok --session-id ${OTHER_UUID}`,
`grok -- "fix the bug"`
])('allows %s', async (command) => {
installOwnership({ handle: acp('grok', GROK_ID) })
await allowed(command)
})
})
describe('terminal resumes of a conversation an OMP chat owns', () => {
it.each([
`omp --resume ${OMP_ID}`,
`omp --resume '${OMP_FILE}'`,
`omp -r ${OMP_ID.slice(0, 8)}`,
`omp --session=${OMP_ID.slice(0, 13)}`,
`omp --session ./2026-10-09T10-00-00-000Z_${OMP_ID}.jsonl`,
`omp --resume`,
`omp -c`,
`omp --continue "what next"`
])('refuses %s', async (command) => {
installOwnership({ handle: acp('omp', OMP_ID) })
await refused(command)
})
it.each([
`omp --resume ${OTHER_UUID}`,
`omp --resume ${OTHER_UUID.slice(0, 8)}`,
`omp --resume /Users/me/.omp/agent/sessions/--Users-me-repo--/2026-10-09T10-00-00-000Z_${OTHER_UUID}.jsonl`,
`omp --fork ${OMP_ID}`,
`omp "hello"`
])('allows %s', async (command) => {
installOwnership({ handle: acp('omp', OMP_ID) })
await allowed(command)
})
})
describe('terminal resumes of a conversation a Pi chat owns', () => {
it.each([
`pi --session ${PI_ID}`,
`pi --session '${PI_FILE}'`,
`pi --session=${PI_FILE}`,
`pi --session ${PI_ID.slice(0, 8)}`,
`pi --session-id ${PI_ID}`,
`pi --session-id=${PI_ID}`,
`pi -c`,
`pi --continue`,
// `--resume` opens a picker; the next token is a prompt, not a target.
`pi --resume ${OTHER_UUID}`,
`pi -r`
])('refuses %s', async (command) => {
installOwnership({ handle: PI_HANDLE })
await refused(command)
})
it.each([
`pi --session ${OTHER_UUID}`,
`pi --session-id ${OTHER_UUID}`,
`pi --session /Users/me/.pi/agent/sessions/--Users-me-repo--/2026-10-09T10-00-00-000Z_${OTHER_UUID}.jsonl`,
`pi --fork '${PI_FILE}'`,
`pi "hello"`,
`cd /Users/me/pi && bash -c 'make'`
])('allows %s', async (command) => {
installOwnership({ handle: PI_HANDLE })
await allowed(command)
})
})
// Their CLIs read flags case-sensitively, unlike Claude's and Codex's folded flags.
describe('flags in another case', () => {
it.each([
{ handle: PI_HANDLE, command: `rg foo src/main/pi -C 3` },
{ handle: PI_HANDLE, command: `pi --SESSION ${PI_ID}` },
{ handle: acp('opencode', OPENCODE_ID), command: `opencode -C` },
{ handle: acp('grok', GROK_ID), command: `grok -R ${GROK_ID}` },
{ handle: acp('omp', OMP_ID), command: `omp --Continue` }
])("are not the agent's resume flags: $command", async ({ handle, command }) => {
installOwnership({ handle })
await allowed(command)
})
it('still fold for Claude', async () => {
installOwnership({ provider: 'claude', providerSessionId: PI_ID })
await refused(`claude -C`)
})
})
describe('the agent named again inside its own command', () => {
it.each([
{
handle: acp('opencode', OPENCODE_ID),
command: `opencode -s ${OPENCODE_ID} ~/src/opencode --fork`
},
{
handle: acp('grok', GROK_ID),
command: `grok -r ${GROK_ID} --cwd ~/src/grok --fork-session`
},
{ handle: PI_HANDLE, command: `pi --session pi` }
])('is an argument: $command', async ({ handle, command }) => {
installOwnership({ handle })
await allowed(command)
})
it.each(['\r', '\r\n'])('ends at a %j line break, as a PTY Enter sends', async (lineBreak) => {
installOwnership({ handle: PI_HANDLE })
await refused(`pi --session ${OTHER_UUID}${lineBreak}pi --session ${PI_ID}${lineBreak}`)
await allowed(`pi --session ${OTHER_UUID}${lineBreak}echo -c${lineBreak}`)
installOwnership({ handle: acp('opencode', OPENCODE_ID) })
await refused(`opencode -s ses_other${lineBreak}opencode -s ${OPENCODE_ID}${lineBreak}`)
await allowed(`opencode -s ses_other${lineBreak}echo -c${lineBreak}`)
})
it('ends at a newline, which starts another command', async () => {
installOwnership({ handle: PI_HANDLE })
await allowed(`pi --session ${OTHER_UUID}\necho -c`)
await refused(`echo hi\npi --session ${PI_ID}`)
})
})
describe('another agent named in a command', () => {
it.each([
`echo pi && claude --resume ${PI_ID}`,
`echo grok && claude --resume ${PI_ID}`,
`cd /Users/me/omp && codex resume ${PI_ID}`
])('reads a Claude or Codex resume as theirs, not a Pi one: %s', async (command) => {
installOwnership({ handle: PI_HANDLE })
await allowed(command)
})
it('still reads a Pi resume that follows a Claude one', async () => {
installOwnership({ handle: PI_HANDLE })
await refused(`claude --resume ${OTHER_UUID}; pi --session ${PI_ID}`)
})
})
// terminal.send parses every submission, so frequent agent names must not cause repeated scans.
describe('parsing cost', () => {
afterEach(() => vi.restoreAllMocks())
it('reads each token once per agent however often agents are named', async () => {
installOwnership({ handle: PI_HANDLE })
const parsedArgs = STRUCTURED_AGENT_RUNTIME_REGISTRATIONS.map(({ sessionHistory }) =>
vi.spyOn(sessionHistory, 'parseResumeArgs')
)
const line = 'the claude agent said codex and pi and grok are fine; omp wrote opencode output\n'
const text = line.repeat(2_000)
const tokenCount = text.split(/\s+/).filter(Boolean).length
await allowed(text)
const argsRead = parsedArgs
.flatMap((spy) => spy.mock.calls)
.reduce((sum, [args]) => sum + args.length, 0)
expect(argsRead).toBeLessThanOrEqual(tokenCount * parsedArgs.length)
})
it('reads one long command once per agent', async () => {
installOwnership({ handle: PI_HANDLE })
const parsedArgs = STRUCTURED_AGENT_RUNTIME_REGISTRATIONS.map(({ sessionHistory }) =>
vi.spyOn(sessionHistory, 'parseResumeArgs')
)
const text = `claude ${'pi codex grok ~/src/claude '.repeat(20_000)}`
const tokenCount = text.split(/\s+/).filter(Boolean).length
await allowed(text)
const argsRead = parsedArgs
.flatMap((spy) => spy.mock.calls)
.reduce((sum, [args]) => sum + args.length, 0)
expect(argsRead).toBeLessThanOrEqual(tokenCount * parsedArgs.length)
})
it('still refuses an owned resume after many mentions', async () => {
installOwnership({ handle: PI_HANDLE })
await refused(`${'echo pi; '.repeat(5_000)}pi --session ${PI_ID}`)
})
})