@statewalker/vcs-workspace
A small orchestrator that combines plain file sync with Git history. It runs four workflows over a local working tree: publish (mirror files to file remotes, commit, upload large objects, push), update (copy files from file remotes), restore (check out the commit recorded in a checkpoint) and checkpoint (record the current state). Each workflow is an async generator of step events and ends with a serializable WorkspaceCheckpoint.
Why this layer exists
An application often keeps the same folder both mirrored as files (to a backup, a device, a server) and versioned as Git history. The two engines, @statewalker/webrun-files-sync for files and the @statewalker/vcs-* packages for history, do not know about each other. Something has to run them in order and record which commit matches which synced file state. This package does that and nothing else: it holds a declarative policy (SyncVersioningPolicy) and the correspondence record (WorkspaceCheckpoint), not engine logic.
It calls the file engine directly. It reaches history only through two small structural interfaces, Repository and GitRemote, that the caller implements. The root entry never imports vcs-core, vcs-working-tree or vcs-transport; a test (tests/ban.test.ts) enforces this. Network sync, which needs the Git engine, is a separate entry, @statewalker/vcs-workspace/net (see Network sync), so file-only users never load the engine. So the file engine and the Git engine stay independent, and a sync-only workspace (no repository) works the same way.
How to use it
pnpm add @statewalker/vcs-workspace
No peer dependencies. Two entry points: @statewalker/vcs-workspace for the workflows below, and @statewalker/vcs-workspace/net for network sync. The root entry:
| Export |
What it does |
publish(ws, remotes, policy, opts) |
Local to remote: sync files, commit, upload large objects, push, emit a checkpoint |
update(ws, remotes, policy, opts) |
Remote to local: copy each file remote into the working tree, emit a checkpoint |
restore(ws, checkpoint) |
repository.checkout(checkpoint.commit), then echo the checkpoint |
checkpoint(ws, remotes, opts) |
Snapshot the current manifests and HEAD without running a workflow |
buildSyncOptions(hashContent, policy, opts) |
The SyncOptions the workflows pass to the file engine |
manifestOf(files, hashContent) |
Content identity of a file tree (hash of the sorted path to content-id map) |
Types: Workspace, WorkspaceRemotes, Repository, GitRemote, SyncVersioningPolicy, WorkflowOptions, WorkspaceCheckpoint, WorkspaceEvent, and re-exported FilesApi, ContentStore, PathFilter, VerificationMode, ByteStream.
The interfaces you implement:
interface Repository {
manifest(): Promise<string>;
head(): Promise<string | undefined>;
hasChanges(): Promise<boolean>;
commit(opts: { message?: string }): Promise<{ commit: string; changed: boolean }>;
checkout(commit: string): Promise<void>;
}
interface GitRemote {
push(refspecs: string[]): Promise<{ commit: string }>;
objects?: ContentStore; // remote large-object store, if this remote takes large objects
}
The package ships no adapter for these. Write one over @statewalker/vcs-commands (commit(), checkout(), push()) or your own history layer.
Examples
Publish files and history
import { createHash } from "node:crypto";
import { MemFilesApi } from "@statewalker/webrun-files-mem";
import {
type ByteStream,
type Workspace,
type WorkspaceCheckpoint,
type WorkspaceRemotes,
publish,
} from "@statewalker/vcs-workspace";
async function sha256(input: ByteStream): Promise<string> {
const h = createHash("sha256");
for await (const chunk of input) h.update(chunk);
return h.digest("hex");
}
const ws: Workspace = {
workingTree: new MemFilesApi({ initialFiles: { "/a.txt": "one" } }),
repository, // your Repository adapter
};
const remotes: WorkspaceRemotes = {
fileRemotes: new Map([["backup", new MemFilesApi()]]),
historyRemotes: new Map([["origin", gitRemote]]), // your GitRemote adapter
};
let saved: WorkspaceCheckpoint | undefined;
for await (const event of publish(
ws,
remotes,
{ commitAfterSync: true, commitOnlyWhenChanged: true, pushAfterCommit: true },
{ hashContent: sha256, message: "sync" },
)) {
if (event.type === "failed") console.error(event.step, event.reason);
if (event.type === "checkpoint") saved = event.checkpoint; // persist it yourself
}
// Events in order: scan, transfer..., commit, push, checkpoint
Resume after a failed push
for await (const event of publish(ws, remotes, policy, { hashContent: sha256, resume: saved })) {
// Remotes already recorded in `saved` emit { type: "skipped", reason: "already synced" | "already pushed" }.
// A commit recorded in `saved` is reused, not repeated.
}
Pull files, snapshot, restore
import { checkpoint, restore, update } from "@statewalker/vcs-workspace";
for await (const event of update(ws, remotes, {}, { hashContent: sha256 })) {
if (event.type === "transfer") console.log("pulled", event.path);
}
const now = await checkpoint(ws, remotes, { hashContent: sha256 });
for await (const event of restore(ws, now)) {
// { type: "commit", changed: false } after repository.checkout(), then { type: "checkpoint" }
}
Network sync
import { createMemoryHistoryWithOperations } from "@statewalker/vcs-core";
import { httpRemote, openGitWorkspace, syncWorkspace } from "@statewalker/vcs-workspace/net";
const history = createMemoryHistoryWithOperations(); // or a repository on files, in a database
await history.initialize();
const ws = await openGitWorkspace({
folder, // any FilesApi: the folder kept in step
history,
identity: { name: "Ann", email: "ann@example.com" },
});
const result = await syncWorkspace(ws, httpRemote({ url: "https://example.com/notes.git" }));
// { head, committed, integration: "up-to-date" | "fast-forward" | "merge" | "conflicted",
// pushed, conflicts, attempts, skipped, rejoined, merge? }
if (result.integration === "conflicted") console.warn("resolve, then concludeMerge:", result.conflicts);
One call does what git add -A && git commit && git pull && git push does for a folder: it commits the folder's changes on main, fetches the remote's main into refs/remotes/origin/main, brings it in, and pushes the result. It never forces. If someone else pushed between our fetch and our push, the push is refused as git refuses it, and the round runs again: fetch, merge, push. After maxAttempts rounds (default 5) it gives up with a SyncError.
The server side is the transport's own server. createSyncServer serves one repository over smart HTTP and over duplex streams, and tells subscribers which refs each push moved. receive-pack's post-receive hook does this once the push's report is written, so a workspace can pull as soon as another one pushes:
import { createSyncServer, syncWorkspace } from "@statewalker/vcs-workspace/net";
// a bare repository (vcs-transport facade); `requestPolicy: "REACHABLE_COMMIT"` refuses
// fetches of objects no branch or tag reaches (git's v2 default serves any object)
const server = createSyncServer({ repository, refStore });
Bun.serve({ fetch: server.fetch });
server.subscribe((updates) => {
// [{ ref: "refs/heads/main", oldOid, newOid }]: tell the other clients (WebSocket, push message...)
broadcast(updates);
});
// on another client, when the message arrives:
await syncWorkspace(otherWs, httpRemote({ url }));
The same sync runs over a duplex stream (a MessagePort, a WebSocket, a WebRTC channel) and over an httpeers mesh:
import { messagePortDuplex, serveOverPort } from "@statewalker/vcs-transport";
import { meshGitHandler, meshRemoteFetch, servePeerConnection } from "@statewalker/vcs-transport-httpeers";
import { duplexRemote, httpRemote } from "@statewalker/vcs-workspace/net";
// duplex: one connection per fetch and per push
const overChannel = duplexRemote({
connect: (service) => {
const channel = new MessageChannel();
// serveOverPort closes both ports once the session is over
serveOverPort(channel.port2, (duplex) => server.serve(duplex, service));
return messagePortDuplex(channel.port1);
},
});
// mesh: the hub serves the repository behind httpeers access, with the sync server's hooks
const handler = meshGitHandler({ repository, refStore, access, receivePack: { hooks: server.hooks } });
const call = servePeerConnection(handler, { remotePeer }); // the peer connection
const overMesh = httpRemote({ url: "http://hub.mesh/notes.git", fetchImpl: meshRemoteFetch({ call, token }) });
How remote changes come in
-
Fast-forward when the local branch is behind: the folder is brought to the remote commit, writing only the files that differ.
-
Merge when both sides committed: a merge commit with both parents, against the best common ancestors. These are found as git's merge-base finds them: a newest-first walk that stops at the merge base, so it reads only the commits since then. When there are several (a criss-cross history), they are first merged into a virtual base, recursively, as git's recursive strategy does.
-
Paths only one side changed are taken from that side.
-
Text files both sides changed are merged line by line with mergeLines of @statewalker/vcs-utils. That merge works on bytes: it splits on LF and keeps every terminator, so CRLF files, a missing final newline and non-UTF-8 text come out unchanged. A file with a NUL byte in its first 8000 bytes is binary, as git decides it.
-
mergeLines aligns lines with a histogram diff, while git merge-file uses its own xdiff. They agree on almost every input. In a fuzz run against git merge-file (1500 random three-way merges), the merged output was identical whenever both were clean, but 3 inputs that git reports as conflicts merged cleanly here. In those, one side deleted a line the other side kept next to its own change.
-
Conflicts are kept and reported, never resolved silently. The merge result holds both sides:
- text files get git's markers, labelled with the branch and the commit:
<<<<<<< main (1a2b3c4) … ======= … >>>>>>> origin/main (5d6e7f8), in the file's own line ending;
- a binary file keeps ours, with theirs next to it as
<path>.theirs-<id> (-2, -3… when that name is taken);
- a change against a deletion keeps the change;
- a file against a directory moves the file aside as
<path>.ours-<id> or <path>.theirs-<id>, after the side it came from.
By default the merge then stops, as git stops; see When a merge conflicts.
When a merge conflicts
import { abortMerge, concludeMerge, readMergeState, syncWorkspace } from "@statewalker/vcs-workspace/net";
const result = await syncWorkspace(ws, remote);
if (result.integration === "conflicted") {
// the folder holds the merge result; result.conflicts (and result.merge.conflicts) name the files
// ...the user edits them, removing the markers...
await concludeMerge(ws); // the merge commit, both parents
await syncWorkspace(ws, remote); // pushes it
}
// or, to give up the merge: await abortMerge(ws);
A merge with conflicts does what git merge does (the default, onConflict: "stop"):
- The merge result is written into the folder: markers in text files, the other side beside binary files and beside files that met a directory, as listed above. Paths that merged cleanly get their merged content too.
- Nothing is committed or pushed. The branch stays where it was (local edits made before the sync are committed, as
git commit before git pull would).
- The merge stays in progress under
refs/workspace/merge/main, git's MERGE_HEAD: a ref only the workspace writes, never pushed. Its commit holds the merge result, the other parent and the conflicted paths. readMergeState(ws) returns it.
- The sync returns
integration: "conflicted", pushed: false, the paths in conflicts, and merge. It emits the integrate event and a conflicted event (started: true).
While the merge is in progress, syncWorkspace fetches, merges and pushes nothing. It returns the same conflicted result and a conflicted event (started: false), so a sync on a timer is safe. The exception is a sync that finished writing a merge result whose writing was cut short (below): the merge stopped in that sync, so its event says started: true. commitWorkspaceChanges makes no commit either, and its result has merge (and mergeStarted in that same case).
What was left out when the merge stopped stays left out until it ends. The record freezes the ignored paths, nested repositories and held files of that moment. It keeps only the topmost ones (an ignored directory is one entry), and paths are matched against it with one lookup per ancestor directory. If ignore changes or a nested repository's .git is removed during the merge, concludeMerge still carries those paths over from the merge result, and abortMerge never writes or removes them. The commit after the merge ends brings them back by the usual rules (below): a stale ignored copy gets the branch's version, and a local file that history never had is held.
Two calls end the merge:
concludeMerge(ws, { message?, force? }) makes the merge commit from the folder as it is then, with both parents. The next sync pushes it. The call is refused with an UnresolvedConflictsError (its paths name the files) while a conflicted text file still holds a marker line: a line starting with <<<<<<< or >>>>>>> and then a space or the line's end. git refuses while the index has unmerged entries; a folder has no index, so the markers are the equivalent. The ======= line is not checked, since Markdown underlines headings with it. Binary conflicts are not checked: the folder's version is taken, and a .theirs-<id> copy still beside it is committed like any other file, so remove it first if you keep ours. A change against a deletion is not checked either: the changed file is in the folder, and it is committed as it is, so delete it first to accept the deletion. A file against a directory is in the folder as the directory, plus the file moved aside, both committed as they are. A conflicted path that was left out of the folder when the merge stopped (ignored, say) never reached the folder, so its markers are looked for in the merge result. The conclude is refused the same way, and the error's leftOut names such paths. Abort the merge, stop leaving the path out, and sync again to resolve it in the folder. force: true skips the marker check, for files whose content really has such lines. hasConflictMarkers(bytes) is exported for your own checks.
abortMerge(ws, { force? }) does what git merge --abort (git reset --merge) does. Every path the merge changed gets the branch tip's version back, and files the merge added are removed. Edits made since the stop to conflicted files are discarded, as git discards them. Edits made since the stop to a file that merged cleanly would be discarded too, so the abort is refused instead, as git refuses with "not uptodate". It throws a MergeAbortRefusedError whose paths name the files, and nothing changes. Keep those edits elsewhere, or pass force: true to discard them. Paths the merge did not change are not touched, so edits made there during the merge stay, and nothing from before the merge is lost: the merge started from a committed folder. A directory holding files of its own is never removed; such a path is listed in kept.