Repository navigation
feat(orcad): migration manifest and dormant-state contracts (#16741 T6-7) - #24422
Conversation
…6-7) Adds the shared contracts for converting a desktop catalog into a dormant managed-server catalog: the versioned migration manifest, import receipts, dormant worktree/workspace/automation/session/client-state validation, scrollback snapshot descriptors, migration preflight categories, catalog state and staged-catalog normalization. Nothing calls them yet. - The manifest is a cross-version artifact: it carries version 1 and any other version is refused (orcad_migration_manifest_version_unsupported). - Workspace references accept `folder:` keys alongside `worktree:` keys and bare worktree ids; each must belong to the manifest's own catalog. - Every list and payload is bounded: the manifest at 768 KiB, scrollback at 512 snapshots, each within the terminal store limit, 256 MiB in total and fixed-size chunks. - Workspace sessions are validated with main's own parseWorkspaceSession, so the contract tracks the current session shape instead of a frozen copy. Porting note (source: #16741 a68b6f3): - Adapted: production parsers no longer cast. Each structuredClone(...) as T became a type-guard predicate that runs the same field checks; host-id arrays narrow through isWorkspaceHostId, and manual repo order now requires a real workspace host id, as its type always claimed. - Split to stay under 300 lines: manifest field helpers and the automation run field checks moved into their own modules. - Excluded: terminal publications and live terminal bindings (T7/T8) and the source-cutover contract (T8).
There was a problem hiding this comment.
ℹ️ Minor suggestions only.
Reviewed changes
- Manifest contract (
orcad-migration-manifest*.ts) — versioned catalog payload (repositories, project groups, folder workspaces), canonical deterministic serialization, import receipts, digest format, and a 768 KiB cap. - Dormant state (
orcad-migration-dormant-*.ts) — worktree metadata/lineage, workspace lineage, sparse presets, retired names/namespaces, the workspace session, scrollback snapshot descriptors, automations/runs, and client state, each with bounds and destination-ownership scope checks. - Session + automation validation — session references validated against main's own
parseWorkspaceSession, and field/scope checks for automations and their final runs. - Client state + scrollback wire — mobile tab selections, UI routing, saved port forwards, hosted-browser close intents; chunked base64 scrollback request/result schemas.
- Catalog state, staged catalogs, preflight — catalog state/abort, fail-closed staged-catalog normalization, and the blocker/dependency vocabulary.
- Tests — five new files (31 tests pass locally).
ℹ️ Receipt and staged-catalog version gates are tied to the manifest version
parseReceipt and parseStagedCatalog reject any version that is not ORCAD_MIGRATION_MANIFEST_VERSION, and both normalizers drop rejected entries fail-closed. Receipts and staged catalogs are destination-persisted records with their own shape, so bumping the manifest wire version would silently discard every record written under the older version rather than migrating or recognizing it. This is latent (nothing persists yet), but it is worth deciding whether these local artifacts should carry an independent version before the deployment slices start writing them.
Technical details
# Receipts/staged catalogs share the manifest version constant
## Affected sites
- src/shared/orcad-migration-manifest-validation.ts:248 — `parseReceipt` requires `value.version === ORCAD_MIGRATION_MANIFEST_VERSION`
- src/shared/orcad-migration-staged-catalog-validation.ts:39 — `parseStagedCatalog` requires the same
- src/shared/orcad-migration-manifest-validation.ts:78 — `normalizeOrcadMigrationImportReceipts` drops invalid receipts
- src/shared/orcad-migration-staged-catalog-validation.ts:17 — `normalizeOrcadMigrationStagedCatalogs` drops invalid catalogs
## Required outcome
- An old-but-well-formed receipt/staged catalog must not be mistaken for corrupt data when the manifest version advances.
## Open questions for the human
- Should receipts and staged catalogs have their own version constant, or is "they bump together with the manifest" the intended contract?deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
| if (!['existing', 'new_per_run'].includes(String(record.workspaceMode))) { | ||
| throw new Error('orcad_migration_dormant_automation_workspace_mode_invalid') | ||
| } | ||
| optionalNullableString(record.workspaceId, 'orcad_migration_dormant_automation_workspace_invalid') |
There was a problem hiding this comment.
optionalNullableString treats a missing workspaceId as valid, but Automation.workspaceId is required in the type. Downstream, assertOrcadMigrationDormantAutomationReferences treats anything that is not null as a workspace key and calls owns() with it, so an omitted field raises a raw TypeError from parseWorkspaceKey rather than one of the contract's labeled orcad_migration_* errors. The same applies to AutomationRun.workspaceId at line 158.
Technical details
# Missing workspaceId crashes the reference check instead of failing the parse
## Affected sites
- src/shared/orcad-migration-dormant-automation-validation.ts:107 — `optionalNullableString(record.workspaceId, ...)` in `isMigratedAutomation`
- src/shared/orcad-migration-dormant-automation-validation.ts:158 — same in `isMigratedAutomationRun`
- src/shared/orcad-migration-dormant-automation-validation.ts:57 / :67 — `automation.workspaceId !== null && !args.owns(automation.workspaceId)` dereferences an absent value
## Required outcome
- A manifest omitting `workspaceId` must be refused with a specific `orcad_migration_*` error, not a raw `TypeError` from `parseWorkspaceKey`.
## Suggested approach
- Validate `workspaceId` as required-nullable (`string | null`) in both type guards, or have `owns()` treat a non-string argument as not-owned.
## Evidence
- Verified locally: deleting `workspaceId` from the automation test fixture makes `parseOrcadMigrationManifest` throw `TypeError: Cannot read properties of undefined (reading 'startsWith')`.|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (21)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review. 📝 WalkthroughWalkthroughThe changes add shared ORCAD migration contracts and validators for manifests, catalog states, dormant state, client state, automation records, workspace sessions, and terminal scrollback. The parsers enforce field formats, collection limits, identity uniqueness, and references to destination repositories, workspaces, and owned worktrees. New tests cover parsing rules, reference checks, size limits, and transfer data validation. Priority: ⬇️ Low Merge Risk: ⚪ Minimal · up to This change adds migration data contracts and validators that nothing calls yet, so user behavior does not change. No merge-blocking issue remains. Security Architecture ReviewSecurity architecture risk: 🔵 Low · up to The new contracts include useful identity, reference, and size checks, and no active migration execution path was identified. Risk is limited today, but these checks do not establish authorization, content authenticity, or durable recovery guarantees for the future importer. Retained concerns Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
| const manifestSha256 = requiredString(value.manifestSha256, 'manifestSha256') | ||
| if (!/^[a-f0-9]{64}$/.test(manifestSha256)) { | ||
| throw new Error('orcad_migration_manifest_digest_invalid') |
There was a problem hiding this comment.
Digest does not verify content A manifest whose payload changes while its
manifestSha256 stays the same still passes this parser: the digest is checked only for format. The catalog-state contract then uses that declared digest as the migration identity, so two different payloads can appear to have the same identity.
| const worktreeId = parsed?.type === 'worktree' ? parsed.worktreeId : value | ||
| return args.repositoryIds.has(getRepoIdFromWorktreeId(worktreeId)) |
There was a problem hiding this comment.
Invalid worktree IDs pass If a dormant-state reference contains a bare repository ID or
repo-1::, this check treats it as owned because the extracted repository ID is in the catalog. Neither value is a valid worktree ID, so the accepted manifest can leave the destination with workspace references it cannot resolve.
Knowledge Base Used: Workspace and worktree lifecycle
| requiredString(value.id, 'folderWorkspace.id') | ||
| requiredString(value.projectGroupId, 'folderWorkspace.projectGroupId') |
There was a problem hiding this comment.
Folder group can be missing A folder workspace passes validation when its
projectGroupId names a group absent from the manifest. That produces a catalog with a folder workspace whose required group relationship cannot be restored or used for routing.
Knowledge Base Used: Workspace and worktree lifecycle
| function isMigratedFolderWorkspace(value: unknown): value is FolderWorkspace { | ||
| if (!isRecord(value)) { | ||
| throw new Error('orcad_migration_manifest_folder_workspace_invalid') | ||
| } | ||
| requiredString(value.id, 'folderWorkspace.id') | ||
| requiredString(value.projectGroupId, 'folderWorkspace.projectGroupId') | ||
| requiredString(value.name, 'folderWorkspace.name') | ||
| requiredString(value.folderPath, 'folderWorkspace.folderPath') | ||
| requiredFiniteNumber(value.sortOrder, 'folderWorkspace.sortOrder') | ||
| requiredFiniteNumber(value.lastActivityAt, 'folderWorkspace.lastActivityAt') | ||
| requiredFiniteNumber(value.createdAt, 'folderWorkspace.createdAt') | ||
| requiredFiniteNumber(value.updatedAt, 'folderWorkspace.updatedAt') | ||
| for (const key of ['isArchived', 'isUnread', 'isPinned'] as const) { | ||
| if (typeof value[key] !== 'boolean') { | ||
| throw new Error(`orcad_migration_manifest_folder_workspace_${key}_invalid`) | ||
| } | ||
| } | ||
| return true |
There was a problem hiding this comment.
| export function parseOrcadMigrationDormantWorkspaceSession(value: unknown): WorkspaceSessionState { | ||
| const parsed = parseWorkspaceSession(value) | ||
| if (!parsed.ok) { | ||
| throw new Error(`orcad_migration_dormant_workspace_session_invalid:${parsed.error}`) | ||
| } | ||
| return parsed.value | ||
| } |
There was a problem hiding this comment.
Invalid session rows disappear If a migration manifest contains a malformed terminal, editor, or browser row,
parseWorkspaceSession can drop that row and return a successful parse. The migration then accepts a smaller session instead of rejecting the incomplete transfer, silently losing workspace state.
Knowledge Base Used: Desktop persistence and lifecycle
| for (const [tabId, layout] of Object.entries(session?.terminalLayoutsByTabId ?? {})) { | ||
| for (const [leafId, ref] of Object.entries(layout.scrollbackRefsByLeafId ?? {})) { | ||
| const descriptor = expected.get(`${tabId}\0${leafId}`) | ||
| if (!descriptor || descriptor.ref !== ref) { | ||
| throw new Error('orcad_migration_dormant_scrollback_reference_invalid') | ||
| } | ||
| referenceCount += 1 |
There was a problem hiding this comment.
Scrollback can target missing pane A scrollback descriptor passes this check when its reference appears in
scrollbackRefsByLeafId, even if that leaf is absent from the layout tree. The snapshot is accepted for a pane the restored layout cannot display, leaving its transferred scrollback inaccessible.
Knowledge Base Used: Persist parked remote terminal scrollback across restarts
| const result: PersistedMobileClientTabSelections = {} | ||
| let count = 0 | ||
| for (const [deviceId, byWorktree] of Object.entries(record)) { | ||
| if (!deviceId || !isRecord(byWorktree)) { | ||
| throw new Error('orcad_migration_dormant_mobile_selections_invalid') | ||
| } | ||
| const entries: PersistedMobileClientTabSelections[string] = {} |
There was a problem hiding this comment.
Reserved IDs lose selections A mobile selection with device ID
__proto__ passes the nonempty-ID check, but assigning it to this ordinary object changes the object's prototype instead of adding an own entry. The selection then disappears from the normalized migration payload without an error; reserved group IDs can be lost in the same way.
* Revert "feat(orcad): source-side dormant export of a relay-hosted SSH target (#16741 T6-8) (#24519)" This reverts commit 783101b. * Revert "feat(ssh): update, roll back, recover and stop a managed orcad server (#16741 T6-5 follow-up) (#24463)" This reverts commit 38c2d1d. * Revert "feat(ssh): deploy and pair an empty managed orcad server over SSH (#16741 T6-5) (#24453)" This reverts commit 8b76683. * Revert "fix(ssh): orcad GC honors the activation journal; readiness requires proven daemon coverage (#16741 T6 follow-up) (#24451)" This reverts commit d3f8c50. * Revert "feat(ssh): remote orcad stop by request file and journaled decommission (#16741 T6-4) (#24449)" This reverts commit 43d9b43. * Revert "feat(orcad): supervisable server: stop requests, managed stop receipts and a lifetime that keeps its lock on failed teardown (#16741 T6-3) (#24433)" This reverts commit b093d3a. * Revert "feat(ssh): crash-safe orcad activation, rollback and recovery (#16741 T6-2) (#24423)" This reverts commit 1a9ac0e. * Revert "feat(runtime): SSH access links for paired servers in a downgrade-safe sidecar (#16741 T5-1+T5-2) (#24420)" This reverts commit 99db2bf. * Revert "feat(relay): capability-gated owner reset with a durable preparation journal (#16741 T3 R1) (#24418)" This reverts commit 34a582b. * Revert "feat(ssh): track connection-manager drains, test probes and provider continuations (#16741 T2 P3+P8a) (#24407)" This reverts commit d53063d. * Revert "feat(daemon): idle retirement, session census and recovery-only provider (#16741 T2 P4b) (#24409)" This reverts commit ff212db. * Revert "feat(ssh): add pty.resumeClient and split SSH PTY process listing (#16741 T2 P5+P6) (#24414)" This reverts commit 92cb717. * Revert "feat(relay): await owned watcher and agent children on shutdown (#16741 T2 P1) (#24400)" This reverts commit 6b36e4f. * Revert "feat(session): retry failed renderer session writes and verify local folder PTYs (#16741 T2 P9) (#24406)" This reverts commit d23ecef. * Revert "feat(ssh): remote orcad primitives on the pinned Node runtime (#16741 T6-1) (#24419)" This reverts commit dd87ae5. * Revert "fix(runtime): fence runtime-environment subscriptions and status probes by identity (#16741 T5-3) (#24421)" This reverts commit ece9e4d. * Revert "feat(orcad): migration manifest and dormant-state contracts (#16741 T6-7) (#24422)" This reverts commit 3fbdaba. * Revert "feat(ssh): wire SshConnection through the work and transport close ledgers (#16741 T2 P2) (#24401)" This reverts commit 4e8edc8. * Revert "feat(profiles): carry markdown frontmatter visibility in project transfers (#16741 T2 P7) (#24405)" This reverts commit 60c9326. * Revert "fix(runtime): project the PTY incarnation onto mobile session tabs (#24413)" This reverts commit 99e0303. * Revert "feat(daemon): tag daemon stream data with the PTY incarnation id (#16741 T2 P4a) (#24402)" This reverts commit 817af76. * Revert "feat(ssh): port the SSH connection work ledger and transport close ledger (#16741 T2) (#24210)" This reverts commit c991893. * Revert "feat(relay): fence and drain file and git response streams on shutdown (#24185)" This reverts commit dc08ffe. * Revert "refactor(runtime-rpc): extract the Node WebSocket lifecycle; opt-in pinned port (#24186)" This reverts commit a789233. * Revert "feat(relay): route relay handlers through work admission; producer publication drain (#24181)" This reverts commit 0b812bd. * Revert "feat(relay): land the #16741 T1 seam (work drain, publication drain, release gate) (#24156)" This reverts commit 3aa2d3a. --------- Co-authored-by: m4air <[email protected]>

This is T6 slice 7 of the #16741 port: the shared contracts for migrating a desktop catalog onto a managed Orca server. It is inert: nothing calls these parsers yet. The managed-deployment slices that produce and consume manifests come later.
ELI5
Before Orca can move a workspace catalog from your desktop onto a managed server, both sides need to agree exactly what a valid migration file looks like and refuse anything else. This PR adds only those agreed rules and their checks. Nothing uses them yet.
What Changed
Before: main had no definition of a migration manifest.
After: user behavior is unchanged. New shared modules (
src/shared/orcad-migration-*) define:absent/staged/committed) and staged-catalog normalization.Safety rules:
version: 1, and any other version, higher or not a number, is refused withorcad_migration_manifest_version_unsupportedinstead of being parsed by guesswork.folder:keys alongsideworktree:keys and bare worktree ids. Each must belong to the manifest's own catalog, so a reference to a workspace that isn't migrating is refused.parseWorkspaceSession, so the contract follows main's current session shape (including the SQLite-era profile state from refactor(persistence): retire ordinary JSON profile writes #23202) instead of a frozen copy from feat(orcad): consolidate Bun runtime and SSH/Remote migration #16741.Why
These are pure data contracts with no callers, so they can land ahead of the deployment work. That makes later T6 slices small and leaves the validation reviewed on its own.
Changed from #16741:
Left out:
Linked Issue
Part of the Node runtime plan, Phase 3, T6 slice 7. Ported from #16741 (a68b6f3).
Visual Proof
N/A. These contracts are not called anywhere yet.
Testing
Ported: manifest (deterministic serialization, bounded receipts, Node-18-safe normalization, dormant-state scope, automations), dormant session validation, scrollback wire validation and staged-catalog normalization.
New
orcad-migration-manifest-contract.test.ts:'1', missing andnullare refused;folder:andworktree:keys validate together;folder:key is refused.Result: 54 passed across the migration tests plus
workspace-session-schemaandworkspace-scope.The changed-code quality gate passes, and these files contain no Bun, PTY ownership transfer, outgoing, cutover or live-migration imports.
I manually tested these changes locally
Automated tests added/updated, or explained why not below
AI Disclosure
Review
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)