Navigation
ELOWEN · Documentation

Last updated: October 27, 2026

Browse documentation · onedrive implementation
Developer reference

onedrive implementation

API route purposes

src/api.ts registers eight authenticated, account-owned Project mirror operations. Each registerApiRoute declaration supplies its English purpose in summary for the host's automatic API catalog; there is no separate endpoint catalog. For example, sync-now synchronizes only the selected owned mirror, with optional deletion confirmation scoped to that run. Summaries do not alter Project admission, mirror ownership, existing input coercions or agent access. Missing Microsoft or managed-file capabilities still fail at the existing handler boundaries.

src/apiContract.ts is the pure descriptor module beside the compiled entry. Its named apiRoutes object owns all eight request schemas, credential declarations and JSON response kinds; runtime registration spreads those descriptors. Canonical schemas retain the existing Number coercion, literal-true flags, local conflict winner default, subpath normalization and permissive unknown-field handling. Nonobject JSON still becomes an empty object. The JSON Schema input projection is deliberately broad where any JSON value was accepted; it must not invent required fields or enum constraints merely to improve discovery.

Handlers use the exact registered schemas lazily. Malformed/empty JSON follows the existing empty-object default by parsing {} with the same canonical schema; schema identity/programming errors propagate instead of becoming an authorized default. Resource-dependent mirror ID selection still prefers body ID over query ID, then checks the same account, Project and lifecycle. No eager parser moves those owner or filesystem gates. Agent and personal-token policy remains allowed.

tests/pluginApiMailPurposes.test.ts captures the real registrations and checks the eight-route count and nonempty purposes of at most 200 characters without opening a mirror, acquiring credentials or running synchronization.

Project removal

Version 0.3.32 ships this contract in committed dist/, rebuilt from src/ with scripts/build-ts.mjs. Marketplace installation copies these outputs without compiling; npm run check:dist must pass after staging regenerated artifacts. tests/projectWriteAdmission.test.ts exercises the committed runtime rather than the TypeScript source; tests/projectRemovalParticipants.test.ts additionally verifies the shipped Sites cascade and GitHub cleanup.

This participant requires coordinated core 0.30.47 or later, including durable removal acknowledgement and transaction-scoped active-Project admission. Update core before installing this plugin version.

Mirror creation/reconnection calls tx.host.projects.requireActive(id) in the same transaction as the link upsert, after remote-folder lookup has finished. Core's Project row lock serializes this durable binding with deletion across processes. Existing cleanup markers and cycle claims continue to fence baseline writes; remote work is not performed inside the admission transaction.

The plugin declares provides.projectRemoval: "services". Its registerProjectRemoved callback awaits SyncEngine.removeProject: the store first marks every matching link for removal, disables it and invalidates its claim, then drains baselines and removes links. A failed drain leaves every target fenced for retry. The engine then waits for already-admitted in-process account cycles and root-lock work before acknowledging completion. This drain currently includes unrelated active cycles because those existing owners are account/root scoped. Cleanup does not delete Microsoft credentials or remote OneDrive folders/files. API and directory/worktree resolution reject Projects with lifecycle deleting, including a second connect check after remote-folder lookup.

Migration entry

The manifest entry exports migrate(db: PluginDb<never>): Promise<void> beside register. The daemon loader always awaits it before registration for this reads: ['db'] plugin; the DB CLI calls the same export without registering tools, routes, timers or services. The export runs only the existing transactional plugin SQL through db.migrate. A failed step rolls back its SQL and ledger entry and prevents registration. Repeated calls skip applied versions. Runtime store construction never invokes migrations. Tests that bypass the loader explicitly await this export before using their fixture.

Problem audiences

Account, mirror and file-operation logs preserve the typed Microsoft/core cause, user filesystem errno and native network causes before selecting publisher reporting. Missing remote folders and unavailable managed environments carry the core instance-condition type; direct chunk HTTP refusals retain that type for access, conflict, quota and availability. Response-contract defects and persistence failures remain reportable. Retry counters and diagnostic text are unchanged. Microsoft Teams supplies typed delegated Graph causes; both plugins require the matching core's public elowen-plugin-shared/errors seam.

Retry reporting

SyncEngine uses ConsecutiveFailures from elowen-plugin-shared/consecutiveFailures. The current manifest declares core 0.30.47 and shared API 16; the paired core archive must actually export the helper. Account startup, mirror cycles and file operations count independently by account, link, and link plus relative path. Managed read/upload and local file failures share the file counter across cycles. Only failure three exports the existing code; subsequent failures stay local until success resets that counter. A successfully planned file resets its counter only when that cycle recorded no failure for that path. Bulk-deletion refusal remains local and does not consume a failure counter.

A managed mirror whose environment is unprovisioned, starting or stopped is not a failure: managedFor throws EnvironmentNotRunningError, and the cycle defers that link for the same 60-second backoff as environment_pending, keeps the start-it explanation on the link and logs at info without consuming the mirror counter. A failed, deleting or deleted environment still counts towards onedrive.mirror_failed.

Bounded baseline persistence

Database deletion uses core-owned drainDbRows from elowen-plugin-shared/dbBatches. The same coordinated core archive and shared API 16 requirement applies; the manifest floor alone does not prove this export. It selects identities and payload sizes, commits at most 64 rows / 256 KiB per batch, processes one oversized row alone and yields between commits. Other bounded loops use the same module's yieldDbBatch for their event-loop yield.

The PostgreSQL schema plugin_onedrive contains links and items. The four async migrations create the link, baseline and durable cleanup marker. The host awaits the entry export migrate(db) before registration; OneDriveStore.open(await ctx.db()) only constructs the runtime store. PostgreSQL steps 1 through 4 create the current schema; installed ledgers already record them, so they are never renumbered. Every SQL object is explicitly schema-qualified, every value uses positional parameters, and the host supplies the async PluginDb. Link IDs and baseline row_id values are bigint identities generated by PostgreSQL. The item primary key remains (link_id, rel_path); relative paths use C collation for bytewise keyset paging. Stored instants use timestamptz and project back to epoch milliseconds. Local file mtimes remain double precision milliseconds so fractional filesystem times survive.

Reset and disconnect invalidate the current claim before draining baseline rows in transactions of at most 64 rows and 256 KiB of stored text plus overhead, with setImmediate between batches. Claims and live link projections treat cleanup as disabled, so a sync cannot read a partly erased baseline. Reconnecting a marked link fails until cleanup completes. Boot reconciliation starts reset/removal marker drains in the background, logs rejected drains and releases predecessor claims without waiting for the full drain. Markers keep claims fenced until completion, so long cleanup does not consume the host's boot-reconcile budget. API and account/Project cleanup callers await the complete operation; remote files remain untouched.

Every OneDriveStore method returns a promise. items(linkId) builds its Map in indexed, 64-row relative-path keyset pages. The shared deletion helper receives the raw schema, items table and explicit row_id identity, with octet_length measuring UTF-8 payload bytes. SyncEngine awaits both inventory reads and rechecks its existing CycleFence after the final read before writing status. The baseline remains per link and uses the existing primary key; no second database or core API is introduced.

A reconnect uses one conflict-aware INSERT with RETURNING. Its conflict predicate checks the cleanup marker while PostgreSQL owns the existing row lock, so a concurrent reset cannot reconnect a partial baseline. A changed drive, folder or local subpath marks the link for reset and invalidates the claim in that same write, then drains the old baseline before returning the new link.

CycleFence.commit(write) renews/checks the claim, then calls withCurrentLink to lock the link row and revalidate its owner, expiry, enabled state, cleanup marker and destination before executing the supplied async SQL writes on that same transaction. SyncEngine uses it for baseline, conflict and status writes. The SQL-only mutation methods accept either the root PluginDb or a PluginDbTx; only the latter exposes the transaction-bound host facade. CycleFence always passes its locked transaction handle. The store owns CycleStoppedError, shared by the fence and SyncEngine so claim rejection has one error identity without a store-to-fence dependency. Pause, reset, remove and reconnect serialize with that row lock; a superseded cycle rejects without publishing stale baseline data. Remote and filesystem operations stay outside database transactions. This cut adds no schema or baseline migration, no automatic reset and no new stored version: reset remains the explicit reconnect/disconnect transition above, and existing link ids, relative paths, stored hashes/mtimes and baseline rows stay. Host project reads and access checks are awaited at their existing resolution boundaries. MicrosoftIdentityControl.identityFor(accountUserId) is also asynchronous under shared API 13. The overview route awaits its identity object before serializing the response; panel visibility awaits the same account lookup before deciding whether to expose the project panel. Missing control means an unlinked identity and a hidden panel. Lookup failures propagate to the host without becoming a successful unlinked result. Neither consumer makes a Graph request.

Sync implementation boundaries

Maintainer section: the content below describes the code that owns each rule. It is not needed to use the plugin.

src/cycle.ts owns the shared asynchronous CycleFence.check() and deletion-valve decision used by both sync planners. Call the fence before the next operation, after awaited work before a baseline or status write, and before finishing the cycle. It checks the current stored link and renews the existing worker claim by elapsed time; it needs one link read per check and a renewal only when due, with no Graph requests. An obsolete link or lost claim stops the cycle without publishing a replacement status. With no enabled mirror, no cycle runs. Each transport retains its own planner.

One withHost(link, work) dependency is injected into the API and SyncEngine. It normalizes the stored subpath, rejects a workspace-scoped host link, and calls ctx.host.projectFiles().withProject({project:{kind:'host',projectId},accountUserId:link.userId,subpath}, scope => work(new HostMirror(scope, ctx.host.git()))). API callers build the link from the authenticated request's account; a background cycle uses the stored link account. The complete folder request, connect, sync cycle or conflict resolution is awaited inside that callback; only its result escapes and the scoped channel is not reusable afterwards. Core rechecks live Project/account/plugin membership before every operation, so authoritative background work needs no turn or linked conversation. Host work requires the project-files read, now actually exercised, and both inventories require the host git read. HostMirror.lockKey is the canonical whole-Project scope.projectRoot, never the narrowed root. A managed target keeps its explicit account, workspace, expected generation and startIfNeeded:false binding; a stopped or missing environment is an error, a computer Project is refused, and neither falls back to host access.

Host and managed inventories share scanManaged, which calls the mirror's listedFiles(); both planners then call ignoredAmong() for absent candidates. Those methods delegate to ctx.host.git().projectListedFiles and projectIgnoredAmong. Core owns repository classification, NUL/quoted-path parsing, bounded output, deadlines, cancellation and the authorized-root check; names are relative to the selected mirror root. isRepo:false alone selects non-repository traversal. An unavailable, corrupt, cancelled or unreadable Git answer fails the cycle instead of becoming an empty inventory or ignore set, and an incomplete scan cannot authorize deletion.

Host inventory reads metadata-only pages through HostMirror.listFolders/walk and prunes hard, operator and Git-excluded branches before spending its file budget; managed inventory keeps the bounded guest walk and mandatory directory skips. The ignore floor excludes .git, node_modules, .elowen-trash, .ssh, .aws, credential stores, .onedrive-part-*, .elowen-upload-* and .elowen-write-*; interrupted files stay ignored and untouched.

File hashes, upload reads and every CAS mutation are pinned to a content version observed by that read (stat, open or hash) and passed as expectedVersion; a rename uses the source version and a null write means create-only. These versions are transient, not baseline hashes, mtimes or new stored columns; the existing baseline, link identifiers and conflict/trash layout stay unchanged, and no full upload is triggered.

Drive owns Microsoft Graph HTTP and remote bytes: downloadBytes, sha256 and the preauthenticated chunk PUT. It never opens a local path. Every local read, hash, write, rename and trash move goes through the scoped HostMirror or ManagedMirror and shared guestFiles; the former raw filesystem, containment and Git-command helpers are gone. No transport substitutes host access for an unavailable managed or computer target.

src/paths.ts owns remote folder paths and conflictName(rel, when, taken). A synchronous occupancy callback returns a name immediately; a managed asynchronous callback returns a promise. Both use the same extension-preserving names and bounded collision search. src/trash.ts owns local and managed trash moves; local conflict-resolution routes reuse trashFile, while sync supplies its current-cycle check before the final rename. Internal helper imports move to their owning modules; the installed plugin entrypoint, controls and HTTP routes keep their contracts.

Managed command and browser contracts

OneDrive executes no project commands: both Git inventories use the typed ctx.host.git() reads above, and every managed file operation goes through its explicit guest binding. Editor's remaining Office utility, converter and cleanup workloads still use the shared one-shot runner with leaseKind: 'project-command', a 30-second timeout and an 8 MiB combined bound; that runner is not OneDrive's Git transport. OneDrive's managed workspace keeps its explicit account, Project, generation and startIfNeeded:false binding; a stopped or missing environment is unavailable, never a host fallback.

OneDrive's browser runtime declarations describe the host components used by OneDriveProjectPanel. Every declared name is checked against the published UI kit, so a component the host does not publish fails the build instead of reaching React as undefined. The panel renders mirror values as SettingsRow inside SettingsGroup, each workspace as a SettingsItem row inside SettingsList, each conflicted file as a CardGrid list card inside WorkspaceDetailRail (file name on the first line, its folder beneath, the two resolve buttons on the right; a conflict has no detail, so the card opens nothing) and the disconnect confirmation as ConfirmDialog. With no active worktree no workspace list is mounted. Workspace rows carry no open action: every state answers through its own buttons. This declaration is type-only, adds no runtime work and does not extend the host component API or change host styling.

OneDrive requires UI API 62 and uses the host's interpolate and formatBytes signatures; interpolate(template, values) handles named literal substitutions and formatBytes(bytes, viewerLocale) formats the mirror's byte count using the displayed language. Missing runtime support prevents loading rather than selecting a local fallback.

Managed file writes

ManagedMirror uses elowen-plugin-shared/guestFiles for all guest file I/O. For example, writeGuestFile(operation => this.call(operation), path, bytes, { expectedVersion }) selects one write up to 512 KiB and chunked upload above it. The callback forwards operations to the existing projectFiles binding, preserving its acting account, Project, workspace, expected generation and startIfNeeded: false.

Core owns chunk boundaries, acknowledgements, the resolved destination, missing parent directories and atomic version-checked commit. It aborts a failed upload and reports cleanup failure alongside the original error; begin and commit refusals retain their codes. The same client owns every folder-list page, bounded walk, stat, version-pinned range reads, streamed hashing, mkdir and rename. OneDrive retains mirror conflicts, size limits and sync decisions, and constructs no guest operation literals. Requires the coordinated core release named in the manifest; shared API 14 is unchanged. Ship together with Editor and LSP in the same registry snapshot as the core. A missing or stopped environment is still unavailable, never started by a write. This adds no extra file copy or whole-file buffer beyond the downloaded bytes already held by the mirror.

Conflict resolution and bounded scans

A Project can be mirrored directly, and each active managed Sandbox worktree can be connected separately. OneDrive obtains worktree IDs and labels through sandbox.managedWorktrees with the acting account and startIfNeeded: false. Host Projects have no Sandbox worktree list. Without Sandbox support a managed file operation is unavailable; it never falls back to a host directory. Stored paused links from retired local workspaces remain until an explicit retention decision.

POST conflicts/resolve takes { id, rel, keep: 'local' | 'remote' } and rechecks mirror ownership and Project access. Host resolution runs inside the same withHost callback and underRootLock(fs.lockKey) as the cycle; the lock key is the canonical whole-Project root, never the narrowed subpath. Managed resolution keeps its existing workspace key. Under CycleFence, the engine reads the current conflict, verifies the Microsoft drive ID and remote ETag, then selects the host or guest transport. Keeping local uploads conditionally on that ETag. Keeping remote promotes the already downloaded conflict copy and preserves the superseded local file in sync trash. Managed reads and renames use guest version checks; rename requires an absent destination. Missing copies, stale versions, a running claim, a paused or removed link return 409 without recording a successful baseline. A callback entry refusal or a typed Git/version failure remains an error, never an empty successful resolution or a host fallback. Every refusal body is { code } with a stable code and no English sentence: ConflictRefusal (src/sync.ts) carries mirror_unavailable, mirror_busy, drive_mismatch, conflict_gone or copies_changed; a CycleStoppedError from the fence answers mirror_unavailable; the route adds not_connected and conflict_gone (404, the conflict is not listed). Any other failure is logged with its cause (onedrive.mirror_failed) and answers resolve_failed. The panel maps each code to a conflict* string of the manifest and i18n/{cs,sk}.json and shows it in the failed file's card; ConflictRefusalCode in web-src/runtime.ts mirrors the server's set. A transfer already sent may finish; the next operation boundary stops further work. A later remote ETag reoffers the conflict through the normal cycle while preserving earlier copies. Without an enabled mirror no resolution runs. OneDriveProjectPanel is the real consumer; no general filesystem adapter is introduced.

scanManaged passes exact mandatory directory names to ManagedMirror.walk, which forwards them to Sandbox's bounded guest walk. The same name list derives the hard-floor patterns for .git, node_modules, .elowen-trash, .ssh and .aws. These directories are pruned at every depth before consuming the walk budget. Git membership and the full ignore predicate still filter returned files. Arbitrary extraIgnore globs are not translated into directory skips. The 20,000-entry budget, one sentinel entry and the guest depth/deadline bounds remain; an incomplete scan cannot authorize deletion. ScanResult exposes files, skippedPaths, fromGit, complete and isIgnored. skippedPaths is the sole skipped-path projection and is consulted by both sync planners before deciding absence; it is not a user-facing skip report.

The OneDrive settings reader in src/index.ts normalizes extraIgnore once into string tokens, preserving commas inside brace globs and already-tokenized array entries. SyncEngine, registerApi and buildIgnore consume that normalized array through SyncSettings. rootFolder is trimmed and stripped of surrounding slashes before the Elowen default is applied; remoteRootFor consumes it without another fallback. registerApi uses one directory resolver for folders and connect, and reuses the fetched workspace label. OneDrive imports errorText from elowen-plugin-shared/errors and keeps shared API 14; its manifest names the coordinated core release that provides the typed host Git and scoped project-files callback. The helper preserves Error.message and stringifies other thrown values without introducing retries or success defaults. registerUserRemoved is required and always wires account cleanup, leaving remote files untouched. Only the injected lease timing override is internal to tests; production lease durations are unchanged. DriveItem exposes only id, etag and size while validating raw Graph id and name. MirrorLink no longer projects createdAt; its stored SQL column remains pending a separate migration decision.

Cycle stop and conflict fixtures

Pausing, disconnecting or choosing a different mirror folder stops a running cycle at its next operation boundary. A transfer already sent may finish, but the stopped cycle starts no further change, does not record that transfer in the old baseline and does not replace the paused status. Both local and managed mirrors re-check the enabled link, its selected subfolder and the original OneDrive drive, item and path before continuing, and stop when their worker claim can no longer be renewed.

Managed conflict copies are written only at an absent destination, so a file created during the download is preserved and the cycle reports the write failure instead of overwriting it. A name already recorded for a conflict is not renamed, and both transports keep the original extension with a numeric suffix when the generated name is occupied.

The manifest requires host UI API 62 and the Sandbox managed Project file and workspace controls.