veins (command-line program: vn) is a single-user-first version control system built around a chunked, content-addressed object store, an operation log with stable change IDs, and first-class conflicts that never insert markers into files. It keeps a two-way bridge to git so history can be imported from git, mirrored to git, and abandoned back to git at any time.
This is a draft. Items marked (review) should be confirmed. Open questions lists unresolved items.

1. Introduction

1.1. Purpose

veins exists because git has three properties that are painful for the primary use case (a solo developer working on large projects, some of which commit large generated files that are regenerated many times):

  1. Cloning repositories with many large, similar revisions is slow because pack files do not store object IDs for deltified objects. A client must reconstruct each object by walking its delta chain and then hash it ("Resolving deltas").

  2. Merges can leave the repository or working tree in a half-finished state, and conflicts are expressed by inserting <<<<<<< markers into the files themselves.

  3. Rolling back arbitrary operations (rebases, merges, resets) is unreliable and relies on the reflog.

1.2. Goals

  1. Fast clone and checkout for histories with many large, similar revisions. No step of clone or checkout may scale with delta-chain length.

  2. Seamless rollback. Every state-changing command is recorded as an operation, and any operation can be undone or restored.

  3. Seamless merges. A merge never fails and never blocks. Conflicts are values stored in history, not text inserted into files.

  4. Lossless git interoperability. History can be imported from git, exported to git, and round-tripped with identical git object IDs. A user can leave veins for git at any time without losing commit history.

  5. Remote sharing through a native fetch/push protocol with lazy chunk fetching.

  6. Controlled sharing. A server grants identified keys read-only or read-write access to a repository, and can optionally serve a repository to anonymous readers. Read-only access is a core v1 feature.

  7. Corruption resistance. Silent data loss is treated as a worse failure than a crash.

1.3. Non-goals

  • Replacing git as an ecosystem. Pull requests, issues, and CI remain git-hosted, and veins interoperates with them through the bridge.

  • Delta compression. veins trades some store size for random access and fast reads (see Performance requirements).

  • Semantic (AST-level) merging in v1. The merge engine is designed so a structural layer can be added later.

  • User accounts, passwords, groups, per-bookmark or per-path permissions, or other hosting features in the server. Access control in v1 is per repository and per key (see Authentication and authorization).

  • Multi-writer concurrency beyond what the operation log provides (see Operation log).

1.4. Naming

The product and file format are named veins. The command-line program is named vn (vn.exe on Windows). All command examples in this document use vn. The name veins is used for the repository directory (.veins/), configuration and attribute files (.vnexclude, .veinsattributes), the object-ID domain separator, and reserved header keys (veins-change-id, veins-sig). Conforming implementations of the format are not required to ship a program called vn.

1.5. Conventions

The key words MUST, MUST NOT, SHOULD, SHOULD NOT, and MAY are used as described in RFC 2119. Byte order is little-endian unless stated. Sections marked informative do not impose requirements.

Command-line options use Plan 9 style: a long option is a single dash followed by its name (for example -message, -rev, and -verbose). Short aliases MAY also be accepted. An unrecognized option MUST be reported as an error and MUST NOT be treated as an operand. -- terminates option parsing; every argument after it is an operand.

User-facing diagnostics use level prefixes: error: for failures, warning: for non-fatal problems, and info: for informational results. Prefixes are colored when standard output/stderr is a terminal and NO_COLOR is unset.

1.6. Terminology

Term Meaning

vn

The command-line program (vn.exe on Windows) used to operate on veins repositories.

Object

An immutable, content-addressed record in the store (chunk, blob, tree, commit, conflict, operation, or view).

Chunk

A content-defined slice of file data, stored as an independent object.

Blob

The object that represents a file’s content: either inline data or a manifest of chunks.

Manifest

An ordered list of chunk references (possibly a tree of lists) describing a large file.

Commit

A snapshot of a root tree, with parents and metadata.

Change ID

A stable 16-byte identifier carried across rewrites of the same logical change.

Conflict value

A signed sum of values stored in place of a single value, representing an unresolved merge.

Operation

A record of a state change to the repository, forming the operation log.

View

The set of heads, bookmarks, tags, and working-copy commits at a point in time.

Bookmark

A named, movable pointer to a commit. Maps to a git branch.

Working copy

The files on disk, tracked as a commit (see Working copy).

Mirror

The bare git repository .veins/git that veins keeps in sync with its own history.

Promised object

An object known to exist on a remote and fetched on demand.

Key

An Ed25519 key pair. The public key is a client’s identity on a server.

Role

The permission a key holds on a repository: read or write.

Anonymous session

A connection that has not authenticated. It can only read, and only if the repository allows anonymous read.

1.7. Design decisions

The following decisions were made by the project owner.

Topic Decision

Git relationship

Two-way. veins can export to git and import commits back from git (for example contributor pull requests).

Remotes

Full native fetch/push protocol with lazy chunk fetching.

Object hash

BLAKE3 (256-bit). Git SHA-1 IDs are computed only on export, and cached.

History identity

Operation log plus stable change IDs.

Renames

Recorded explicitly in veins commits. Heuristic detection is used for imported git history.

Conflict presentation

The working-copy file is clean (no markers), accompanied by .base, .ours, and .theirs sidecar files.

Authentication

Native Ed25519 keys, verified by vn serve itself and independent of the transport.

Authorization

Per-repository roles only: read and write.

Anonymous access

Optional anonymous read-only access for repositories marked public.

The following decisions were made by the spec author and are subject to review.

Topic Decision (review)

Working copy model

The working copy is automatically snapshotted as a commit before each command (jj-style). There is no staging area.

Branch terminology

"Bookmark" is used for named movable pointers.

Chunking parameters

Fixed in format v1 (FastCDC, 16 KiB / 64 KiB / 256 KiB) so that chunk IDs deduplicate across repositories.

Conflict resolution

Explicit (vn resolve). Editing a conflicted file does not auto-resolve it, because no markers exist to detect.

Operation-log sync

Local only. Remotes carry refs and objects, not operations.

Platform

Linux and macOS first. Windows is deferred.

Authentication handshake

Challenge-response with an Ed25519 signature over both nonces, the repository name, the protocol version, and a transport channel binding (see Authentication and authorization).

Transport security rule

Authentication is accepted only on secure transports (SSH, TLS, local). Insecure transports may carry only anonymous reads of public repositories.

Reference transports

SSH (stdio), TLS 1.3 (veins://), and local stdio (file://).

Access management

A text file .veins/access in the served repository, edited only locally on the server with vn access. There is no remote administration in v1.

Revocation

Removing a key from .veins/access. Takes effect on new connections, and open sessions are re-checked when the file changes.

Write role scope

write can update or delete any ref. Repo-wide protections are listed in open questions.

Client key storage

Per-user key directory with owner-only permissions and optional passphrase protection. Import of OpenSSH Ed25519 keys is allowed.

2. Architecture overview

+------------------------------ vn CLI ------------------------------+
|  status log diff new describe merge rebase resolve undo op ...     |
+-----------+------------+-------------+-------------+---------------+
| working   | merge      | operation   | git         | native        |
| copy      | engine +   | log + views | bridge      | protocol      |
|           | conflicts  |             | (import/    | (serve/fetch/ |
|           |            |             |  export)    |  push)        |
+-----------+------------+-------------+-------------+---------------+
|        object store: packs, indexes, git-map, promised set         |
+--------------------------------------------------------------------+

All persistent state is either an immutable object in the store or a small mutable pointer (operation heads, working-copy cache, git-map). Everything user-visible is derived from the current operation’s view.

3. Data model

3.1. Primitive encodings

All objects use a canonical binary encoding. A decoder MUST reject any encoding that is not canonical (see Canonical form).

Type Encoding

u8, u16, u32, u64

Unsigned integers, little-endian, fixed width.

varint

Unsigned LEB128, at most 10 bytes. MUST be minimal (no redundant trailing zero groups).

bytes

varint length followed by that many raw bytes.

id

32 raw bytes (a BLAKE3 digest).

list<T>

varint count followed by that many encoded T.

opt<T>

u8 0 (absent) or 1 (present, followed by T).

sig

bytes name, bytes email, i64 Unix seconds, i16 timezone offset in minutes.

time_ms

i64 milliseconds since the Unix epoch, i16 timezone offset in minutes.

Names, paths, emails, and messages are arbitrary bytes. veins MUST NOT assume UTF-8 for stored data.

3.2. Object IDs

object_id = BLAKE3( "veins/1" 0x00 || type_byte || body )
Type byte Object

0x01

chunk

0x02

blob

0x03

tree

0x04

commit

0x05

conflict

0x06

operation

0x07

view

The chunk body is the raw chunk data. The ID of two objects with the same type and body is identical, so equal content has equal IDs everywhere.

3.3. Chunking

File data larger than the inline threshold is split into chunks using FastCDC with normalized chunking. The parameters are fixed for format version 1:

Parameter Value

Minimum chunk size

16 KiB

Average chunk size

64 KiB

Maximum chunk size

256 KiB

Normalization level

2

Gear table

Specified in Appendix A of the format test vectors (to be published with this spec)

A conforming implementation MUST produce identical chunk boundaries for identical input. Chunk boundaries depend only on file content.

Because regenerated files tend to change locally, chunk boundaries resynchronize after an edit, and unchanged regions share chunk IDs across revisions. This is what replaces delta chains.

3.4. Blob objects and manifests

A blob body is:

u8   form            ; 0 = inline, 1 = manifest leaf, 2 = manifest interior
form 0: bytes data
form 1: list< { id chunk_id, varint length } >
form 2: list< { id child_blob_id, varint total_length } >

Canonical construction rules:

  1. A file of length at most 16 KiB MUST be stored as an inline blob (form 0). An empty file is an inline blob with empty data.

  2. A larger file MUST be split into chunks and stored as a manifest. The chunk list is grouped into leaf nodes (form 1) using the boundary rule below. If more than one node results, the nodes are grouped into interior nodes (form 2) using the same rule applied to the child IDs, repeating until a single node remains. That node’s ID is the file’s blob ID.

  3. Boundary rule. After entry i in a level, the node is cut if the low 8 bits of u32le(entry_id[0..4]) are zero, or the node has reached 1024 entries. A node MUST NOT be cut before it has 16 entries, except at the end of the level.

Because the boundary decision depends only on entry IDs, inserting or removing a chunk disturbs only a bounded number of nodes (a prolly-tree property). The blob ID is therefore stable for equal content and local edits produce local changes.

3.5. Tree objects

A tree body is a list of entries sorted by name in ascending bytewise order, with unique names:

entry = { bytes name, u8 kind, id target }
Kind Meaning (target)

0x01

Regular file (blob ID)

0x02

Executable file (blob ID)

0x03

Symbolic link (inline blob ID containing the link target)

0x04

Subtree (tree ID)

0x05

Git submodule (opaque: the 20-byte git SHA-1 right-padded with 12 zero bytes). Preserved and exported, not otherwise interpreted in v1.

0x06

Conflict (conflict object ID)

Entry name rules. A name MUST be non-empty, MUST NOT be . or .., MUST NOT contain / or NUL, and MUST NOT equal .veins (any case). Implementations MUST refuse to check out a tree containing a name equal, case-insensitively, to .git or .veins.

veins sorts directory entries as plain names. Git sorts directory entries as if they ended with /. The git exporter MUST re-sort entries using git’s rule.

Empty directories are not representable and are not tracked.

3.6. Conflict objects

A conflict object records an unresolved value as an alternating sum (see Conflict algebra):

value  = { u8 kind, [id target when kind != 0x00] }   ; kind 0x00 = absent
body   = { list<value> adds, list<value> removes }

Constraints:

  1. adds MUST contain exactly one more element than removes, and removes MUST be non-empty.

  2. The stored form MUST be simplified: no add may equal any remove, and the adds MUST NOT all be identical.

  3. A value of kind 0x04 (a tree) is permitted. This represents a file-versus-directory conflict.

A conflict object appears as a tree entry of kind 0x06. Conflicts are stored at the level of individual entries, not whole trees, so a commit’s root tree is always a single tree ID.

3.7. Commit objects

u8                  version = 1
list<id>            parents
id                  root_tree
bytes[16]           change_id            ; fixed 16 bytes, no length prefix
sig                 author
sig                 committer
bytes               message
u8                  renames_state        ; 0 = unknown, 1 = recorded
list<rename>        renames              ; empty if renames_state = 0
list<{bytes key, bytes value}> extra     ; ordered
rename = { varint parent_index, u8 kind, bytes from_path, bytes to_path }
         ; kind: 0 = rename, 1 = copy
         ; paths are '/'-separated byte strings
         ; sorted by (parent_index, to_path)
  • renames_state = 1 means the renames list is authoritative: any path not listed was not renamed relative to that parent. renames_state = 0 means rename information is unknown and the merge engine MUST fall back to heuristics. Commits created by veins use state 1. Commits imported from git use state 0.

  • extra carries headers from imported git commits (encoding, gpgsig, mergetag, and others) so they can be exported verbatim. Keys beginning with veins- are reserved.

  • The change ID is generated randomly when a change is first created and copied unchanged when the change is rewritten (amended, rebased, squashed).

  • A commit is conflicted if its tree, recursively, contains an entry of kind 0x06. This is derived and MUST NOT be stored in the object. Implementations MAY cache it in an index.

3.8. Operation and view objects

operation = {
  list<id>   parents,
  id         view,
  time_ms    start,
  time_ms    end,
  bytes      hostname,
  bytes      username,
  bytes      description,                 ; e.g. "rebase commit k4m2..."
  list<{bytes key, bytes value}> tags     ; e.g. command line, "snapshot"
}

view = {
  list<id>   heads,                       ; visible head commits, sorted
  list<{bytes name, target_set}> bookmarks,           ; sorted by name
  list<{bytes name, id}>         tags,                ; sorted by name
  list<{bytes remote, bytes name, id}> remote_refs,   ; sorted
  list<{bytes workspace, id}>    working_copies       ; sorted
}

target_set = { list<opt<id>> adds, list<opt<id>> removes }
             ; resolved form: adds = [x], removes = []

A bookmark with more than one add is a conflicted bookmark (for example after concurrent updates). Resolving it is a normal operation.

3.9. Canonical form and limits

A conforming implementation MUST reject an object that:

Implementations MUST enforce at least the following limits (a stricter limit MAY be chosen):

Item Limit

Chunk size

256 KiB

Manifest node entries

1024

Tree entries

1,000,000

Name length

4096 bytes

Path length (on checkout)

65,536 bytes

Conflict terms

64

Commit message

16 MiB

Any single object body (other than chunk)

64 MiB

4. Storage

4.1. Repository layout

.veins/
  format               "veins-store 1"
  config               local configuration (never tracked)
  access               server only: authorized keys and the anonymous-read setting
  lock                 advisory lock for compaction and gc
  store/
    packs/             pack-<hex>.vpack and pack-<hex>.vidx
    tmp/               in-progress writes
  op_heads/            one empty file per current operation head (named by op ID)
  git/                 bare git repository (the mirror)
  git-map/             mapping tables between veins IDs and git IDs
  working_copy/        stat cache, draft-edit references, conflict bookkeeping
  resolutions/         recorded conflict resolutions

4.2. Pack files

veins has no loose objects and no deltas. Objects are stored in pack files that are written once and never modified.

vpack file:
  magic     "VPK1"
  u32       format_version = 1
  u64       object_count
  record*   (object_count records)
  trailer   32-byte BLAKE3 of all preceding bytes

record:
  id        object ID (32 bytes)
  u8        type_byte
  u8        compression (0 = none, 1 = zstd)
  varint    raw_length
  varint    stored_length
  bytes     stored data (stored_length bytes, no length prefix)

Each record is compressed independently, so any object can be read with one seek and one decompression. Chunks SHOULD be compressed with zstd (level 3 by default). Records that do not shrink SHOULD be stored uncompressed.

Records carry their IDs, so an index can be rebuilt by scanning headers without decompressing or rehashing. This is why there is no "resolving deltas" phase.

4.3. Index files

vidx file:
  magic     "VIX1"
  u32       format_version = 1
  u32[256]  fanout           ; cumulative count of ids whose first byte <= i
  id[N]     sorted object IDs
  u64[N]    pack offsets of the corresponding records
  trailer   32 bytes: the pack's trailer hash
  trailer   32 bytes: BLAKE3 of all preceding index bytes

Lookup is a fanout jump plus binary search, performed over a memory-mapped index. An implementation MUST verify that the index’s pack trailer hash matches the pack before trusting it.

4.4. Writing and durability

  1. Each state-changing command MUST write its new objects as a single new pack. The pack MUST be written to store/tmp/, flushed with fsync, and renamed into store/packs/, followed by the index (same procedure). The parent directory MUST be `fsync`ed after each rename.

  2. A pack without an index is ignored (and may be deleted by gc). The index is the commit point for the pack.

  3. Only after the pack and index are durable MAY the operation head be advanced (see Operation log).

  4. A crash at any point MUST leave the repository usable. At worst, unreferenced packs remain.

4.5. Reading and verification

  • Every object read from disk MUST be verified: the BLAKE3 of the decoded data MUST equal the ID used to look it up. Verification MUST be parallelizable and SHOULD use a SIMD implementation.

  • A verification failure MUST be a hard error naming the object and pack. The implementation MUST NOT silently fall back to another copy without reporting it.

  • vn fsck MUST verify all packs, indexes, canonical form, referential integrity (every referenced object exists or is promised), the operation log chain, and the git-map’s consistency.

4.6. Compaction and garbage collection

  • When more than 32 packs exist, the implementation SHOULD merge small packs into a larger one. Merging writes a new pack and index before deleting the sources.

  • vn gc computes the set of objects reachable from every operation in the operation log that has not been expired, and rewrites packs to drop everything else. The default expiry for operations is 90 days (configurable). Unreachable objects younger than 24 hours MUST NOT be deleted, to protect in-flight writes.

  • gc MUST NOT delete promised-object records, and MUST take the repository lock.

4.7. Promised objects

A repository cloned lazily records the remote that is the source of any object it references but does not hold. Such objects are promised. Reading a promised object that is absent triggers a fetch (see Lazy chunk fetching). If the remote is unreachable, the read fails with an error that names the missing object and the remote. Promised status applies only to chunks and blob manifest nodes. Commits, trees, and conflicts are always present locally.

5. Operation log and change IDs

5.1. Operations

Every command that changes repository state MUST create exactly one operation that records the resulting view. Read-only commands MUST NOT create operations. An operation that changes only the working-copy snapshot is tagged snapshot, and a snapshot that produces no change MUST NOT create an operation.

The current view is the view of the current operation head. The operation log is the DAG of operations through parents.

5.2. Concurrency

  1. A process loads all current operation heads from op_heads/.

  2. If there is more than one head, it first creates a merge operation: the views are combined with the same three-way rule used for conflicts (bookmarks may become conflicted), and the old heads are removed.

  3. After executing, the process writes its new operation’s pack, then creates op_heads/<new op id> and removes the file(s) of its parent(s) via atomic file operations.

Two processes that run concurrently may therefore produce two heads. The next command resolves them. No locking is required for correctness.

5.3. Undo and restore

  • vn undo creates a new operation whose view equals the view of the parent of the most recent undoable operation (that is, it records a restore, rather than deleting history).

  • vn op restore <op> creates a new operation whose view equals the view of <op>.

  • vn op revert <op> creates a new operation that applies the inverse of `<op>’s effect (the three-way merge of the current view, `<op>’s view, and `<op>’s parent view).

  • An undo is itself undoable. The operation log is append-only.

  • Objects are never deleted by undo, so a restore can always find them (until gc expires the operation).

5.4. Change IDs

  • A change ID is created when a commit is first created by veins (random, 16 bytes), and is copied to the rewritten commit when that commit is amended, rebased, or squashed.

  • A commit imported from git receives a change ID derived deterministically from its git SHA-1 (the first 16 bytes of BLAKE3 over "veins/change" || git_sha), unless the git commit carries a veins-change-id header, in which case that value is used.

  • Change IDs are displayed in lowercase base32 (RFC 4648 alphabet), as the shortest unique prefix with a minimum of 4 characters.

  • If two or more visible commits share a change ID, the change is divergent. vn log MUST flag divergence, and the commits are addressed by commit ID until one is abandoned.

  • Commands accept change IDs, commit ID prefixes, bookmark names, and @ (the working-copy commit) wherever a revision is expected. A change ID that resolves to one visible commit refers to that commit.

6. Working copy

6.1. Model (review)

The working copy is represented by a commit (conventionally @) recorded in the view per workspace. Before each command that reads or writes the working copy, veins MUST snapshot the files on disk into @ (creating a new commit with the same change ID, and an operation if anything changed). Consequences:

  • There is no staging area and no stash. Every on-disk edit is captured in history and can be restored through the operation log.

  • vn new starts a new empty change on top of @. vn describe -message <msg> sets a message. vn commit -message <msg> is describe followed by new.

  • Checking out a revision means making it (or a new empty child of it) the working-copy commit, then updating the files.

6.2. Empty changes

@ has changes when its root tree differs from the root tree of its first parent. A working-copy commit with no parents has changes when its root tree is not empty; it is compared with the empty tree.

vn describe MUST NOT create a commit or operation when @ has no changes and the requested message is identical to the current message.

vn commit MUST NOT create a commit or operation when @ has no changes, regardless of the requested message. It MUST instead report that there is nothing to commit and leave the repository unchanged. In particular, veins does not create empty commits implicitly.

6.3. Snapshotting

  • Tracked state is determined by the tree of the working-copy commit, plus any new files that are not ignored.

  • veins MUST keep a stat cache (path, size, mtime in nanoseconds, inode, content ID) in .veins/working_copy/. A file whose stat data is unchanged MUST NOT be re-read. A file whose mtime is within a "racy" window (less than 2 seconds old relative to the cache write) MUST be re-verified by content.

  • New or changed files are chunked and hashed in parallel. Files are only read once.

  • Ignore rules come from .vnexclude (gitignore syntax), which vn ex appends to. If ignore.git = true (default), .gitignore files are also honored.

  • File modes: only the owner execute bit is tracked. Line endings are not translated; bytes on disk are bytes in the store.

  • Exact renames (a deleted path and an added path with the same content ID) are recorded automatically in the snapshot commit’s renames. With rename.autodetect = similar (default), added/deleted pairs with similarity of at least 60% are also recorded. rename.autodetect = off records only renames made with vn mv.

6.4. Untracking paths

vn rm [-delete] <path>…​ removes paths from the working-copy tree. By default the files remain on disk; -delete also removes the matched tracked files from disk. Arguments are resolved relative to the current directory and may be literal paths or globs using , ?, and *. * and ? do not cross directory separators. If any argument does not match a tracked path, the command MUST fail without changing the working-copy tree.

Because every command snapshots the working copy first, a path that remains on disk and is not ignored will be added back to the working-copy tree by the next snapshot. vn rm MUST warn about such paths. vn ex <pattern>…​ appends gitignore-style patterns to the repository-root .vnexclude so that removed paths stay untracked. A successful vn rm records one operation.

6.5. Checkout safety

A checkout or update that would overwrite or delete a file MUST do so only if the file’s current content matches the snapshot (i.e., it was snapshotted first). Because every command snapshots first, local edits are never lost.

An implementation MUST:

  • create files with openat relative to a verified directory, refusing to follow symlinks that point outside the working copy;

  • validate every path component per Data model before writing;

  • write files by chunk streaming, so memory use is bounded by chunk size and not file size;

  • use multiple threads to write files.

7. Merging and conflicts

7.1. Principles

  1. A merge never fails. It produces a value, which may be a conflict.

  2. Conflicts live in history. A conflicted commit is a normal commit. It can be described, rebased, or built upon.

  3. Conflicts are values, not text. The merge engine and the object store never see markers.

  4. Resolution propagates. Resolving a conflict in one commit removes the conflict from descendants when it cancels algebraically.

  5. Deterministic. The same inputs MUST produce the same merged tree and conflict objects, so the same conflict has the same ID everywhere.

7.2. Conflict algebra

A value is a formal sum of signed terms whose signs add up to +1:

A0 - R0 + A1 - R1 + ... + An          (n >= 0 removes, n+1 adds)

n = 0 is an ordinary resolved value. A three-way merge of sides S1 and S2 with common base B is S1 + S2 - B, which is the term list adds = [S1, S2], removes = [B].

Operations:

  1. Flatten. If a term is itself a conflict value, its terms are spliced into the sum (a negated conflict has its signs flipped).

  2. Cancel. For each remove in order, cancel the first not-yet-cancelled add that is equal to it. Cancelled pairs are deleted.

  3. Resolve. If, after cancellation, only one add remains, the value is resolved to it. If all remaining adds are equal, the value resolves to that value.

  4. Order. Surviving terms keep their original relative order. By convention, adds[0] is "ours" and adds[1] is "theirs".

Examples:

Sum Result

A + B - A

B (ours unchanged, theirs wins)

A + A - B

A (both sides made the same change)

(A + B - O) + C - B

A + C - O (rebasing a conflicted commit)

X + (B - B)

X

7.3. Merge base selection

For merging heads S1 and S2, the common ancestors are the lowest common ancestors of the two commits in the commit DAG. If there is exactly one, base = B. If there are multiple (a criss-cross), the base is a virtual conflict value, produced by folding R1 + R2 - LCA(R1, R2) recursively over the ancestors. The virtual base is never written as a commit. The final merge is S1 + S2 - base, flattened and simplified. Unlike git’s recursive strategy, no virtual commit is created and no intermediate conflict markers can leak.

7.4. Tree merge

merge_trees(terms) takes a signed list of tree values (some possibly absent) and produces a tree. For each name present in any term:

  1. Collect each term’s entry (or absent), keeping signs.

  2. Flatten, cancel, and resolve. If the entry resolved, use it.

  3. Otherwise, if all remaining non-absent terms are subtrees, recurse with the corresponding subtrees (absent terms become empty trees).

  4. Otherwise, if all remaining non-absent terms are files (kind 0x01 or 0x02), attempt a file merge (see File merge). The executable bit is merged independently using the same algebra. If content resolves but modes do not, the result is a conflict.

  5. Otherwise (mixed kinds, for example a directory on one side and a file on the other, or a deletion against a modification), store a conflict object with the simplified terms.

Rename handling is applied before the per-name merge (see below).

7.5. Renames

Before merging, the engine computes for each side a rename map relative to the base:

  1. Walk the commits from the base to the side’s head. For each commit with renames_state = 1, apply its recorded renames. Composing renames means that a → b followed by b → c is a → c. A path that is deleted and re-added within the span is not a rename. Cross-parent entries (for merge commits) use the entries for the parent that is on the path.

  2. For any commit in the span with renames_state = 0 (typically imported from git), compute renames heuristically between that commit’s tree and its first parent’s tree. Exact content matches come first. Then similarity is scored as the Jaccard similarity of chunk-ID sets for blobs with more than one chunk, and line-based similarity for small blobs. Pairs of at least 50% similarity are accepted, assigned greedily by best score, with a cap of 5,000 candidate pairs per commit (beyond which only exact matches are used).

  3. When a side renamed P → Q and the other side changed P, the merge treats the other side’s change as applying to Q. If both sides rename P to different paths, the result at P is a conflict whose terms are the two destinations.

7.6. File merge

A file merge takes terms that are all regular files and attempts to produce a single blob.

  1. Classification. A file is binary if it contains a NUL byte in its first 8 KiB, or if its path matches a merge=binary attribute. Binary files do not merge at the content level: they resolve only through the algebra.

  2. Chunk fast path. Compare the terms' manifests. Chunk ranges that are identical between a side and the base are copied directly. Only the windows that differ, expanded to enclosing line boundaries, are diffed.

  3. Line merge. Within a differing window, use a histogram diff to compute diffs from the base to each side, then merge hunks as in diff3. Two hunks conflict if their base ranges overlap or are adjacent (touching with no unchanged line between them). merge.adjacent = merge may relax adjacency.

  4. More than three terms. Fold left to right: pair each remove with the adds around it, merge, and carry the result. If any step conflicts, the original simplified terms are kept as the conflict value.

  5. Result. If the whole file merges, store the merged blob. Otherwise, the entry becomes a conflict object, and the working copy materialization is as described in the next section.

7.7. Materializing conflicts in the working copy

A conflicted path is materialized as follows. For a conflict with two adds (ours = adds[0], theirs = adds[1]) and one remove (base = removes[0]), the files are:

Path Content

<path>

The merged file with conflicting regions resolved to ours. Non-conflicting hunks from both sides are applied. No markers are inserted. If ours is absent (deleted), <path> is not created.

<path>.base

The complete content of the base term (absent if the base term is absent).

<path>.ours

The complete content of adds[0].

<path>.theirs

The complete content of adds[1].

For conflicts with more than two adds, additional terms are named .theirs2, .theirs3, …​ for further adds and .base2, .base3, …​ for further removes.

Rules:

  1. Sidecar files are never snapshotted while their path is conflicted. Snapshotting skips any file whose name matches <conflicted path>.(base|ours|theirs|theirsN|baseN).

  2. If materializing a sidecar would overwrite a different tracked or untracked file, the command MUST fail before modifying the working copy and report the colliding path.

  3. A file-versus-directory conflict is materialized with <path> set to the ours side and the other side written as <path>.theirs (a file or directory tree).

  4. vn conflicts lists each conflicted path, its kind, and for text conflicts the line ranges of the conflicting hunks within <path> and within each sidecar. The -porcelain format MUST be stable, tab-separated, and documented. An editor integration can use it.

  5. vn status shows conflicted paths and the number of conflicted commits in the ancestry of @.

  6. Edits to <path> while the conflict is unresolved are drafts. The snapshot stores the draft as a blob, referenced from .veins/working_copy/ and from the view of the working-copy operation, so that the edit is recorded and survives undo and checkout. A draft never alters the stored conflict.

7.8. Resolving

  • vn resolve <path> accepts the current content of <path> as the resolution, replacing the conflict entry with that blob.

  • vn resolve -take ours|theirs|base <path> resolves to one term.

  • vn resolve -tool <cmd> <path> runs an external merge tool with the sidecars and <path> as arguments ($BASE, $OURS, $THEIRS, $OUTPUT placeholders), then resolves from $OUTPUT if the tool exits successfully.

  • On resolution, the sidecars for the path are deleted, and descendants are automatically rebased. Where the conflict cancels (for instance the same conflict appears in descendants), the descendants resolve without further user action.

  • vn resolve -list is an alias of vn conflicts.

Resolution never requires every conflict to be handled at once. Conflicts can be partially resolved, and the working copy is always usable.

7.9. Rebase and rewrite

When rewriting commit C with parent P onto new parent P':

tree(C') = tree(C) + tree(P') - tree(P)

evaluated as a tree merge (flatten, cancel, resolve, recurse). For a merge commit, tree(C') = tree© + Σ(tree(P'_i) - tree(P_i)). All descendants of a rewritten commit are automatically rebased, producing a single operation. Conflicts propagate through descendants in value form, and cancel when the algebra allows.

7.10. Resolution memory

When merge.rerere = true (default), veins records resolutions: the key is the BLAKE3 of the simplified conflict object, and the value is the resolved blob ID. The recorded resolutions are stored in .veins/resolutions/. Whenever a merge or rebase produces a conflict object whose key has a recorded resolution, veins resolves it automatically and notes it in the operation description. Keys are exact, so only identical conflicts are reused.

7.11. Path policies

A tracked .veinsattributes file assigns attributes to paths, with one glob attr=value rule per line (later rules override earlier ones).

Attribute Meaning

merge=text

Default for non-binary files.

merge=binary

Never merge content. Conflicts resolve only through the algebra.

merge=regenerate

On conflict, take ours, record no conflict, and mark the path as needing regeneration.

generated=true

Informational (hides from review diffs by default).

For merge=regenerate, vn status lists paths that need regeneration. If the local config defines regenerate.<glob> = <command>, vn regenerate runs that command and snapshots the result. A commit that contains a path still marked as needing regeneration triggers a warning. Commands are only read from local config (.veins/config), never from tracked files.

This is the intended answer to the case of a 100,000-line generated C file: no human ever merges it.

8. Git interoperability

8.1. The mirror repository

veins maintains a bare git repository at .veins/git. It serves as the staging area for all git traffic. Network operations with git hosts (such as GitHub) are performed by invoking the git executable against this repository, and objects are then imported to or exported from the veins store. This keeps veins independent of the git transport protocols.

8.2. ID mapping

The directory .veins/git-map/ holds persistent, append-only mapping tables:

Table Contents

commits

veins commit ID <→ git commit SHA-1

trees

veins tree ID <→ git tree SHA-1

blobs

veins blob ID <→ git blob SHA-1. Lazy IDs embed the SHA-1, but the mapping is still recorded for materialization and export.

raw

veins ID → original git object bytes, for commits and trees that cannot be reconstructed canonically (see below)

Lookups MUST work in both directions in O(log n) or better. Mappings are written in the same atomic step as the objects they refer to.

8.3. Import (git to veins)

vn git import converts every git commit reachable from the chosen refs that is not already in the map.

  1. Order. Parents before children. Independent subtrees and blobs are converted in parallel.

  2. Blobs are chunked and stored as veins blobs. The SHA-1 to blob ID mapping is recorded.

  3. Trees are converted entry by entry. Git modes map as follows: 100644 → file; 100755 → executable; 120000 → symlink; 040000 → subtree; 160000 → submodule. Any other mode MUST cause the tree to be stored in raw.

  4. Commits. Author, committer (name, email, seconds, timezone), message, parents, and all other headers (encoding, gpgsig, mergetag, and so on) are carried into the fields and extra. renames_state = 0. The change ID is derived as described in Operation log and change IDs.

  5. Round-trip check. The importer MUST re-serialize each commit and tree using the exporter, and compare the SHA-1 with the original. If they differ (non-canonical modes, unusual header order or whitespace, trailing data, and so on), the original bytes MUST be stored in raw and the exporter MUST use them verbatim.

  6. Importing is idempotent. A commit whose SHA-1 is in the map is not converted again.

The initial import of a long history pays git’s delta resolution cost once, for reading the source. This cost is not paid again on any later clone.

8.4. Lazy git-backed import (M1)

To keep import time independent of blob count and blob size, the M1 importer uses lazy blob IDs. It converts commits, trees, refs, the view, and the operation log, but it does not read, chunk, hash, or recompress blob bodies. A blob referenced by an imported tree is represented by a 32-byte lazy ID:

`"veins-gitoid"` (12 bytes) followed by the 20-byte git SHA-1

The body remains in the .veins/git mirror. Tree entries keep their normal file, executable, or symlink kind, but the target is a lazy blob ID instead of a canonical veins blob ID.

Reading a lazy blob reads the corresponding git object from the mirror. vn checkout uses this path, so an imported repository checks out to the same bytes as git. vn fsck treats lazy blob references as promised objects; they are not errors merely because they are absent from .veins/store.

Lazy IDs are deterministic for a given git blob. The blobs mapping table records them so that a later materialization pass can replace lazy references with canonical chunked veins blobs. Materialization is a separate operation and will rewrite the affected tree, commit, and view IDs. Deleting .veins/git while lazy references remain makes those blobs unavailable.

Lazy import is an importer fast path. Repositories created by a native veins clone use canonical chunked blobs and do not depend on a git mirror.

8.5. Export (veins to git)

vn git export writes the commits reachable from bookmarks and tags into the mirror.

  1. Commits are exported parents first. For a commit with a raw entry, those bytes are emitted unchanged (when its tree and parents map to the same git SHAs). Otherwise, the commit is serialized in git’s canonical form from its fields, with extra headers in order.

  2. Native commits (created by veins) include an extra header veins-change-id <hex> (review), so that a later import of the same git commit recovers the change ID. This header is never added to imported commits.

  3. Blobs are SHA-1-hashed once per distinct blob ID. The result is cached in the blobs table. SHA-1 MUST be computed with collision detection (sha1dc, as git does).

  4. Trees are serialized with git’s sort order (see Data model).

  5. Timestamps are exported at one-second precision.

  6. Renames and change IDs (except as in the header above) are not representable in git and are dropped.

  7. The exporter MAY write objects directly (as packs) or by driving git fast-import. Both MUST produce identical object IDs.

  8. Conflicted commits are not exported. If a bookmark points to a commit with a conflicted ancestor, the git branch is advanced to the nearest exportable ancestor on that bookmark’s first-parent chain, or is left unchanged if none exists. vn git export MUST report such bookmarks.

  9. The working-copy commit is exported only if a bookmark points to it.

  10. Export is incremental, driven by the commits map. Exporting one new commit MUST NOT require work proportional to repository size.

8.6. Refs

Bookmarks map to git branches (refs/heads/<name>), and tags to git tags. A bookmark’s remote tracking state is stored in remote_refs of the view and mirrored under refs/remotes/<remote>/ in the mirror. Fetching moves remote refs, not local bookmarks. Local bookmarks move on explicit command or merge.

8.7. Pull request workflow

  1. vn git push <remote> <bookmark> exports and runs git push from the mirror. Branch protection on the host prevents contributors pushing to your main branch.

  2. A contributor opens a pull request against the host in the normal way.

  3. vn git fetch <remote> runs git fetch into the mirror, then imports the new commits. Their git SHA-1s are preserved in the map.

  4. vn creates a bookmark for the imported branch. Review, test, and merge happen natively.

  5. After the merge, vn git push exports the merge commit. Because the contributor’s commits are exported under their original SHA-1s (they are in the map, with raw where needed) and the merge commit lists them as parents, the host recognizes the pull request as merged. If the owner squashes or rebases instead, the pull request simply shows as closed.

8.8. Leaving veins

vn git export -all followed by copying .veins/git to a normal .git directory MUST yield a git repository whose working tree is identical to the veins working copy, and whose history contains all exported commits, plus any conflict-free state. No other conversion is required. Users MAY keep using veins afterwards.

8.9. Invariants

Conforming implementations MUST satisfy:

  1. Import then export of any git repository reproduces every commit, tree, and blob SHA-1 exactly.

  2. Export then import of any exportable veins history in a fresh repository yields commits whose root trees and ancestry are isomorphic to the original (IDs may differ because change IDs and rename records are not carried unless the header is present).

  3. Idempotence. Repeating import or export with no changes performs no writes to the store other than its logs.

9. Native protocol

9.1. Overview

The protocol is a request/response protocol over any reliable, ordered, bidirectional byte stream. Clients authenticate to the server with Ed25519 keys inside the protocol (see Authentication and authorization), whatever the transport. The protocol itself provides no confidentiality: that is the transport’s job. Object integrity is guaranteed by the object IDs themselves.

The reference transports are:

URL form Transport Notes

ssh://[user@]host[:port]/path

SSH. The client runs ssh host vn serve -stdio <path>.

Secure. No channel binding is available.

veins://host[:port]/repo

TCP with TLS 1.3 (vn serve -listen).

Secure. Channel binding is the TLS exporter value. The client validates the server certificate against the system trust store, or against a pinned fingerprint set in remote.<name>.tls-pin.

file:///path

Local. The client spawns vn serve -stdio <path>.

Secure (local process).

Other transports (for example HTTP/2) MAY be added. A transport is secure if it provides confidentiality and integrity and authenticates the server to the client. Plain, unencrypted transports MAY be provided, but are insecure and subject to the restrictions in Authentication and authorization.

Design requirements:

  • A fresh clone MUST need no work proportional to delta-chain length, and no per-object reconstruction. The receiver writes received records straight into a pack.

  • The client MUST be able to fetch history (commits and trees) without file data, and fetch chunks on demand.

  • Chunks the client already holds MUST NOT be re-sent during incremental fetch.

  • A session without the write role MUST NOT be able to change anything in the repository, by any request.

9.2. Framing

frame:
  u32   length            ; of the rest of the frame, max 16 MiB
  u8    kind
  u32   request_id        ; chosen by the client; echoed in responses
  bytes payload (length - 5 bytes)

Multiple requests MAY be outstanding. Responses for different request_id`s MAY be interleaved. Frames of one request arrive in order. Unknown `kind values MUST be rejected with an ERROR frame.

9.3. Messages

Message Purpose

HELLO / HELLO_OK

Version and capability negotiation, repository selection, and exchange of nonces. Capabilities include zstd-records, lazy-chunks, push, auth-ed25519. The highest common version is used. See Authentication and authorization for the fields.

AUTH / AUTH_OK

Proves possession of an Ed25519 key. Sent at most once per connection, directly after HELLO_OK. AUTH_OK reports the role granted.

WHOAMI / WHOAMI_OK

Returns the session’s role (anonymous, read, or write) and key fingerprint.

LIST_REFS / REFS

Returns bookmarks and tags with their target commit IDs and change IDs.

NEGOTIATE / NEGOTIATE_OK

The client sends wants (commit IDs) and haves (commit IDs it owns, in batches of ancestors with exponentially increasing spacing). The server replies with which haves are known and whether it has enough common history.

FETCH_SKELETON

Requests all commits, trees, conflict objects, and blob manifest nodes reachable from wants and not reachable from the acknowledged haves. Response is a RECORDS stream.

GET_CHUNKS

Requests a list of chunk IDs. Response is a RECORDS stream in request order. Missing chunks produce NOT_FOUND.

HAVE_QUERY / HAVE_BITMAP

The client sends a sorted list of IDs. The server returns a bitmap of which it holds. Used by push.

PUT_RECORDS

The client sends a RECORDS stream of objects to store. Ends with a trailer hash.

UPDATE_REFS / UPDATE_REFS_OK

Atomic compare-and-swap of refs: list of (name, expected old target, new target). All-or-nothing.

ERROR

Error code and message. Terminates the request.

RECORDS streams contain a sequence of records in the same layout as pack records, terminated by an END frame containing the 32-byte BLAKE3 hash of the concatenated record bytes. Records on the wire MAY be zstd-compressed exactly as stored, so a server can send stored bytes without decompressing or recompressing. Each record carries its ID, so the receiver needs no per-object reconstruction to build the index.

9.4. Clone and fetch flow

  1. HELLO, then AUTH (omitted for an anonymous read of a repository that allows it), then LIST_REFS.

  2. NEGOTIATE (for a clone, haves is empty and the server can skip to step 3).

  3. FETCH_SKELETON. The client writes the records into a pack as they arrive, builds the index in one pass, and verifies each record’s hash in parallel with receipt. Hashing uses multiple threads.

  4. The client chooses a chunk policy (vn clone -blobs <policy>):

    • head (default): fetch all chunks needed to check out the target commit.

    • none: fetch no chunks. Everything is promised.

    • all: fetch every chunk in history.

  5. For head or all, the client computes the set of chunk IDs it lacks from the received manifests and issues GET_CHUNKS. On an initial clone with all, the server MAY satisfy this directly by streaming its packs, because it knows the client has nothing.

  6. In incremental fetches, the client sends GET_CHUNKS only for chunk IDs it does not already hold (found by index lookup). Revisions of a regenerated file share most chunks, so only the changed chunks cross the wire.

The client MAY verify hashes lazily in the background (-verify=lazy) but the default is eager. Failed verification MUST abort the operation and discard the received data.

9.5. Lazy chunk fetching

  • A repository with promised objects stores the promisor remote name in config.

  • Reading an absent promised chunk MUST trigger a GET_CHUNKS to the promisor. The client SHOULD prefetch following chunks of the same blob when the first chunk of the blob is requested (read-ahead), and SHOULD batch concurrent misses.

  • Fetched chunks are written to a new pack and are no longer promised.

  • Lazy fetches authenticate exactly like any other request. If the client’s access has been revoked, the fetch fails with FORBIDDEN or AUTH_FAILED, and local data is unaffected.

  • Commands that need file content (checkout, diff, merge) work in a lazy repository when the promisor is reachable. Commands that need only history (log, bookmark, rebase of non-conflicting changes by tree) do not touch the network.

9.6. Push flow

  1. HELLO, then AUTH, then LIST_REFS. The session MUST hold the write role; the server rejects the push otherwise (see Authentication and authorization).

  2. The client determines the new commits and queries HAVE_QUERY for the chunk and manifest IDs that those commits reference but are not known to be on the server.

  3. The client sends PUT_RECORDS containing the missing objects. The server verifies the hash of every record, enforces canonical form and limits, and checks closure: every object referenced by an accepted object MUST either exist on the server or be in the same push.

  4. The client sends UPDATE_REFS with the expected old values. If any ref does not match, the update fails entirely, and the client MUST fetch and merge.

  5. Pushing a conflicted commit is refused by default (push.allow-conflicts = false). A server MAY accept it.

The operation log is not pushed or fetched. Operation history is a local concern.

9.7. Server

vn serve operates on a normal veins store plus a ref table (refs/ with one file per bookmark and tag, updated by atomic rename under a lock). A server repository has no working copy. It MUST compact and gc like any other store, and MUST NOT delete objects reachable from any ref.

Two modes exist:

  1. vn serve -stdio <repo> serves one repository over standard input and output. It is used by the SSH and local transports.

  2. vn serve -listen <addr:port> -root <dir> -tls-cert <file> -tls-key <file> serves every repository under <dir> over TLS. The repository named in HELLO MUST be resolved relative to <dir>. Names containing .., absolute paths, or NUL MUST be rejected.

Each repository’s access policy is read from its own .veins/access file.

9.8. Errors

Code Meaning

1 UNSUPPORTED_VERSION

No common protocol version.

2 BAD_FRAME

Malformed or oversized frame.

3 NOT_FOUND

Requested object or ref does not exist.

4 HASH_MISMATCH

A record’s ID does not match its content.

5 NON_CANONICAL

An object violates canonical form or limits.

6 MISSING_CLOSURE

Pushed object references an object the server lacks.

7 REF_CONFLICT

UPDATE_REFS compare failed.

8 REJECTED

Policy rejection (for example conflicted commit).

9 INTERNAL

Server error.

10 UNAUTHENTICATED

The request needs an authenticated identity (or the repository does not allow anonymous access) and the session has none.

11 FORBIDDEN

The session is authenticated, but its role does not permit the request.

12 AUTH_FAILED

Authentication failed. The same code is returned for an unknown key, a bad signature, a malformed key, and a nonexistent repository.

10. Authentication and authorization

10.1. Model

A veins server authenticates clients itself, using Ed25519 keys. This is independent of the transport: the same keys work over SSH, TLS, and local connections, and the server never uses SSH user names, operating-system accounts, or TLS client certificates to decide what a client may do.

Authorization is per repository. A key has exactly one of two roles on a repository, and a repository MAY additionally allow anonymous reads.

Role Permitted

anonymous

Read operations, only if the repository’s access file has an anonymous read directive.

read

Read operations: everything a clone, fetch, or lazy chunk request needs.

write

Everything read can do, plus push.

There are no accounts, passwords, groups, or per-bookmark and per-path rules in v1. A read key can read the complete repository: all history, all refs, all chunks. Anything committed to a repository is visible to every reader of that repository. Per-path secrecy is not provided and MUST NOT be implied by tooling.

10.2. Keys

  • A key’s public half is 32 bytes. Its fingerprint is the lowercase base32 (RFC 4648 alphabet, no padding) encoding of the first 16 bytes of BLAKE3("veins/key/1" || public_key), which is 26 characters.

  • Public keys are written as ed25519: followed by unpadded base64url of the 32 bytes.

  • Private keys are stored on the client in the user key directory: $XDG_CONFIG_HOME/veins/keys/ (default ~/.config/veins/keys/) on Linux and macOS, and %APPDATA%\veins\keys\ on Windows. One file per key, named <key name>.key. Each file holds a format version byte and the 32-byte seed. It SHOULD be encrypted with a passphrase (Argon2id key derivation and an authenticated cipher, with parameters recorded in the file).

  • On POSIX systems vn MUST refuse to use a private key file that is readable or writable by group or others.

  • Private keys MUST NOT be written to repositories, configuration files, logs, or error messages.

  • A remote selects its key with remote.<name>.key = <key name>. The default key name is default.

  • vn key import -openssh <file> MAY be offered to import an OpenSSH Ed25519 private key.

10.3. Server access file

The file .veins/access in a served repository defines who may do what. It is UTF-8 text, one directive per line. Blank lines and lines beginning with # are ignored.

# allow <role> <public key> [<name>]
allow write ed25519:q3x8...43 characters of base64url...  laptop
allow read  ed25519:Zk2m...43 characters of base64url...  ci-runner

# serve this repository to unauthenticated readers
anonymous read

Rules:

  1. role is read or write. name is optional, contains no whitespace, and is used only in logs and listings.

  2. A key MUST appear at most once. A duplicate is an error.

  3. An unknown directive, unknown role, or malformed key is an error. If the file has any error, the server MUST refuse to serve that repository (fail closed) and report the line number locally. It MUST NOT serve it with a partial policy.

  4. If the file does not exist, nobody has access: no keys are authorized and anonymous reads are off.

  5. On POSIX systems the server MUST refuse to use a file that is writable by group or others.

  6. The server MUST read the file when a connection is opened. It SHOULD re-validate open sessions when the file’s modification time changes and terminate sessions whose key was removed or whose role was lowered (the session’s next request fails with FORBIDDEN).

10.4. Managing access

Access is managed only on the server machine, by someone with filesystem access to the repository. No protocol message changes the access file, so a write key cannot grant itself or anyone else access.

Command Effect

vn access add -role read|write -key <public key or file> [-name <name>]

Add a key.

vn access list

List keys with role, name, and fingerprint, and whether anonymous read is on.

vn access remove <fingerprint or name>

Remove a key (revocation).

vn access anonymous on|off

Add or remove the anonymous read directive.

Client-side key commands:

Command Effect

vn key generate <name>

Create a key pair and print the public key and fingerprint.

vn key list

List local keys with fingerprints.

vn key show <name>

Print the public key.

vn key import -openssh <file>

Import an OpenSSH Ed25519 key (optional feature).

vn whoami [<remote>]

Connect and report the role and key fingerprint the server grants.

10.5. Handshake

After the transport is established, the exchange is:

HELLO (client -> server):
  u16   min_version
  u16   max_version
  list<bytes> capabilities
  bytes repo               ; repository name; may be empty for stdio servers
  bytes client_nonce       ; 32 random bytes

HELLO_OK (server -> client):
  u16   version            ; highest version both support
  list<bytes> capabilities
  bytes server_nonce       ; 32 random bytes, fresh for every connection
  u8    auth_required      ; 1 if anonymous reads are not allowed for this repository

AUTH (client -> server), optional, at most once:
  bytes public_key         ; 32 bytes
  bytes signature          ; 64 bytes

AUTH_OK (server -> client):
  u8    role               ; 1 = read, 2 = write
  bytes fingerprint        ; 16 bytes

The signature is a pure Ed25519 signature (RFC 8032) over the message:

"veins-auth/1" 0x00
|| u16 version              ; the version from HELLO_OK
|| bytes repo                ; exactly as sent in HELLO
|| server_nonce
|| client_nonce
|| bytes channel_binding      ; empty if the transport provides none

Rules:

  1. The server MUST generate server_nonce from a cryptographically secure random source and MUST NOT reuse it. It MUST verify the signature over the message using the nonces of the current connection. A signature is never valid on any other connection.

  2. Channel binding. On TLS, channel_binding is the 32-byte TLS 1.3 exporter value for the label EXPORTER-veins-auth/1 with an empty context. This ties the signature to the TLS session, so a malicious intermediary that accepts the client’s connection cannot forward the signature to the real server. Other transports MUST define their binding. On transports without a binding (SSH stdio, local), it is empty and protection against relay depends on the transport authenticating the server (the SSH host key).

  3. The server finds the public key in .veins/access. If the key is unknown, or its signature is invalid, or the repository does not exist, the server MUST send AUTH_FAILED with identical content and timing characteristics for all three cases, so that probing cannot discover which keys or repositories exist.

  4. After a failed attempt the server SHOULD delay its reply by a fixed amount and MUST close the connection after three failed attempts. A server SHOULD rate-limit failed attempts per source address where the transport exposes one.

  5. A second AUTH on the same connection is a protocol error (BAD_FRAME). The session’s role is fixed once set and cannot be raised by a later message.

  6. A client SHOULD authenticate whenever auth_required is 1 or it intends to push. A client that holds no key and sees auth_required = 0 MAY proceed anonymously.

  7. If the repository does not exist, HELLO_OK still returns auth_required = 1, and every later request except WHOAMI fails with UNAUTHENTICATED, so a nonexistent repository looks like a private one.

10.6. Transport security

  • A server MUST NOT accept AUTH on an insecure transport. It MUST reply AUTH_FAILED and SHOULD close the connection.

  • On an insecure transport, only anonymous reads of repositories that allow them are possible. A server MUST reject every other request with UNAUTHENTICATED, including all write requests.

  • An implementation that offers an insecure transport MUST keep it disabled unless explicitly enabled by the operator, and it MUST be restricted to anonymous read-only use.

  • On an insecure transport the contents of fetched objects are protected by their hashes, but ref values are not authenticated and a network attacker can serve stale or withheld refs. Clients SHOULD warn when fetching refs over an insecure transport. Signed refs are a possible future extension.

  • The file:// transport and ssh:// transport are secure in the sense above. TLS clients MUST validate the server certificate, or match a pinned fingerprint, and MUST refuse TLS versions below 1.3.

10.7. Request authorization

The server MUST check authorization on every request, using the session’s role, and not only at connection time.

Request anonymous read write

HELLO, AUTH, WHOAMI

yes

yes

yes

LIST_REFS, NEGOTIATE, FETCH_SKELETON, GET_CHUNKS

yes*

yes

yes

HAVE_QUERY

no

no

yes

PUT_RECORDS

no

no

yes

UPDATE_REFS

no

no

yes

(*) Only if the repository has an anonymous read directive. Otherwise the request fails with UNAUTHENTICATED.

When a request is refused, the server MUST return UNAUTHENTICATED if the session has no authenticated identity and FORBIDDEN if it has one with an insufficient role. A refused request MUST NOT change any server state.

HAVE_QUERY requires write because it exists only to support push, and so that anonymous resource use stays bounded.

10.8. Resource limits for unauthenticated use

A repository that allows anonymous reads can be used by anyone, so the server MUST bound resource use per connection and SHOULD bound it per source address: concurrent connections, bytes sent per period, the number of IDs in one GET_CHUNKS (at most 4096 for any session), the size of one FETCH_SKELETON response, and the time allowed to complete HELLO. The limits SHOULD be configurable by the operator.

10.9. Audit log

A server SHOULD append to .veins/server.log one line for each connection outcome (time, source address if known, repository, role, key fingerprint or anonymous, and success or error code) and one line for each successful UPDATE_REFS (time, fingerprint, ref name, old and new targets). Logs MUST NOT contain private keys, nonces, or signatures.

Authentication identifies the key that pushed, not the author of the commits. Author and committer fields in commits remain self-asserted. Commit signing is a separate, future feature (see veins-sig in Commit objects).

10.10. Deployment notes (informative)

  • Over SSH. An SSH account that has a shell, or file access to the repository directory, can read and write the store directly and bypass veins' authorization entirely. To enforce read-only access, give users a restricted account whose only permitted command is the server, for example an authorized_keys entry of the form command="vn serve -stdio /srv/veins/project",restrict ssh-ed25519 …​. Then the veins keys, not the SSH accounts, decide each client’s role.

  • Public repositories. Add anonymous read and serve over the TLS transport. Authenticated keys then matter only for pushing.

  • Revoking a key. Run vn access remove. If the key was used to push something undesirable, history in the repository can still be rewritten or abandoned by an operator with local access.

11. Command-line interface

The program is vn (vn.exe on Windows). The first column below lists each command as invoked.

Command Description

vn init [path] [-git-import:<gitdir>]

Create a repository, optionally importing an existing git repo.

vn clone <url> [-blobs head|none|all]

Clone via the native protocol.

vn status

Working-copy changes, conflicts, files needing regeneration.

vn log [-rev <revset>] [-no-col-titles]

Show history, newest first, flagging conflicted and divergent changes.

vn show <rev>, vn diff [-rev <rev>]

Display a commit or a diff.

vn new [<rev>…​], vn describe [-message <message>], vn commit -message <message>

Create and describe changes. vn commit does nothing when the working copy has no changes.

vn mv

Move tracked files, recording renames.

vn rm [-delete] <path>…​, vn ex <pattern>…​

Untrack paths from the working copy (files stay on disk by default), or add ignore patterns to .vnexclude.

vn merge <rev>…​

Create a merge commit. Never fails; may produce conflicts.

vn rebase -s <rev> -d <rev>

Rewrite commits onto a new parent, auto-rebasing descendants.

vn squash, vn split, vn abandon

Rewrite or remove changes.

vn conflicts [-porcelain]

List conflicts with hunk line ranges.

vn resolve

See Merging and conflicts.

vn regenerate

Run configured regeneration commands for merge=regenerate paths.

vn undo, vn op log, vn op restore <op>, vn op revert <op>

Operation log commands.

vn bookmark set|list|delete, vn tag

Manage named pointers.

vn fetch, vn push

Native protocol.

vn git import [-source:<gitdir>] [path], vn git export, vn git fetch, vn git push, vn git remote

Git bridge.

vn serve -stdio <repo>, vn serve -listen <addr:port> -root <dir> …​

Run the native server over stdio or TLS.

vn key generate|list|show|import

Manage client keys.

vn access add|list|remove|anonymous

Manage a served repository’s access file (server side, local only).

vn whoami [<remote>]

Report the role and key fingerprint the server grants.

vn fsck [-verbose], vn gc

Verification and garbage collection.

vn config

Read and write configuration.

vn help [<command>], vn -help, vn version, vn -version

Show usage or version information.

vn log prints commits newest first in aligned columns with no borders. Column titles are shown by default and can be omitted with -no-col-titles. Output is colored when standard output is a terminal; setting NO_COLOR disables color.

vn status colors its change markers (A bright green, M cyan, D red, and C bright red). vn diff prints unified hunks with context; removed lines are red and added lines are green.

All commands that change state MUST be atomic with respect to the operation log: they either produce one operation or leave the repository unchanged.

12. Performance requirements

12.1. Reference workloads

Workload Description

W1 (synthetic)

A repository of 2,000 revisions of one generated 100,000-line C file (about 4-6 MiB), where each regeneration changes 0.5-5% of lines in scattered locations, plus 200 ordinary source files with normal edit patterns.

W2 (real)

The spectrelang/spectre repository (about 17,700 objects, 228 MiB pack), as measured in the project’s initial investigation: 16.2 s clone from GitHub, about 8.6 s clone from a local file:// copy, with roughly 19 CPU-seconds in index-pack.

W3 (real)

The owner’s largest private project(s) that motivated veins.

12.2. Requirements

ID Requirement

P1

No phase of clone, fetch, or checkout may have cost proportional to delta-chain length. Reading any file at any revision MUST cost O(file size) plus a bounded number of index lookups.

P2

On W1 and W2, a native vn clone over the same local or loopback transport SHOULD be at least 3x faster in wall-clock time than git clone file:// of the same history after git gc --aggressive.

P3

Clone throughput SHOULD be limited by the transport or disk, not CPU, on a machine with at least 4 cores.

P4

Incremental fetch of N new revisions of a large regenerated file SHOULD transfer bytes proportional to the changed chunks.

P5

vn status with an unchanged working copy of 100,000 files SHOULD complete within 200 ms (warm cache).

P6

Exporting one new commit to git SHOULD complete within 1 s (excluding the network).

P7

Checkout of a large file MUST use bounded memory (chunk-sized buffers).

P8

Store size on W1 SHOULD be no more than 2x that of the same history in an aggressively repacked git repository. This is a soft target. Chunking compresses less well than delta chains. This trade-off is accepted.

Go/no-go gate. At milestone M1 (see Milestones), measure P2 on W1 and W2. If veins is less than 2x faster than git on the clone of W1, stop and reconsider the design (or use jj with a tuned git repack) before building further.

12.3. Measurement method

Benchmarks MUST be reproducible scripts: pinned inputs, cold and warm cache runs (drop caches between), at least five runs with median and spread reported, and CPU time, wall time, bytes read and written, and peak memory recorded. Baselines for git MUST be run on a freshly repacked server copy so that git’s reuse-of-existing-deltas behavior is accounted for.

13. Security considerations

  • Hostile repositories. All data received from the network or from imports MUST be treated as untrusted: verify hashes, enforce canonical form, enforce limits, and refuse names per the rules in Data model.

  • Decompression bombs. A record’s declared raw_length MUST be checked against type limits before decompressing, and decompression MUST stop at the declared length.

  • Path attacks. Checkout MUST NOT write outside the repository root (no .., no absolute paths, no writes through symlinks that point outside, no case-folded .git or .veins components).

  • Code execution. veins MUST NOT execute commands whose definition comes from tracked or fetched data. Merge tools, regenerate commands, and hooks are read from local config only.

  • Hash function. BLAKE3 is not known to be vulnerable to collision attacks. Git SHA-1 is only used for export, with collision detection, and a detected collision MUST abort the export.

  • Signatures. Signature support (veins-sig in extra) is reserved for a future version. Imported gpgsig headers are preserved but not verified by veins.

  • Server. The server MUST validate every pushed object as described in Native protocol, and rate-limit or bound resource use per connection.

  • Authentication. Identity is an Ed25519 public key verified by a challenge-response signed over fresh nonces, the repository, the protocol version, and a channel binding. Replay of a captured signature fails because nonces are per-connection. Relay attacks are prevented by channel binding on TLS and by server authentication on SSH. See Authentication and authorization.

  • Authorization. Roles are checked on every request. Write requests need the write role, and a refused request never changes state. Anonymous sessions are read-only. No protocol message modifies the access file.

  • Information disclosure. An unknown key, a bad signature, and a nonexistent repository are indistinguishable to the client. A read key (or an anonymous session on a public repository) can read all history and all chunks. Secrets that were ever committed remain visible to every reader, and must be rotated rather than removed from history.

  • Denial of service. Anonymous access exposes read paths to the internet. Servers MUST apply the resource limits in Authentication and authorization.

  • Key handling. Private key files are owner-only and SHOULD be passphrase-protected. Comparisons of secret-dependent values MUST be constant time. Randomness MUST come from the operating system’s secure source.

  • Insecure transports. Authentication is refused on them, and only anonymous reads are possible. Ref values on such transports are not authenticated.

14. Implementation notes (informative)

This section describes the project owner’s intended implementation language, Spectre, and has no normative weight.

14.1. Required library support

Capability Notes

Threads, mutexes

Exist. Mutex storage MUST be sized for the largest supported platform (aarch64 Linux pthread_mutex_t is 48 bytes), or over-allocated.

Condition variables / semaphores

Needed for a work-queue thread pool.

CPU count

sysconf(_SC_NPROCESSORS_ONLN) on POSIX.

Atomics

May require a small C shim. Do not spin on plain variables, because aggressive folding may hoist loads.

BLAKE3

Bind the C implementation (with SIMD) through FFI.

zstd

Bind through FFI.

SHA-1 with collision detection

Bind sha1dc through FFI. Needed for export only.

File primitives

mmap, fsync, atomic rename, openat/O_NOFOLLOW, directory fsync, flock.

Ed25519

Bind a maintained library (for example libsodium or Monocypher) through FFI. Do not implement it from scratch.

TLS 1.3

Bind a maintained TLS library that supports the exporter interface (RFC 5705 / RFC 8446 section 7.5), certificate validation, and pinning.

Secure randomness

getrandom / arc4random_buf / BCryptGenRandom for nonces and key generation.

Passphrase KDF and AEAD

Argon2id and an authenticated cipher for protecting private key files. libsodium provides both.

14.2. Structure

  • Give each worker thread its own arena allocator for hashing and chunking to avoid heap contention.

  • Express codec invariants as contracts, for example postconditions asserting decode(encode(x)) == x and that canonical-form rules hold. Keep trust blocks small and confined to FFI and syscalls.

  • Keep the object format specification and a set of binary test vectors independent of any implementation, so that a second implementation (for example a small reader in another language, for debugging) can be checked against it.

14.3. Test strategy

  • Round trip. Import a git repository, export it, and compare every SHA-1 (differential test against git). Run on W2, git’s own repository, and a Linux kernel subset.

  • Fuzzing. Fuzz every decoder (objects, packs, indexes, protocol frames).

  • Crash injection. Kill the process at random points during writes and verify that vn fsck is clean and the operation log is consistent.

  • Authorization matrix. For every request type and every session type (anonymous, read, write, revoked key, unauthenticated on a private repository, authenticated attempt on an insecure transport), assert the exact result. Assert that anonymous and read sessions leave the repository byte-for-byte unchanged, including after malformed and oversized requests.

  • Authentication. Fuzz HELLO and AUTH. Test replay of a captured AUTH on a new connection, wrong repository, wrong channel binding, truncated and malleable signatures, and identical failures for unknown keys and nonexistent repositories (compare bytes and timing).

  • Algebra properties. Property tests for flatten/cancel/resolve: sum commutativity (up to term order), cancellation idempotence, rebase-then-resolve equivalence.

  • Merge corpus. Replay historical merges from real repositories and compare outcomes with git’s three-way results. Differences must be explained (adjacency policy, renames).

15. Milestones

ID Scope Exit criteria

M0

Object codecs, IDs, chunker, pack and index format, fsck, test vectors.

Fuzz-clean. Test vectors published. Chunker deterministic across platforms.

M1

Git importer, store, checkout (parallel, bounded memory). Benchmarks on W1, W2.

Go/no-go: P1 and P2 measured. Import then checkout reproduces git’s working tree byte for byte.

M2

Working copy snapshotting, status, log, diff, describe, new, operation log, undo, op restore, git export.

Round-trip SHA invariants hold. Crash-injection tests pass.

M3

Conflict algebra, tree merge, file merge, renames, materialization with sidecars, resolve, rebase with auto-rebase, resolution memory.

Algebra property tests pass. Merge corpus replay explained.

M4

Git import-back, refs, fetch/push through the mirror, pull request workflow.

A contributor pull request can be imported, merged, and shown as merged on the host.

M5

Native protocol: serve over stdio and TLS, authentication and authorization (vn key, vn access, vn whoami, anonymous read), clone, fetch, push, lazy chunks, -blobs policies.

P3 and P4 measured. Hostile-input tests pass. The authorization matrix tests pass: anonymous and read sessions never mutate the repository, and a revoked key loses access.

M6

Path policies (regenerate), gc, pack compaction, operation expiry, polish.

Long-running soak test with gc has no data loss.

16. Open questions

  1. Working copy model. Should veins offer a git-like staging mode, or is the auto-snapshot model acceptable for all use? (Section "Working copy".)

  2. Line-aware chunking. Should chunk cut points prefer line boundaries for text files? This may improve diff and merge alignment, but makes the chunker content-type dependent and changes chunk IDs.

  3. Chunk parameters. Is 64 KiB average the best size for generated C? Smaller chunks dedupe better but increase manifest and index overhead. This should be tuned on W1 and W3 before the parameters are frozen.

  4. Change-ID header. Is adding veins-change-id to exported native commits acceptable? It changes the git SHA of every native commit versus an export without it, and some users might consider it noise.

  5. Cross-repository identity. A native commit that is exported and imported into a second repository yields a different veins commit ID than the original. Is that acceptable, or should an optional hashed git_origin field be allowed?

  6. Submodules and LFS. Submodules are preserved opaquely. LFS pointer files are ordinary files, and no LFS support is specified.

  7. Case-insensitive file systems. Need a policy for trees that contain names differing only by case.

  8. Windows. The native design assumes POSIX semantics for checkout safety. Windows support is deferred.

  9. Large directories. Tree objects are flat. Sharding for directories with very many entries is not specified.

  10. Structural merge. A tree-sitter-based layer is a candidate for a post-v1 extension of the file merge stage.

  11. Finer-grained access. Roles beyond read and write, groups, per-bookmark rules, and per-path read restrictions are out of scope for v1. Per-path read restrictions are especially hard because chunks are content-addressed and shared across paths.

  12. Repository-wide write protections. write can currently force-update and delete any ref. Should there be repository-wide settings such as denying non-fast-forward updates or deletions (not per-bookmark)?

  13. Key agents and hardware keys. Support for an ssh-agent-style key agent, or hardware-backed keys, so private keys need not sit on disk.

  14. Key lifetime. Expiry dates on keys, and whether a time-limited key is worth the added file format.

  15. Signed refs and commit signing. Authenticating ref values on insecure transports and attributing commits cryptographically.

  16. HTTPS transport. Whether to add an HTTP/2 transport, which would help with proxies and firewalls and would need its own channel-binding definition.

  17. Default TLS port and URL scheme. No default port is specified for vn serve -listen.

  18. Line endings. No autocrlf-style conversion exists. Users who work on mixed platforms and mirror to git may need a policy.