tenon vc
format and CLI contract (tvc 1)
This is the frozen interface between the vc lanes. This is the
implementation contract. Design and execution status live in
the vc plan. After that, a lane edits its own section
only when the contract itself changes; that edit is its own
docs(spec) commit, and the open lanes are told about
it. ADRs: 0160 (no git), 0161 (storage unit), 0162 (merge).
Revision 2b applies the second review pass
(REVIEW.md §E); revision 3 applies the third
(REVIEW.md §F).
1. Layout
<root>/.tenon/vc/ the store: durable data, never a cache
format "tvc 1\n"
config policy (§6); lives only in the store, never in the tree
objects/<2 hex>/<62 hex> immutable objects (§2)
refs/branches/<name> "<commit>\n"
refs/tags/<name> "<commit>\n"; created once, never moved
locks/<name> empty files held with File::lock (§5)
queue/next "<seq>\n"; the next sequence number
queue/pending/<seq>-<branch> "<commit>\n"; seq is 8 digits, zero-padded
queue/active/<seq>-<branch> the one entry being processed
queue/done/<seq>-<branch> "landed <commit>\n" | "rejected <code> <one-line reason>\n"
gates/<tree>-<key> "<gate-id>\n"; written only by the queue
approvals/<branch>/<owner> "<approval-id>\n"
worktree-gates/<id> "<gate-id>\n"; informational, never queue authority
cache/ derived; safe to delete
<root>/.tenon/vc-run/<seq>/ the queue's scratch tree for gating; deleted afterwards
<worktree>/.tenon/vc-tree/ per-worktree state; never copied by ADR-0117 snapshots
store absolute path of the store
branch "<name>\n"
head "<commit>\n"; the commit the files were last checked out from
index "<mtime-ns> <size> <inode> <id> <path>\n", sorted by path, written whole
sync present only during a conflicted sync: "<protected tip>\n"
conflicts "<path>\n" per file that `sync` wrote with markers, sorted; absent when empty
Snapshots exclude .git and
.tenon at every level (as ADR-0117 does), plus
anything matching a config ignore glob. The store
root is also a worktree.
2. Objects
- Encoding. An object is
"<kind> <len>\n" + payload. Its id is the lowercase hex SHA-256 of the whole object (sha256.rs::digest). - Kinds.
blob,chunk,module,tree,commit,gate,approval. - Payloads.
blobandchunkpayloads are raw bytes. All other kinds are UTF-8 lines ending in\n, with fixed fields first and free text last (running to the end of the line).
Writing. Every command that writes objects
holds locks/gc shared (§5).
- If the object already exists, skip it.
- Otherwise:
- Write
objects/tmp-<pid>-<n>. - fsync it.
- Rename it into place.
- fsync the directory.
- Write
- Before the command releases the lock, every object it wrote must be reachable from a root (§5).
commitchecks that every object it references exists, writing any that are missing, except objects it inherits unchanged from the parent tree.
tree
<mode> <kind> <id> <name>
| Field | Values |
|---|---|
| mode | f for a file, x for an executable
file |
| kind | mod (fmt-clean .tn, pointing to a
module), raw (any other .tn, pointing to
a blob), blob, or tree (with mode
f) |
- Entries are sorted by name bytes.
- A name must be valid UTF-8, must not be
.or.., and must not contain/, NUL or control characters. - Two names in one tree must not be equal after ASCII case folding.
- Snapshots reject symlinks, special files and multiply-linked files.
- Empty directories are not stored.
.tnfiles that start with gen's magic line (~1g, seegen.rs) areblob.
module
fmt <FMT_VERSION>
header <chunk-id> optional
item <chunk-id> <key>
impl <head-id> <tail-id> <key>
method <chunk-id> <key> zero or more, following their impl line
footer <chunk-id> optional
Keys come from the parser alone, using the
existing outline vocabulary:
| Item | Key |
|---|---|
| function (any form) | fn <name> |
| struct | struct <Name> |
| enum | enum <Name> |
| newtype | type <Name> |
| interface | interface <Name> |
| derive | derive <Gen> for <Target> |
| impl | impl <Iface> for <Type> |
| method | <Iface> for <Type>.<name>,
which is FnEntry::full_selector |
The type text is the AST's to_string(). A key
repeated within a module makes the whole file
raw.
Addressing. An item is addressed as
<path>#<key>, for example
src/geom.tn#fn area. The CLI, OWNERS and the
dependency graph all use this form.
Split applies only when
fmt(f) == f; otherwise the file is
raw.
- header: the imports, plus the comments before and between them. With no imports there is no header.
- item chunk: the comments that precede the item, plus its text through its closing line, with no trailing newline.
- impl: always an impl unit, even with no methods;
fmtprints an empty impl on two lines.- head: the preceding comments plus the
impl … {line. - method chunk: the method's preceding comments plus
the method, with indentation exactly as printed. Comments right
after
{belong to the first method. - tail: the comments after the last method, plus
}.
- head: the preceding comments plus the
- footer: the comments after the last item.
Join is concatenation:
- Join
[header?] ++ unitswith"\n\n". - If there is a footer, append
"\n" + footer, or the footer alone if step 1 produced nothing. - If the result is non-empty, append
"\n".fmtturns an empty file into 0 bytes.
An impl unit is written as
head + "\n" + (methods joined by "\n", followed by "\n", if there are any) + tail.
Invariants, all tested:
join(split(f)) == ffor every fmt-cleanf.fmt(join(m)) == join(m)for every module produced by merge.- Writes (
commit,sync, the queue) split only under the runningFMT_VERSION. Reading and joining any older version always works.
commit
tree <id>
parent <id> 0 or 1 lines
base <id> branch commits only
source <id> landing commits only: the branch commit that landed
by <k>=<v> ... keys: agent model reviewer tokens_in tokens_out cost; values match [A-Za-z0-9._:@+-]+ or "unknown"
time <RFC 3339 UTC>
gate <gate-id>|none
(a blank line)
<message, any UTF-8>
Protected commits are written only by
init and by the queue. base(C) is the
commit's base line if it has one. Otherwise
C is protected, and base(C) = C.
| Operation | Rule |
|---|---|
init |
Writes the root protected commit: the current snapshot
(possibly empty), gate none, and
msg init. It sets the root worktree to
branch <protected>. |
branch x [--from rev] |
Sets x to a protected commit, the tip by
default. Branching from a non-protected commit is refused. |
commit |
Writes parent = head and
base = base(head), or the tip in
vc-tree/sync if that file exists. Under
locks/branch-<name> it CASes the ref from
head to the new commit, then removes
vc-tree/sync and vc-tree/conflicts. |
commit is refused when |
the branch is protected; the branch has a pending or active
queue entry; ref != head ("branch moved: run
vc sync"); or a path in
vc-tree/conflicts still has a marker line (§3). |
sync step 1 |
If ref != head, update the worktree to
merge3(head, ref, worktree) (a dirty worktree is
allowed) and set head = ref. Stop here if there are
conflicts; their paths go in vc-tree/conflicts. |
sync step 2 |
Requires a clean worktree. If base(head) != tip,
compute merge3(base(head), tip, head). Prepare and
validate a clean result as commit S with
parent = head, base = tip before
materializing it and CASing it onto the ref. Conflicts become
marker files, their paths in vc-tree/conflicts, plus
vc-tree/sync. |
| landing (§4) | Writes L with parent = tip,
source = A and
tree = merge3(base(A), tip, A). It then moves the
branch ref from A to L, so later work
merges against L. |
If both sync steps will produce a clean protected-tip merge, validate its commit metadata before applying the carry. A metadata rejection leaves the checkout and its local state unchanged.
Moving the branch to L after a landing is what
makes a later revert of a landed unit merge correctly. Commits
store no change list; item changes are always computed
(ADR-0161).
gate
tree <id>
key <toolchain-key>
origin queue|worktree
mode full|incremental <since-tree>
result pass|fail
time <RFC 3339>
command <gate command>
summary <last summary line>
NUL bytes in the selected process output line are recorded as
\0.
The toolchain key is the SHA-256 of these lines, in this order:
tenon <sha256 of current_exe>
cmd <gate command>
os <os>-<arch>
probe <command> <sha256 of stdout>
There is one probe line per config probe, in
config order. The queue trusts and indexes only records it made
itself (origin queue), from a fresh materialization
in vc-run/ with a scrubbed environment.
vc gate in a worktree writes an
origin worktree record, which is informational
only.
approval
branch <name>
commit <id>
owner <owner>
time <RFC 3339>
An approval is valid only if its commit is the
queued source. If config gives
admin <owner> uid=<n>, an approval by
that owner also requires the approvals file to be owned by uid
n. With agents running as a different OS user, that
makes admin approvals unforgeable. Otherwise approvals are
self-reported.
Revs
| Form | Meaning |
|---|---|
| full id | that commit |
| unique hex prefix, ≥ 8 characters | that commit |
| branch or tag name | its tip |
<rev>~<n> |
the n-th parent |
a..b |
the parent chain from b, stopping before
a |
3. Merge (ADR-0162)
merge3(base, ours, theirs) is a pure function over
three trees. It reads child objects through the
ObjectSource trait (types.rs) and never
runs the resolver.
Normalize. First, any side whose modules have
a different fmt version is rewritten as
split(fmt(join(m))) under the running version. A
reformat on the trunk therefore does not make open
branches conflict.
| Level | Rule |
|---|---|
| Paths | A change on one side only takes that side. The same change on
both sides takes either. Different changes on both sides recurse
if both are tree or both are mod;
otherwise they conflict. A delete on one side with an edit on the
other conflicts. |
| Units, by key | Items, impl heads, impl tails and methods each follow the same rules. Two different changes to one unit conflict. A method added or edited on one side while its impl was deleted on the other is a conflict on the impl key. |
| Order | Ours first. Each new unit from theirs goes after its nearest preceding unit in theirs that exists in ours, or first if there is none. Methods are ordered only within their own impl. Order is never a conflict. |
| Header | Import entries (path, name, alias) merge as a
three-way set: B + (O−B) + (T−B) − (B−O) − (B−T).
Lines are ordered as in ours, followed by theirs' new lines, and
the result is rendered with fmt (imports only). If
the header's comments changed on both sides, that conflicts. |
raw, blob |
Merged as whole files. |
| Renames | None. A rename is a delete plus an add. |
A conflicting file is written as raw, with markers
around each conflicting unit:
<<<<<<< ours <key>
…
||||||| base
…
=======
…
>>>>>>> theirs
A marker line starts with
<<<<<<< , |||||||
or >>>>>>> , or is exactly
=======. Only paths listed in
vc-tree/conflicts are checked, so other files may
contain such lines. A conflicted file counts as resolved when it
has no marker lines; it is stored as mod again if it
is fmt-clean and as raw otherwise. raw
files land like any other file: whether a .tn file
must be fmt-clean is the gate's policy. E1030 means "merge
conflict".
merge-file <base> <ours> <theirs>
runs split and merge3 on three versions of one file,
with no store. It writes the result to <ours>
and exits 0 when clean or 1 with markers, which is the contract of
a git merge driver (%O %A %B). It exists for the
M-VC.15 replay; using it as a merge driver in any git repository
is a separate decision.
4. Queue
land [--wait [--timeout s]].
Under locks/branch-<name>, land
requires ref == head, a clean worktree and no
existing entry for the branch. Then, under
locks/enqueue, it takes queue/next and
writes queue/pending/<seq>-<branch>. The
branch is frozen while its entry is pending or active.
--wait polls queue/done/ until the
timeout, which defaults to 3600 s. An invalid timeout is refused
before enqueue.
queue run [--once] holds
locks/runner. Enqueueing uses a separate lock, so
land never waits on the runner. For the lowest
pending seq:
Claim. Rename the entry to
queue/active/.Idempotency. If the protected history since
base(A)already holds a commit withsource A, skip to step 7.Approvals.
- Read OWNERS from the protected tip.
- The changed set is
diff2(tip, merged); it does not depend on any base the branch wrote. - Owned paths and units in that set need valid approvals. File/directory replacements include the replacement path and the added or removed descendants.
- Changes to
OWNERSor to anowned-gatepath also needadmin.
Merge. Compute
merge3(base(A), tip, A). Any conflict rejects the entry with E1030.Gate.
- If
gates/<merged>-<key>exists, reuse it. - Otherwise materialize the merged tree into
vc-run/<seq>/. - Run the config
gatethere, with onlyPATHandTENON_VC_AFFECTEDset (all, unless M-VC.12 is enabled). - Write the record and its index entry.
- A failure rejects the entry.
- If
Advance. Write
L, then CAS the protected ref from tip toL. If the CAS fails, go back to step 3.Finish.
- Under
locks/branch-<name>, CAS the branch ref fromAtoL. - Write
queue/done/. - Delete the active entry, which unfreezes the branch.
A rejection writes
doneand deletes the entry in the same way.- Under
Every full-every landings, the gate runs in full
mode. On startup, the runner first finishes any
active entry.
OWNERS sits at the tree root:
- Each line is
<owner>[,<owner>...] <pattern>. Owners come first; the pattern is free text running to the end of the line. - A pattern is a path glob (
*,**), optionally followed by#<key-glob>. - The last matching line wins.
- A line whose first non-space character is
#is a comment.
5. Locks and gc
Locks are files under locks/, held with
File::lock / File::lock_shared (Rust ≥
1.89; this repo pins 1.92.0 per ADR-0155). The OS releases a lock
when its process exits, so there are no stale locks, no PID files
and no unsafe.
| Lock | Mode | Held by |
|---|---|---|
branch-<name> |
exclusive | ref CAS on that branch |
protected |
exclusive | the protected ref |
enqueue |
exclusive | land |
runner |
exclusive | queue run |
gc |
shared | every object-writing command |
gc |
exclusive | gc |
gc marks from these roots:
- every branch and tag ref;
queue/pending/andqueue/active/;gates/;approvals/;worktree-gates/when present (informational receipts retain their snapshot objects).
It follows the tree, parent,
base and source edges, plus modules,
chunks and the records' retained ids. Both fsck and
gc require real root directories and regular root
records, then verify the expected object kind at every root and
traversed reference. Records sit directly under each root
directory, except approvals, which are grouped by branch. A
malformed physical root causes refusal before GC removes anything.
GC sweeps unmarked objects after successful validation. Its
exclusive lock excludes object writers.
branch -d <name> (refused while the branch is
queued) makes branch history collectable.
6. Config (store only)
protected main
gate tenon plugin check .
probe gcc --version
admin human:alice uid=501
owned-gate OWNERS
ignore target/**
full-every 20
gatehas no default. The queue refuses to run until it is set.probe,owned-gateandignoremay repeat; each other key appears once.- Unknown keys are rejected.
- Expected-output goldens are a gate input that agents can edit.
For autonomous agents, consider owning them, for example
admin tests/**/expected.out. This is a policy choice, not a default.
7. CLI
Every command accepts --json. Human output is one
line per unit change.
Release tags are opt-in; ordinary
tag <name> [rev] behavior is unchanged.
tenon vc tag --help describes both forms. For
example, tenon vc tag --release v1.2.0 [rev] defaults
rev to the worktree head and checks that the tag is
core semver, the commit is reachable from the configured protected
tip by following parent links, and the package manifest's version,
name, edition, dependencies and pack limits satisfy local release
policy. It creates the tag only after those checks pass. This does
not publish to a remote or provide quotas or authentication.
| Command | Purpose |
|---|---|
init |
Create the store and the root commit. |
status |
Changed paths and units, conflicts, sync and queue state. |
diff [path#key] |
Item-level diff; --rev a..b. |
commit -m <msg> |
Commit the worktree. |
log [-n N] [--item path#key] |
Commit history. |
show <rev> [path#key] |
|
tag <name> [rev] |
Create an ordinary immutable local tag. |
tag --release v<major>.<minor>.<patch> [rev] |
Opt into local release preflight, then create the immutable tag. |
branch [<name> [--from rev]] |
|
branch -d <name> |
|
switch <name> |
Refuses a dirty tree or foreign paths that block checkout. Stages new content before removing tracked paths. |
fork <name> <dir> |
Stage a protected commit in a new or empty directory, then publish its branch. Preserve the identity of an existing directory. |
sync |
|
land [--wait [--timeout s]] |
|
approve <branch> [--commit id] |
|
queue run [--once] |
|
gate |
|
affected [--since rev] [--mine] |
|
reformat |
|
merge-file <base> <ours> <theirs> |
Merge one file (§3); needs no store. |
gc |
|
fsck |
|
cat <id> |
Plumbing. |
Separately, tenon deps <file.tn> [--json]
prints graph nodes keyed path#key.
Fork reserves the destination during checkout and state publication. A returned preparation or publication error rolls back its owned entries so the name and destination can be retried. Foreign additions or replacements survive, and an error reports any incomplete rollback. Use stable destination ancestors and wait for fork to complete before using the checkout. The store and destination may reside on separate filesystems, with no atomic crash recovery across them.
Environment:
| Variable | Meaning |
|---|---|
TENON_VC_BY |
Provenance k=v pairs. |
TENON_VC_TIME |
Fixed time, for tests. |
TENON_VC_AFFECTED |
Set by the queue for the gate. |
TENON_VC_CRASH=<point> |
Crash at that point; honored only under
cfg(debug_assertions). |
Crash points: obj-tmp,
obj-rename, ref-locked,
ref-swap, enqueue,
queue-claim, queue-gated,
queue-advance, queue-branch,
index-write.
Object publication syncs new directory entries, object data, and the directories changed by rename before a durable ref can depend on them. Atomic metadata writes also sync newly created ancestors. Crash hooks exercise process-exit recovery. Directory operation-order tests cover the sync protocol separately from hardware power-loss testing.
Checkout excludes competing VC worktree writers. It checks blocking entries and stages file data before removing tracked paths. New destinations use exclusive publication. Concurrent external changes to tracked paths during checkout are outside the worktree ownership contract.
8. Diagnostics (E1000–E1049)
Each task registers codes only in its own range.
| Range | Task | Area |
|---|---|---|
| E1000–E1009 | VC.1 | store, refs, locks, fsck, config |
| E1010–E1014 | VC.2 | split |
| E1015–E1019 | VC.3 | deps |
| E1020–E1024 | VC.5 | worktree, paths, history, refused commits |
| E1025–E1029 | VC.7 | branches, fork |
| E1030–E1032 | VC.4 | merge (E1030 is merge conflict) |
| E1033–E1034 | VC.8 | sync |
| E1035–E1037 | VC.6 | gate |
| E1038–E1042 | VC.9 | queue, approvals, OWNERS |
| E1043–E1044 | VC.10 | affected |
| E1045–E1046 | VC.11 | gc |
| E1047–E1048 | VC.13 | agent integration |
| E1049 | VC.15 | merge-file input errors (conflicts are
E1030) |
VC.12 adds no codes.
9. Local workflow and implementation policy
Initialize from the current files with
tenon vc init. An invalid snapshot is rejected before
the store is created, so initialization can be retried after
fixing the input. Only one concurrent initializer can claim the
store. Set the store-local .tenon/vc/config gate to
the project validation command before running a queue; there is
intentionally no default passing gate. Create a task workspace
with tenon vc fork task-name ../task-name, edit
there, and run tenon vc commit -m "message". Run
tenon vc queue run in the original workspace and
submit with tenon vc land --wait --timeout 120 in the
task workspace. A successful landing moves its branch ref; run
tenon vc sync before subsequent work.
vc branch -d validates the branch namespace before
deleting a ref and coordinates with garbage collection.
vc approve takes the approver from
TENON_VC_BY agent=<owner>. Every owner listed
by the last matching OWNERS rule is required. The configured admin
also approves OWNERS and owned-gate changes. A raw replacement
retains the ownership requirements of the structured units it
removes.
Probes run in the same fresh candidate directory and scrubbed
environment as the gate, after protected-tree ownership checks.
Configure OWNERS/owned-gate for scripts and other inputs that
determine validation policy. Informational vc gate
receipts live under worktree-gates/; they never enter
the trusted queue index.
The shared store and sanctioned CLI provide coordination and policy enforcement, not OS isolation against a process with arbitrary write access to the store. Such a process could directly replace configuration, refs, objects or gate indices. Distinct admin uid checks protect approval ownership as specified above; signed provenance and a broader security review remain later milestones.
The stat index is advisory: current snapshots conservatively
rehash every file, so timestamp races cannot hide edits. Branch
refs are constant-size metadata; materialization uses plain
copies. Full gates remain enabled until the measured throughput
decision justifies another strategy. The full-every
policy therefore holds on every landing in this
implementation.
--json wraps each command result in an
output or error string; the continuous
runner emits one JSON object per terminal queue receipt. Paths and
selectors inside those strings follow the human item-change
format. The runner and land --wait require a regular,
newline-terminated receipt with
landed <commit-id> or
rejected E####: <reason>. A landed receipt must
resolve to a landing commit for the submitted source. The runner
retains the active entry for recovery when it cannot validate the
receipt.
10. Structured workspace host integration
workspace_backend = "vc" is an explicit
agent-platform policy. The trusted host sets absolute
TENON_VC_BIN; native calls pin the executable, original store and
branch, and use direct argv in a child-only directory context. No
auto-land or implicit repository initialization occurs. Ws.fork
starts at protected history; Ws.commit checkpoints its exact
branch, preserving unknown provenance fields.
vc --directory <worktree> <command>
selects a directory only in that CLI child. The advanced
--state-directory <protected-state> option
binds private command state for status, commit, sync and fork.
Native hosts keep this state outside the tool-writable worktree so
public metadata races cannot redirect authority. Normal CLI
workflows continue to use .tenon/vc-tree.
The workspace_run module owns explicit Root/Child leases, finish/cancel/detach and actual journal-derived token attribution. Dirty or unverifiable vc work survives exit/stale sweep with protected recovery state; successful branch history survives workspace release. See agent workspaces and ADR-0169.
11. tvc-wire 1
ADR-0204
and the remote plan define the control documents,
exchange framing and admission. tvc-wire 1 uses the
existing tvc 1 object bytes and hashes. JSON controls
require v: 1 and reject missing, duplicate or unknown
fields. Wire identifiers are full lowercase hexadecimal SHA-256
IDs. An empty expected or receipt old
denotes an absent branch. An empty next marks the end
of a ref listing.
Tracking files begin with tvc-refs 1. They end
with LF and contain the repository ID, canonical unsigned decimal
generation, protected branch and uniquely sorted namespace/name
ref records. Generation is transported as text. Control documents
are at most 64 KiB, ref pages contain at most 128 entries, and
upload fragments encode at most 256 KiB as lowercase ASCII hex.
Fragment documents use the 1 MiB HTTP body limit. Each encoded
object is at most 16 MiB, and one closure contains at most 128 MiB
of encoded objects.
A raw page uses the following byte grammar. All shown line endings are LF.
tvc-pack 1\n
count <decimal>\n
<object-id> <encoded-object-length>\n
<exact encoded object bytes>
... repeat the object record exactly count times ...
end <sha256-of-all-bytes-before-the-end-line>\n
An object record ends at its declared length, with no appended
separator. Decimal fields use ASCII digits without leading zeroes.
Pages have at most 1,024 objects, 128 bytes per header line
excluding LF, and 1 MiB total. Object IDs are strictly increasing
across pages and describe the exact bytes in each record. The
receiver verifies the footer and checks every page against its
pinned entry IDs and lengths. For an object that exceeds a page,
Forge answers the pack-page request with HTTP 200, content type
application/vnd.tenon.vc.object-slice, and the ASCII
body
<64-hex-object-id> <encoded-object-length>
with no final LF. The client then downloads contiguous raw slices
from
/transfers/<id>/objects/<object>?offset=N&length=N.
Assembly pins the object ID and encoded total, accepts at most
4,096 slices from 1 byte through 256 KiB, and checks the complete
hash and object envelope before returning bytes. A retry's session
handling owns deduplication.
The closure validator reads only explicitly supplied typed roots and their object references. It checks each object's hash, envelope, expected kind, module layout, and any UTF-8 chunk referenced by a module. It counts each ID once for the 100,000-node and transfer-byte bounds and checks every path for the 256-node depth bound, counting its root as depth one. The object source supplies read-only encoded bytes by ID and must bound individual reads before returning bytes. A tree or module has at most 100,000 LF-delimited records before parsing. Admission and reuse of an existing local closure require verification against pinned bytes and separate repository authority checks.
Remote diagnostic codes describe framing, size and closure failures.