navid/veins / commit

d33fc3bf5a88

Navid M <navidmomtahen@gmail.com> · 2026-11-26

parents: 8557ab995058

Browse files at this commit · Download source

all: networking features, vn serve, vn key, vn access, vn whoami and vn clone
--- a/veins/build-native.sh+++ b/veins/build-native.sh@@ -24,6 +24,7 @@ esac  "$cc" -O3 -c "$crypto/blake3_c.c" -o "$out/blake3_c.o"+"$cc" -O3 -c "$crypto/openssl_c.c" -o "$out/openssl_c.o" "$cc" -O3 -c "$b3/blake3.c" -o "$out/blake3_impl.o" "$cc" -O3 -c "$b3/blake3_dispatch.c" -o "$out/blake3_dispatch.o" "$cc" -O3 -c "$b3/blake3_portable.c" -o "$out/blake3_portable.o"@@ -34,6 +35,19 @@     $out/blake3_dispatch.o     $out/blake3_portable.o "++# Link the OpenSSL static libraries into the native object so that the final+# link does not depend on library ordering.+ssl_a=$("$cc" -print-file-name=libssl.a)+crypto_a=$("$cc" -print-file-name=libcrypto.a)+if [ -f "$ssl_a" ] && [ -f "$crypto_a" ]; then+    "$cc" -r "$out/openssl_c.o" -Wl,--whole-archive "$ssl_a" "$crypto_a" \+        -Wl,--no-whole-archive -o "$out/openssl_embed.o"+    objects="$objects $out/openssl_embed.o"+else+    echo "build-native.sh: OpenSSL static libraries not found; TLS will fail to link" >&2+    objects="$objects $out/openssl_c.o"+fi  case "$arch" in     arm64)--- /dev/null+++ b/veins/src/auth/access.sx@@ -0,0 +1,356 @@+/// Server-side `.veins/access` policy parsing and management.++val str    = use("std/string")+val bytes  = use("../core/bytes.sx")+val buf    = use("../core/buf.sx")+val lists  = use("../core/lists.sx")+val files  = use("../io/files.sx")+val layout = use("../store/layout.sx")+val ed     = use("../crypto/ed25519.sx")+val tls    = use("../crypto/tls.sx")++pub val ROLE_ANONYMOUS: u8 = 0+pub val ROLE_READ: u8 = 1+pub val ROLE_WRITE: u8 = 2++pub type AccessEntry = {+    public_key: mut bytes.Bytes+    name: mut bytes.Bytes+    role: mut u64+}++pub type Access = {+    valid: mut bool+    error_line: mut i64+    anonymous_read: mut bool+    entries: mut list[ref AccessEntry]+}++fn trim(b: bytes.Bytes) bytes.Bytes = trust {+    val start: mut usize = 0+    val end: mut usize = b.len+    for start < end {+        val c: u8 = bytes.Bytes.at(b, start)+        if c != 32 && c != 9 && c != 13 && c != 10 {+            break+        }+        start+++    }+    for end > start {+        val c2: u8 = bytes.Bytes.at(b, end - 1)+        if c2 != 32 && c2 != 9 && c2 != 13 && c2 != 10 {+            break+        }+        end--+    }+    return bytes.Bytes.slice(b, start, end)+}++fn tokenize(line: bytes.Bytes) list[bytes.Bytes] = trust {+    val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    val start: mut usize = 0+    val i: mut usize = 0+    for i <= line.len {+        val at_end: bool = i == line.len+        if at_end || bytes.Bytes.at(line, i) == 32 || bytes.Bytes.at(line, i) == 9 {+            if i > start {+                @append(out, bytes.Bytes.slice(line, start, i))+            }+            start = i + 1+        }+        i+++    }+    return out+}++fn token(toks: list[bytes.Bytes], i: usize) bytes.Bytes = trust {+    val o = @get(toks, i)+    if o is some v {+        return v+    }+    return bytes.empty()+}++pub fn path(repo: layout.Repo) str.StringView = {+    return files.join(layout.veins_dir(repo), str.from_cstr(c"access"))+}++fn free_entries(es: list[ref AccessEntry]) void = trust {+    for e in es {+        if e.public_key.ptr != none {+            bytes.free_ptr(e.public_key.ptr)+        }+        if e.name.ptr != none && e.name.ptr != e.public_key.ptr {+            bytes.free_ptr(e.name.ptr)+        }+        val ep: mut ref void = e as ref void+        @free(ep)+    }+    @listfree(es)+}++pub fn empty() Access = {+    return Access{+        valid: true,+        error_line: 0,+        anonymous_read: false,+        entries: lists.new[ref AccessEntry]()+    }+}++fn invalid(line: i64) Access = {+    return Access{+        valid: false,+        error_line: line,+        anonymous_read: false,+        entries: lists.new[ref AccessEntry]()+    }+}++pub fn free(a: Access) void = trust {+    free_entries(a.entries)+}++fn find(es: list[ref AccessEntry], public_key: bytes.Bytes) option[usize] = trust {+    val i: mut usize = 0+    for i < @len(es) {+        val o = @get(es, i)+        if o is some e {+            if bytes.Bytes.eql(e.public_key, public_key) {+                return some i+            }+        }+        i+++    }+    return none+}++fn parse(text: bytes.Bytes) Access = trust {+    val acc: mut Access = empty()+    val start: mut usize = 0+    val line_no: mut i64 = 0+    val i: mut usize = 0+    for i <= text.len {+        if i == text.len || bytes.Bytes.at(text, i) == 10 {+            line_no+++            val line: bytes.Bytes = trim(bytes.Bytes.slice(text, start, i))+            if line.len > 0 && bytes.Bytes.at(line, 0) != 35 {+                val toks: list[bytes.Bytes] = tokenize(line)+                val nt: usize = @len(toks)+                val bad: mut bool = false+                if nt == 2 && bytes.Bytes.eql(token(toks, 0), bytes.bytes(c"anonymous", 9)) {+                    if bytes.Bytes.eql(token(toks, 1), bytes.bytes(c"read", 4)) {+                        acc.anonymous_read = true+                    } else {+                        bad = true+                    }+                } elif nt >= 3 && bytes.Bytes.eql(token(toks, 0), bytes.bytes(c"allow", 5)) {+                    val role_t: bytes.Bytes = token(toks, 1)+                    val role: mut u8 = 0+                    if bytes.Bytes.eql(role_t, bytes.bytes(c"read", 4)) {+                        role = ROLE_READ+                    } elif bytes.Bytes.eql(role_t, bytes.bytes(c"write", 5)) {+                        role = ROLE_WRITE+                    } else {+                        bad = true+                    }+                    val pub_opt = ed.parse_public(token(toks, 2))+                    val public_key: mut bytes.Bytes = bytes.empty()+                    match pub_opt {+                        some p => {+                            public_key = p+                        }+                        none => {+                            bad = true+                        }+                    }+                    if !bad {+                        if find(acc.entries, public_key) is some _ {+                            bad = true+                        } else {+                            val e: mut ref AccessEntry = @alloc(@sizeof(AccessEntry)) as ref AccessEntry+                            e.role = role as u64+                            e.public_key = public_key+                            e.name = bytes.empty()+                            if nt >= 4 {+                                e.name = bytes.Bytes.dup(token(toks, 3))+                            }+                            @append(acc.entries, e)+                            public_key = bytes.empty()+                        }+                    }+                    if public_key.ptr != none {+                        bytes.free_owned(public_key)+                    }+                } else {+                    bad = true+                }+                @listfree(toks)+                if bad {+                    free(acc)+                    return invalid(line_no)+                }+            }+            start = i + 1+        }+        i+++    }+    return acc+}++pub fn load(repo: layout.Repo) Access = trust {+    val p: str.StringView = path(repo)+    val z: ref u8 = bytes.Bytes.to_cstr(bytes.bytes(p.ptr, p.len))+    val mode: i32 = tls.file_mode(z)+    if mode >= 0 && (mode & 18) != 0 {+        files.free_path(p)+        @free(z as ref void)+        return invalid(0)+    }+    val data_opt = files.read_all(p)+    files.free_path(p)+    @free(z as ref void)+    val data: mut bytes.Bytes = bytes.empty()+    match data_opt {+        some d => {+            data = d+        }+        none => {+            return empty()+        }+    }+    val acc: Access = parse(data)+    files.free_buffer(data)+    return acc+}++/// The role granted to `pub`, or 0 for anonymous, or 255 when unknown.+pub fn role_for(a: Access, public_key: bytes.Bytes) u8 = trust {+    if public_key.ptr == none {+        if a.anonymous_read {+            return ROLE_READ+        }+        return ROLE_ANONYMOUS+    }+    val idx = find(a.entries, public_key)+    if idx is some i {+        val o = @get(a.entries, i)+        if o is some e {+            return e.role as u8+        }+    }+    return 255+}++pub fn write(repo: layout.Repo, a: Access) bool = trust {+    val b: mut buf.Buf = buf.new(128)+    buf.Buf.put_raw(b, c"# veins access policy\n" as ref u8, 22)+    if a.anonymous_read {+        buf.Buf.put_raw(b, c"anonymous read\n" as ref u8, 15)+    }+    for e in a.entries {+        val nm: bytes.Bytes = e.name+        if nm.len > 64 || e.public_key.len != 32 {+            buf.Buf.free(b)+            return false+        }+        buf.Buf.put_raw(b, c"allow " as ref u8, 6)+        if e.role == (ROLE_WRITE as u64) {+            buf.Buf.put_raw(b, c"write" as ref u8, 5)+        } else {+            buf.Buf.put_raw(b, c"read" as ref u8, 4)+        }+        buf.Buf.put_u8(b, 32)+        val pub_enc: bytes.Bytes = ed.format_public(e.public_key)+        buf.Buf.put_bytes(b, pub_enc)+        bytes.free_owned(pub_enc)+        if nm.len > 0 {+            buf.Buf.put_u8(b, 32)+            buf.Buf.put_bytes(b, nm)+        }+        buf.Buf.put_u8(b, 10)+    }+    val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+    buf.Buf.free(b)+    val p: str.StringView = path(repo)+    val passed: bool = files.write_all(p, out)+    val z: ref u8 = bytes.Bytes.to_cstr(bytes.bytes(p.ptr, p.len))+    val mode_rc: i32 = tls.chmod(z, 384)+    bytes.free_ptr(z)+    files.free_path(p)+    bytes.free_owned(out)+    if mode_rc < 0 {+    }+    return passed+}++pub fn add(repo: layout.Repo, role: u8, public_key: bytes.Bytes, name: bytes.Bytes) bool = trust {+    val mut_acc: mut Access = load(repo)+    if !mut_acc.valid {+        free(mut_acc)+        return false+    }+    if find(mut_acc.entries, public_key) is some _ {+        free(mut_acc)+        return false+    }+    val e: mut ref AccessEntry = @alloc(@sizeof(AccessEntry)) as ref AccessEntry+    e.role = role as u64+    e.public_key = bytes.Bytes.dup(public_key)+    e.name = bytes.Bytes.dup(name)+    @append(mut_acc.entries, e)+    val passed: bool = write(repo, mut_acc)+    free(mut_acc)+    return passed+}++pub fn remove(repo: layout.Repo, fingerprint: bytes.Bytes, name: bytes.Bytes) bool = trust {+    val mut_acc: mut Access = load(repo)+    if !mut_acc.valid {+        free(mut_acc)+        return false+    }+    val kept: mut list[ref AccessEntry] = lists.new[ref AccessEntry]()+    val removed: mut bool = false+    for e in mut_acc.entries {+        val match_fp: mut bool = false+        if fingerprint.len > 0 {+            val fp_opt = ed.fingerprint(e.public_key)+            if fp_opt is some fp {+                match_fp = bytes.Bytes.eql(fp, fingerprint)+                bytes.free_owned(fp)+            }+        }+        val match_name: bool = name.len > 0 && bytes.Bytes.eql(e.name, name)+        if match_fp || match_name {+            removed = true+            if e.public_key.ptr != none {+                bytes.free_ptr(e.public_key.ptr)+            }+            if e.name.ptr != none {+                bytes.free_ptr(e.name.ptr)+            }+            val ep2: mut ref void = e as ref void+            @free(ep2)+        } else {+            @append(kept, e)+        }+    }+    @listfree(mut_acc.entries)+    mut_acc.entries = kept+    val passed: bool = removed && write(repo, mut_acc)+    free(mut_acc)+    return passed+}++pub fn set_anonymous(repo: layout.Repo, on: bool) bool = trust {+    val mut_acc: mut Access = load(repo)+    if !mut_acc.valid {+        free(mut_acc)+        return false+    }+    mut_acc.anonymous_read = on+    val passed: bool = write(repo, mut_acc)+    free(mut_acc)+    return passed+}--- /dev/null+++ b/veins/src/auth/handshake.sx@@ -0,0 +1,35 @@+/// Shared handshake message construction and role checks.++val bytes = use("../core/bytes.sx")+val buf   = use("../core/buf.sx")++pub fn auth_message(+    version: u16,+    repo: bytes.Bytes,+    server_nonce: bytes.Bytes,+    client_nonce: bytes.Bytes,+    binding: bytes.Bytes+) bytes.Bytes = trust {+    val b: mut buf.Buf = buf.new(128)+    buf.Buf.put_raw(b, c"veins-auth/1" as ref u8, 12)+    buf.Buf.put_u8(b, 0)+    buf.Buf.put_u8(b, ((version >> 8) & 255) as u8)+    buf.Buf.put_u8(b, (version & 255) as u8)+    buf.Buf.put_length_prefixed(b, repo)+    buf.Buf.put_bytes(b, server_nonce)+    buf.Buf.put_bytes(b, client_nonce)+    buf.Buf.put_bytes(b, binding)+    val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+    buf.Buf.free(b)+    return out+}++pub fn role_name(role: u8) bytes.Bytes = {+    if role == 2 {+        return bytes.bytes(c"write", 5)+    }+    if role == 1 {+        return bytes.bytes(c"read", 4)+    }+    return bytes.bytes(c"anonymous", 9)+}--- /dev/null+++ b/veins/src/auth/keys.sx@@ -0,0 +1,259 @@+/// Client-side Ed25519 key storage.++val str    = use("std/string")+val os     = use("std/os")+val bytes  = use("../core/bytes.sx")+val lists  = use("../core/lists.sx")+val files  = use("../io/files.sx")+val ed     = use("../crypto/ed25519.sx")+val tls    = use("../crypto/tls.sx")+val random = use("std/crypto/random")++pub type Key = {+    name: mut bytes.Bytes+    seed: mut bytes.Bytes+    public_key: mut bytes.Bytes+    fingerprint: mut bytes.Bytes+}++fn env_dup(name: ref u8) option[bytes.Bytes] = trust {+    val v = os.env(name)+    match v {+        some s => {+            return some bytes.Bytes.dup(bytes.from_cstr(s))+        }+        none => {+            return none+        }+    }+}++pub fn key_dir() bytes.Bytes = trust {+    val xdg = env_dup(c"XDG_CONFIG_HOME")+    if xdg is some base {+        val out: str.StringView = files.join(+            files.to_view(base),+            str.from_cstr(c"veins/keys")+        )+        files.free_buffer(base)+        return bytes.bytes(out.ptr, out.len)+    }+    val home = env_dup(c"HOME")+    if home is some h {+        val out2: str.StringView = files.join(+            files.to_view(h),+            str.from_cstr(c".config/veins/keys")+        )+        files.free_buffer(h)+        return bytes.bytes(out2.ptr, out2.len)+    }+    return bytes.Bytes.dup(bytes.bytes(c".veins-keys", 11))+}++pub fn key_path(name: bytes.Bytes) bytes.Bytes = trust {+    val dir: bytes.Bytes = key_dir()+    val fname: ref u8 = @alloc(name.len + 5) as ref u8+    @memcpy(fname as ref void, name.ptr as ref void, name.len)+    @memcpy(@ptradd(fname, name.len as i64) as ref void, c".key" as ref void, 4)+    @store8(@ptradd(fname, (name.len + 4) as i64), 0)+    val joined: str.StringView = files.join(+        files.to_view(dir),+        str.view(fname, (name.len + 4) as i64)+    )+    bytes.free_owned(dir)+    @free(fname as ref void)+    return bytes.bytes(joined.ptr, joined.len)+}++fn mkdirs(path: bytes.Bytes) bool = trust {+    if files.exists_dir(files.to_view(path)) {+        return true+    }+    val i: mut usize = 1+    for i < path.len {+        if bytes.Bytes.at(path, i) == 47 {+            val part: str.StringView = str.view(path.ptr, i as i64)+            files.mkdir_all(part)+        }+        i+++    }+    return files.mkdir_all(files.to_view(path))+}++fn valid_name(name: bytes.Bytes) bool = trust {+    if name.len == 0 || name.len > 128 {+        return false+    }+    val i: mut usize = 0+    for i < name.len {+        val c: u8 = bytes.Bytes.at(name, i)+        if c == 47 || c == 92 || c == 0 {+            return false+        }+        i+++    }+    return true+}++pub fn load(name: bytes.Bytes) option[Key] = trust {+    val p: bytes.Bytes = key_path(name)+    val z: ref u8 = bytes.Bytes.to_cstr(p)+    val mode: i32 = tls.file_mode(z)+    if mode < 0 || (mode & 63) != 0 {+        bytes.free_owned(p)+        @free(z as ref void)+        return none+    }+    val data_opt = files.read_all(files.to_view(p))+    bytes.free_owned(p)+    @free(z as ref void)+    val data: mut bytes.Bytes = bytes.empty()+    match data_opt {+        some d => {+            data = d+        }+        none => {+            return none+        }+    }+    if data.len != 33 || bytes.Bytes.at(data, 0) != 1 {+        files.free_buffer(data)+        return none+    }+    val seed: bytes.Bytes = bytes.Bytes.dup(bytes.Bytes.slice(data, 1, 33))+    files.free_buffer(data)+    val pub_opt = ed.public_from_seed(seed)+    val public_key: mut bytes.Bytes = bytes.empty()+    match pub_opt {+        some v => {+            public_key = v+        }+        none => {+            bytes.free_owned(seed)+            return none+        }+    }+    val fp_opt = ed.fingerprint(public_key)+    val fp: mut bytes.Bytes = bytes.empty()+    match fp_opt {+        some v => {+            fp = v+        }+        none => {+            bytes.free_owned(seed)+            bytes.free_owned(public_key)+            return none+        }+    }+    return some Key{+        name: bytes.Bytes.dup(name),+        seed: seed,+        public_key: public_key,+        fingerprint: fp+    }+}++pub fn free_key(k: Key) void = trust {+    if k.name.ptr != none {+        bytes.free_ptr(k.name.ptr)+    }+    if k.seed.ptr != none {+        bytes.free_ptr(k.seed.ptr)+    }+    if k.public_key.ptr != none {+        bytes.free_ptr(k.public_key.ptr)+    }+    if k.fingerprint.ptr != none {+        bytes.free_ptr(k.fingerprint.ptr)+    }+}++pub fn generate(name: bytes.Bytes) option[Key] = trust {+    if !valid_name(name) {+        return none+    }+    val dir: bytes.Bytes = key_dir()+    if !mkdirs(dir) {+        bytes.free_owned(dir)+        return none+    }+    val zdir: ref u8 = bytes.Bytes.to_cstr(dir)+    tls.chmod(zdir, 448)+    @free(zdir as ref void)+    bytes.free_owned(dir)+    val seed: ref u8 = @alloc(32) as ref u8+    random.random_bytes(seed as ref void, 32)+    val seed_b: bytes.Bytes = bytes.bytes(seed, 32)+    val pub_opt = ed.public_from_seed(seed_b)+    val public_key: mut bytes.Bytes = bytes.empty()+    match pub_opt {+        some v => {+            public_key = v+        }+        none => {+            @free(seed as ref void)+            return none+        }+    }+    val fp_opt = ed.fingerprint(public_key)+    val fp: mut bytes.Bytes = bytes.empty()+    match fp_opt {+        some v => {+            fp = v+        }+        none => {+            @free(seed as ref void)+            bytes.free_owned(public_key)+            return none+        }+    }+    val p: bytes.Bytes = key_path(name)+    val body: ref u8 = @alloc(33) as ref u8+    @store8(body, 1)+    @memcpy(@ptradd(body, 1) as ref void, seed as ref void, 32)+    val wrote: bool = files.write_all(files.to_view(p), bytes.bytes(body, 33))+    @free(body as ref void)+    val z: ref u8 = bytes.Bytes.to_cstr(p)+    tls.chmod(z, 384)+    @free(z as ref void)+    bytes.free_owned(p)+    if !wrote {+        @free(seed as ref void)+        bytes.free_owned(public_key)+        bytes.free_owned(fp)+        return none+    }+    return some Key{+        name: bytes.Bytes.dup(name),+        seed: seed_b,+        public_key: public_key,+        fingerprint: fp+    }+}++pub fn list_names() list[bytes.Bytes] = trust {+    val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    val dir: bytes.Bytes = key_dir()+    val dview: str.StringView = files.to_view(dir)+    if files.exists_dir(dview) {+        val names: list[ref u8] = files.list_dir(dview)+        for n in names {+            val len: i64 = @strlen(n)+            if len > 4 && files.name_ends_with(n, c".key") {+                @append(out, bytes.Bytes.dup(bytes.bytes(n, (len - 4) as usize)))+            }+        }+        files.free_names(names)+    }+    bytes.free_owned(dir)+    return out+}++pub fn free_names(names: list[bytes.Bytes]) void = trust {+    for n in names {+        if n.ptr != none {+            bytes.free_owned(n)+        }+    }+    @listfree(names)+}--- /dev/null+++ b/veins/src/cli/access_cmd.sx@@ -0,0 +1,240 @@+/// `vn access`: manage a served repository's access file.++val stdio  = use("std/stdio")+val str    = use("std/string")+val bytes  = use("../core/bytes.sx")+val files  = use("../io/files.sx")+val layout = use("../store/layout.sx")+val access = use("../auth/access.sx")+val ed     = use("../crypto/ed25519.sx")+val cmsg   = use("../core/msg.sx")++fn trim_text(b: bytes.Bytes) bytes.Bytes = trust {+    val start: mut usize = 0+    val end: mut usize = b.len+    for start < end {+        val c: u8 = bytes.Bytes.at(b, start)+        if c != 32 && c != 9 && c != 10 && c != 13 {+            break+        }+        start+++    }+    for end > start {+        val c2: u8 = bytes.Bytes.at(b, end - 1)+        if c2 != 32 && c2 != 9 && c2 != 10 && c2 != 13 {+            break+        }+        end--+    }+    return bytes.Bytes.slice(b, start, end)+}++fn read_public(arg: bytes.Bytes) option[bytes.Bytes] = trust {+    if bytes.Bytes.starts_with(arg, bytes.bytes(c"ed25519:", 8)) {+        return ed.parse_public(arg)+    }+    val p: str.StringView = files.to_view(arg)+    val data_opt = files.read_all(p)+    if data_opt is some d {+        val t: bytes.Bytes = trim_text(d)+        val parsed = ed.parse_public(t)+        if parsed is some v {+            files.free_buffer(d)+            return some v+        }+        files.free_buffer(d)+    }+    return none+}++pub fn run(args: list[ref u8], start: usize) i32 = trust {+    val sub_opt = @get(args, start)+    val sub: mut ref u8 = none+    match sub_opt {+        some s => {+            sub = s+        }+        none => {+            cmsg.error_prefix()+            stdio.eprint("expected access subcommand\n", {})+            return 1+        }+    }+    val path: str.StringView = str.from_cstr(c".")+    val repo_opt = layout.discover(path)+    val repo: mut layout.Repo = layout.Repo{root: bytes.empty()}+    match repo_opt {+        some r => {+            repo = r+        }+        none => {+            cmsg.error_prefix()+            stdio.eprint("not a veins repository\n", {})+            return 1+        }+    }+    if @strcmp(sub, c"add") == 0 {+        val role: mut bytes.Bytes = bytes.empty()+        val key_arg: mut bytes.Bytes = bytes.empty()+        val name: mut bytes.Bytes = bytes.empty()+        val i: mut usize = start + 1+        for i < @len(args) {+            val o = @get(args, i)+            if o is some a {+                val av: bytes.Bytes = bytes.from_cstr(a)+                if bytes.Bytes.eql(av, bytes.bytes(c"-role", 5)) && i + 1 < @len(args) {+                    val v = @get(args, i + 1)+                    if v is some rv {+                        role = bytes.from_cstr(rv)+                        i+++                    }+                } elif bytes.Bytes.eql(av, bytes.bytes(c"-key", 4)) && i + 1 < @len(args) {+                    val v = @get(args, i + 1)+                    if v is some rv {+                        key_arg = bytes.from_cstr(rv)+                        i+++                    }+                } elif bytes.Bytes.eql(av, bytes.bytes(c"-name", 5)) && i + 1 < @len(args) {+                    val v = @get(args, i + 1)+                    if v is some rv {+                        name = bytes.from_cstr(rv)+                        i+++                    }+                } else {+                    cmsg.error_prefix()+                    stdio.eprint("unknown access add option: {s}\n", {str.from_cstr(a)})+                    layout.free_repo(repo)+                    return 1+                }+            }+            i+++        }+        if role.ptr == none || key_arg.ptr == none {+            cmsg.error_prefix()+            stdio.eprint("access add requires -role and -key\n", {})+            layout.free_repo(repo)+            return 1+        }+        val role_code: mut u8 = access.ROLE_READ+        if bytes.Bytes.eql(role, bytes.bytes(c"write", 5)) {+            role_code = access.ROLE_WRITE+        } elif !bytes.Bytes.eql(role, bytes.bytes(c"read", 4)) {+            cmsg.error_prefix()+            stdio.eprint("role must be read or write\n", {})+            layout.free_repo(repo)+            return 1+        }+        val pub_opt = read_public(key_arg)+        if pub_opt is none {+            cmsg.error_prefix()+            stdio.eprint("invalid public key\n", {})+            layout.free_repo(repo)+            return 1+        }+        val public_key: mut bytes.Bytes = bytes.empty()+        if pub_opt is some pk {+            public_key = pk+        } else {+            cmsg.error_prefix()+            stdio.eprint("invalid public key\n", {})+            layout.free_repo(repo)+            return 1+        }+        val passed: bool = access.add(repo, role_code, public_key, name)+        bytes.free_owned(public_key)+        layout.free_repo(repo)+        if !passed {+            cmsg.error_prefix()+            stdio.eprint("cannot add key\n", {})+            return 1+        }+        cmsg.info_prefix()+        stdio.print("access granted\n", {})+        return 0+    }+    if @strcmp(sub, c"list") == 0 {+        val a: access.Access = access.load(repo)+        layout.free_repo(repo)+        if !a.valid {+            cmsg.error_prefix()+            stdio.eprint("invalid access file at line {d}\n", {a.error_line})+            access.free(a)+            return 1+        }+        if a.anonymous_read {+            stdio.print("anonymous: read\n", {})+        } else {+            stdio.print("anonymous: off\n", {})+        }+        for e in a.entries {+            val fp_opt = ed.fingerprint(e.public_key)+            val role: mut bytes.Bytes = bytes.bytes(c"read", 4)+            if e.role == (access.ROLE_WRITE as u64) {+                role = bytes.bytes(c"write", 5)+            }+            if fp_opt is some fp {+                stdio.print(+                    "{s} {s} {s}\n",+                    {+                        str.view(role.ptr, role.len as i64),+                        str.view(fp.ptr, fp.len as i64),+                        str.view(e.name.ptr, e.name.len as i64)+                    }+                )+                bytes.free_owned(fp)+            }+        }+        access.free(a)+        return 0+    }+    if @strcmp(sub, c"remove") == 0 {+        val arg_opt = @get(args, start + 1)+        val arg: mut bytes.Bytes = bytes.empty()+        if arg_opt is some a {+            arg = bytes.from_cstr(a)+        } else {+            cmsg.error_prefix()+            stdio.eprint("access remove requires a fingerprint or name\n", {})+            layout.free_repo(repo)+            return 1+        }+        val is_fp: bool = arg.len == 26+        val fp: mut bytes.Bytes = bytes.empty()+        val nm: mut bytes.Bytes = bytes.empty()+        if is_fp {+            fp = arg+        } else {+            nm = arg+        }+        val passed: bool = access.remove(repo, fp, nm)+        layout.free_repo(repo)+        if !passed {+            cmsg.error_prefix()+            stdio.eprint("key not found or cannot write access file\n", {})+            return 1+        }+        cmsg.info_prefix()+        stdio.print("access removed\n", {})+        return 0+    }+    if @strcmp(sub, c"anonymous") == 0 {+        val arg_opt = @get(args, start + 1)+        val on: mut bool = false+        if arg_opt is some a {+            val v: bytes.Bytes = bytes.from_cstr(a)+            on = bytes.Bytes.eql(v, bytes.bytes(c"on", 2))+        }+        val passed: bool = access.set_anonymous(repo, on)+        layout.free_repo(repo)+        if !passed {+            cmsg.error_prefix()+            stdio.eprint("cannot update access file\n", {})+            return 1+        }+        return 0+    }+    layout.free_repo(repo)+    cmsg.error_prefix()+    stdio.eprint("unknown access subcommand: {s}\n", {str.from_cstr(sub)})+    return 1+}--- /dev/null+++ b/veins/src/cli/clone_cmd.sx@@ -0,0 +1,242 @@+/// `vn clone`: fetch a repository over the native protocol.++val stdio   = use("std/stdio")+val str     = use("std/string")+val bytes   = use("../core/bytes.sx")+val lists   = use("../core/lists.sx")+val objid   = use("../object/id.sx")+val store   = use("../store/store.sx")+val layout  = use("../store/layout.sx")+val files   = use("../io/files.sx")+val config  = use("../core/repoconfig.sx")+val remote_config = use("../git/remote.sx")+val client  = use("../protocol/client.sx")+val msg_refs = use("../protocol/messages.sx")+val transfer = use("../protocol/transfer.sx")+val promisor = use("../protocol/promisor.sx")+val checkout = use("../worktree/checkout.sx")+val cmsg    = use("../core/msg.sx")++fn last_segment(path: bytes.Bytes) bytes.Bytes = trust {+    val slash: mut i64 = -1+    val i: mut usize = 0+    for i < path.len {+        if bytes.Bytes.at(path, i) == 47 {+            slash = i as i64+        }+        i+++    }+    if slash >= 0 && (slash as usize) + 1 < path.len {+        return bytes.Bytes.slice(path, (slash as usize) + 1, path.len)+    }+    if path.len > 0 {+        return path+    }+    return bytes.bytes(c"repo", 4)+}++fn selected_commits(+    refs: list[msg_refs.RefInfo],+    policy: bytes.Bytes+) list[objid.Id] = trust {+    val out: mut list[objid.Id] = lists.new[objid.Id]()+    if bytes.Bytes.eql(policy, bytes.bytes(c"none", 4)) {+        return out+    }+    if bytes.Bytes.eql(policy, bytes.bytes(c"head", 4)) {+        val dt = transfer.default_target(refs)+        if dt is some id {+            @append(out, id)+        }+        return out+    }+    for r in refs {+        if r.target.ptr != none {+            @append(out, objid.id(r.target.ptr))+        }+    }+    return out+}++fn send_chunks(c: ref client.Client, repo: layout.Repo, all: list[bytes.Bytes]) bool = trust {+    val n: usize = @len(all)+    val off: mut usize = 0+    for off < n {+        val batch: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+        val end: usize = off + 4096+        val lim: mut usize = n+        if end < n {+            lim = end+        }+        val i: mut usize = off+        for i < lim {+            val o = @get(all, i)+            if o is some v {+                @append(batch, v)+            }+            i+++        }+        if !client.get_chunks(c, repo, batch) {+            @listfree(batch)+            return false+        }+        @listfree(batch)+        off = lim+    }+    return true+}++pub fn run(args: list[ref u8], start: usize) i32 = trust {+    val url: mut bytes.Bytes = bytes.empty()+    val path: mut bytes.Bytes = bytes.empty()+    val policy: mut bytes.Bytes = bytes.bytes(c"head", 4)+    val key_name: mut bytes.Bytes = bytes.empty()+    val tls_pin: mut bytes.Bytes = bytes.empty()+    val i: mut usize = start+    for i < @len(args) {+        val o = @get(args, i)+        if o is some a {+            val av: bytes.Bytes = bytes.from_cstr(a)+            if bytes.Bytes.starts_with(av, bytes.bytes(c"-blobs:", 7)) {+                policy = bytes.Bytes.dup(bytes.Bytes.slice(av, 7, av.len))+            } elif bytes.Bytes.starts_with(av, bytes.bytes(c"-key:", 5)) {+                key_name = bytes.Bytes.dup(bytes.Bytes.slice(av, 5, av.len))+            } elif bytes.Bytes.starts_with(av, bytes.bytes(c"-pin:", 5)) {+                tls_pin = bytes.Bytes.dup(bytes.Bytes.slice(av, 5, av.len))+            } elif av.len > 0 && bytes.Bytes.at(av, 0) == 45 {+                cmsg.error_prefix()+                stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})+                return 1+            } elif url.ptr == none {+                url = bytes.Bytes.dup(av)+            } else {+                path = bytes.Bytes.dup(av)+            }+        }+        i+++    }+    if url.ptr == none {+        cmsg.error_prefix()+        stdio.eprint("clone requires a URL\n", {})+        return 1+    }+    if path.ptr == none {+        path = bytes.Bytes.dup(last_segment(url))+    }+    val purl = client.parse_url(url)+    if purl is none {+        cmsg.error_prefix()+        stdio.eprint("unsupported URL\n", {})+        return 1+    }+    val pv: bytes.Bytes = path+    val repo_r = layout.init(files.to_view(pv))+    val repo: mut layout.Repo = layout.Repo{root: bytes.empty()}+    match repo_r {+        ok r => {+            repo = r+        }+        err e => {+            cmsg.error_prefix()+            stdio.eprint("cannot create repository ({d})\n", {e})+            return 1+        }+    }+    val remote_name: bytes.Bytes = bytes.Bytes.dup(bytes.bytes(c"origin", 6))+    val url_key: bytes.Bytes = remote_config.key_for(remote_name, bytes.bytes(c"url", 3))+    config.set(repo, url_key, url)+    bytes.free_owned(url_key)+    if tls_pin.len > 0 {+        val pk: bytes.Bytes = remote_config.key_for(remote_name, bytes.bytes(c"tls-pin", 7))+        config.set(repo, pk, tls_pin)+        bytes.free_owned(pk)+    }+    val repo_name: bytes.Bytes = client.url_repo_name(url)+    val c_opt = client.connect_pinned(url, key_name, repo_name, tls_pin)+    val c: mut ref client.Client = none+    match c_opt {+        some v => {+            c = v+        }+        none => {+            cmsg.error_prefix()+            stdio.eprint("cannot connect or authenticate\n", {})+            layout.free_repo(repo)+            return 1+        }+    }+    val refs_opt = client.list_refs(c)+    if refs_opt is none {+        cmsg.error_prefix()+        stdio.eprint("cannot list refs\n", {})+        client.free_client(c)+        layout.free_repo(repo)+        return 1+    }+    val refs: mut list[msg_refs.RefInfo] = lists.new[msg_refs.RefInfo]()+    match refs_opt {+        some rv => {+            refs = rv+        }+        none => {+            return 1+        }+    }+    val wants: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    for r in refs {+        if r.target.ptr != none {+            @append(wants, bytes.Bytes.dup(bytes.bytes(r.target.ptr, 32)))+        }+    }+    val haves: list[bytes.Bytes] = lists.new[bytes.Bytes]()+    client.negotiate(c, wants, haves)+    @listfree(haves)+    if !client.fetch_skeleton(c, repo, wants) {+        cmsg.error_prefix()+        stdio.eprint("fetch failed\n", {})+        transfer.free_id_bytes(wants)+        client.free_client(c)+        layout.free_repo(repo)+        return 1+    }+    transfer.free_id_bytes(wants)+    val st: store.Store = store.open_all(repo)+    val commits: list[objid.Id] = selected_commits(refs, policy)+    val chunks: list[bytes.Bytes] = transfer.chunks_for_commits(st.handles, commits)+    @listfree(commits)+    val chunks_ok: bool = send_chunks(c, repo, chunks)+    transfer.free_id_bytes(chunks)+    store.close(st)+    if !chunks_ok {+        cmsg.error_prefix()+        stdio.eprint("chunk fetch failed\n", {})+        client.free_client(c)+        layout.free_repo(repo)+        return 1+    }+    val applied: i32 = transfer.apply_refs(repo, refs, remote_name, true)+    if applied != 0 {+        cmsg.error_prefix()+        stdio.eprint("cannot write repository state\n", {})+        client.free_client(c)+        layout.free_repo(repo)+        return 1+    }+    val prom_key: bytes.Bytes = bytes.bytes(c"promisor", 8)+    config.set(repo, prom_key, remote_name)+    promisor.configure(repo, remote_name)+    if bytes.Bytes.eql(policy, bytes.bytes(c"none", 4)) {+        cmsg.info_prefix()+        stdio.print("cloned metadata only; blobs are promised\n", {})+    }+    val co: i32 = checkout.materialize_working_copy(repo)+    if co != 0 {+        cmsg.info_prefix()+        stdio.print("cloned; checkout reported {d}\n", {co})+    }+    cmsg.info_prefix()+    stdio.print("cloned into {s}\n", {str.view(pv.ptr, pv.len as i64)})+    client.free_client(c)+    layout.free_repo(repo)+    return 0+}--- /dev/null+++ b/veins/src/cli/fetch_cmd.sx@@ -0,0 +1,220 @@+/// `vn fetch`: native incremental fetch.++val stdio   = use("std/stdio")+val str     = use("std/string")+val bytes   = use("../core/bytes.sx")+val lists   = use("../core/lists.sx")+val objid   = use("../object/id.sx")+val store   = use("../store/store.sx")+val state   = use("../store/state.sx")+val layout  = use("../store/layout.sx")+val remote_config = use("../git/remote.sx")+val client  = use("../protocol/client.sx")+val transfer = use("../protocol/transfer.sx")+val msg_refs = use("../protocol/messages.sx")+val cmsg    = use("../core/msg.sx")++fn send_chunks(c: ref client.Client, repo: layout.Repo, all: list[bytes.Bytes]) bool = trust {+    val st: store.Store = store.open_all(repo)+    val missing: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    for x in all {+        val loc: mut store.Loc = store.Loc{pack_index: 0, record_index: 0, kind: 0}+        if !store.find_handles(st.handles, objid.id(x.ptr), loc) {+            @append(missing, x)+        }+    }+    store.close(st)+    val n: usize = @len(missing)+    val off: mut usize = 0+    for off < n {+        val batch: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+        val end: usize = off + 4096+        val lim: mut usize = n+        if end < n {+            lim = end+        }+        val i: mut usize = off+        for i < lim {+            val o = @get(missing, i)+            if o is some v {+                @append(batch, v)+            }+            i+++        }+        if !client.get_chunks(c, repo, batch) {+            @listfree(batch)+            @listfree(missing)+            return false+        }+        @listfree(batch)+        off = lim+    }+    @listfree(missing)+    return true+}++pub fn run(args: list[ref u8], start: usize) i32 = trust {+    val remote_name: mut bytes.Bytes = bytes.Bytes.dup(bytes.bytes(c"origin", 6))+    val path: mut str.StringView = str.from_cstr(c".")+    val have_remote: mut bool = false+    val i: mut usize = start+    for i < @len(args) {+        val o = @get(args, i)+        if o is some a {+            val av: bytes.Bytes = bytes.from_cstr(a)+            if av.len > 0 && bytes.Bytes.at(av, 0) == 45 {+                cmsg.error_prefix()+                stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})+                return 1+            } elif !have_remote {+                remote_name = bytes.Bytes.dup(av)+                have_remote = true+            } else {+                path = str.from_cstr(a)+            }+        }+        i+++    }+    val repo_opt = layout.discover(path)+    val repo: mut layout.Repo = layout.Repo{root: bytes.empty()}+    match repo_opt {+        some r => {+            repo = r+        }+        none => {+            cmsg.error_prefix()+            stdio.eprint("not a veins repository\n", {})+            return 1+        }+    }+    val url_opt = remote_config.url_of(repo, remote_name)+    if url_opt is none {+        cmsg.error_prefix()+        stdio.eprint("unknown remote\n", {})+        layout.free_repo(repo)+        return 1+    }+    val url: mut bytes.Bytes = bytes.empty()+    match url_opt {+        some v => {+            url = v+        }+        none => {+            return 1+        }+    }+    val key_name = remote_config.key_name_of(repo, remote_name)+    val key: mut bytes.Bytes = bytes.empty()+    if key_name is some k {+        key = k+    }+    val pin_opt = remote_config.tls_pin_of(repo, remote_name)+    val pin: mut bytes.Bytes = bytes.empty()+    if pin_opt is some pv {+        pin = pv+    }+    val repo_name: bytes.Bytes = client.url_repo_name(url)+    val c_opt = client.connect_pinned(url, key, repo_name, pin)+    bytes.free_owned(url)+    if key.ptr != none {+        bytes.free_owned(key)+    }+    if repo_name.ptr != none {+        bytes.free_owned(repo_name)+    }+    val c: mut ref client.Client = none+    match c_opt {+        some v => {+            c = v+        }+        none => {+            cmsg.error_prefix()+            stdio.eprint("cannot connect or authenticate\n", {})+            layout.free_repo(repo)+            return 1+        }+    }+    val refs_opt = client.list_refs(c)+    if refs_opt is none {+        cmsg.error_prefix()+        stdio.eprint("cannot list refs\n", {})+        client.free_client(c)+        layout.free_repo(repo)+        return 1+    }+    val refs: mut list[msg_refs.RefInfo] = lists.new[msg_refs.RefInfo]()+    match refs_opt {+        some rv => {+            refs = rv+        }+        none => {+            return 1+        }+    }+    val st: store.Store = store.open_all(repo)+    val haves: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    val hs: list[objid.Id] = state.heads(repo)+    for h in hs {+        @append(haves, bytes.Bytes.dup(bytes.bytes(h.ptr, 32)))+    }+    graph_free_ids(hs)+    val wants: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    for r in refs {+        if r.target.ptr != none {+            @append(wants, bytes.Bytes.dup(bytes.bytes(r.target.ptr, 32)))+        }+    }+    client.negotiate(c, wants, haves)+    val passed: bool = client.fetch_skeleton(c, repo, wants)+    transfer.free_id_bytes(wants)+    transfer.free_id_bytes(haves)+    store.close(st)+    if !passed {+        cmsg.error_prefix()+        stdio.eprint("fetch failed\n", {})+        client.free_client(c)+        layout.free_repo(repo)+        return 1+    }+    val st2: store.Store = store.open_all(repo)+    val commits: mut list[objid.Id] = lists.new[objid.Id]()+    for r in refs {+        if r.target.ptr != none {+            @append(commits, objid.id(r.target.ptr))+        }+    }+    val chunks: list[bytes.Bytes] = transfer.chunks_for_commits(st2.handles, commits)+    val chunks_ok: bool = send_chunks(c, repo, chunks)+    transfer.free_id_bytes(chunks)+    @listfree(commits)+    store.close(st2)+    if !chunks_ok {+        cmsg.error_prefix()+        stdio.eprint("chunk fetch failed\n", {})+        client.free_client(c)+        layout.free_repo(repo)+        return 1+    }+    val applied: i32 = transfer.apply_refs(repo, refs, remote_name, false)+    msg_refs.free_refs(refs)+    client.free_client(c)+    layout.free_repo(repo)+    if applied != 0 {+        cmsg.error_prefix()+        stdio.eprint("cannot write repository state\n", {})+        return 1+    }+    cmsg.info_prefix()+    stdio.print("fetched from {s}\n", {str.view(remote_name.ptr, remote_name.len as i64)})+    bytes.free_owned(remote_name)+    return 0+}++fn graph_free_ids(ids: list[objid.Id]) void = trust {+    for x in ids {+        if x.ptr != none {+            bytes.free_owned(x)+        }+    }+    @listfree(ids)+}--- a/veins/src/cli/git_cmd.sx+++ b/veins/src/cli/git_cmd.sx@@ -8,6 +8,8 @@ val mirror = use("../git/mirror.sx") val import = use("../git/import.sx") val export = use("../git/export.sx")+val remote = use("../git/remote.sx")+val config = use("../core/repoconfig.sx")  pub fn run(args: list[ref u8], start: usize) i32 = trust {     val sub_opt = @get(args, start)@@ -27,6 +29,15 @@     }     if @strcmp(sub, c"export") == 0 {         return run_export(args, start + 1)+    }+    if @strcmp(sub, c"fetch") == 0 {+        return run_fetch(args, start + 1)+    }+    if @strcmp(sub, c"push") == 0 {+        return run_push(args, start + 1)+    }+    if @strcmp(sub, c"remote") == 0 {+        return run_remote(args, start + 1)     }     msg.error_prefix()     stdio.eprint("unknown git subcommand: {s}\n", {str.from_cstr(sub)})@@ -120,4 +131,204 @@     val status: i32 = export.run(repo)     layout.free_repo(repo)     return status+}++fn open_repo(path: str.StringView) option[layout.Repo] = trust {+    return layout.discover(path)+}++fn run_fetch(args: list[ref u8], start: usize) i32 = trust {+    val remote_name: mut bytes.Bytes = bytes.Bytes.dup(bytes.bytes(c"origin", 6))+    val path: mut str.StringView = str.from_cstr(c".")+    val have_remote: mut bool = false+    val i: mut usize = start+    for i < @len(args) {+        val o = @get(args, i)+        if o is some a {+            val av: bytes.Bytes = bytes.from_cstr(a)+            if av.len > 0 && bytes.Bytes.at(av, 0) == 45 {+                msg.error_prefix()+                stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})+                bytes.free_ptr(remote_name.ptr)+                return 1+            } elif !have_remote {+                remote_name = bytes.Bytes.dup(av)+                have_remote = true+            } else {+                path = str.from_cstr(a)+            }+        }+        i+++    }+    val repo_opt = open_repo(path)+    val repo: mut layout.Repo = layout.Repo{root: bytes.empty()}+    match repo_opt {+        some r => {+            repo = r+        }+        none => {+            msg.error_prefix()+            stdio.eprint("not a veins repository\n", {})+            @free(remote_name.ptr as ref void)+            return 1+        }+    }+    val code: i32 = remote.fetch(repo, remote_name)+    layout.free_repo(repo)+    @free(remote_name.ptr as ref void)+    return code+}++fn run_push(args: list[ref u8], start: usize) i32 = trust {+    val remote_name: mut bytes.Bytes = bytes.Bytes.dup(bytes.bytes(c"origin", 6))+    val bookmark: mut bytes.Bytes = bytes.empty()+    val path: mut str.StringView = str.from_cstr(c".")+    val have_remote: mut bool = false+    val i: mut usize = start+    for i < @len(args) {+        val o = @get(args, i)+        if o is some a {+            val av: bytes.Bytes = bytes.from_cstr(a)+            if av.len > 0 && bytes.Bytes.at(av, 0) == 45 {+                msg.error_prefix()+                stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})+                return 1+            } elif !have_remote {+                remote_name = bytes.Bytes.dup(av)+                have_remote = true+            } elif bookmark.ptr == none {+                bookmark = bytes.Bytes.dup(av)+            } else {+                path = str.from_cstr(a)+            }+        }+        i+++    }+    if bookmark.ptr == none {+        msg.error_prefix()+        stdio.eprint("git push requires a bookmark\n", {})+        @free(remote_name.ptr as ref void)+        return 1+    }+    val repo_opt = open_repo(path)+    val repo: mut layout.Repo = layout.Repo{root: bytes.empty()}+    match repo_opt {+        some r => {+            repo = r+        }+        none => {+            msg.error_prefix()+            stdio.eprint("not a veins repository\n", {})+            return 1+        }+    }+    val code: i32 = remote.push(repo, remote_name, bookmark)+    layout.free_repo(repo)+    @free(remote_name.ptr as ref void)+    @free(bookmark.ptr as ref void)+    return code+}++fn run_remote(args: list[ref u8], start: usize) i32 = trust {+    val sub_opt = @get(args, start)+    val sub: mut ref u8 = none+    match sub_opt {+        some s => {+            sub = s+        }+        none => {+            msg.error_prefix()+            stdio.eprint("expected remote subcommand (add, list, remove)\n", {})+            return 1+        }+    }+    val repo_opt = open_repo(str.from_cstr(c"."))+    val repo: mut layout.Repo = layout.Repo{root: bytes.empty()}+    match repo_opt {+        some r => {+            repo = r+        }+        none => {+            msg.error_prefix()+            stdio.eprint("not a veins repository\n", {})+            return 1+        }+    }+    if @strcmp(sub, c"add") == 0 {+        val name_opt = @get(args, start + 1)+        val url_opt = @get(args, start + 2)+        val name: mut bytes.Bytes = bytes.empty()+        val url: mut bytes.Bytes = bytes.empty()+        if name_opt is some n {+            name = bytes.from_cstr(n)+        }+        if url_opt is some u {+            url = bytes.from_cstr(u)+        }+        if name.ptr == none || url.ptr == none {+            msg.error_prefix()+            stdio.eprint("remote add requires a name and URL\n", {})+            layout.free_repo(repo)+            return 1+        }+        val k: bytes.Bytes = remote.key_for(name, bytes.bytes(c"url", 3))+        val passed: bool = config.set(repo, k, url)+        bytes.free_ptr(k.ptr)+        layout.free_repo(repo)+        if !passed {+            msg.error_prefix()+            stdio.eprint("cannot write repository config\n", {})+            return 1+        }+        return 0+    }+    if @strcmp(sub, c"list") == 0 || @strcmp(sub, c"ls") == 0 {+        val names = remote.list_remotes(repo)+        for n in names {+            val u = remote.url_of(repo, n)+            val url: mut bytes.Bytes = bytes.empty()+            if u is some x {+                url = x+            }+            stdio.print(+                "{s}\t{s}\n",+                {str.view(n.ptr, n.len as i64), str.view(url.ptr, url.len as i64)}+            )+            if url.ptr != none {+                @free(url.ptr as ref void)+            }+            bytes.free_ptr(n.ptr)+        }+        @listfree(names)+        layout.free_repo(repo)+        return 0+    }+    if @strcmp(sub, c"remove") == 0 || @strcmp(sub, c"rm") == 0 {+        val name_opt = @get(args, start + 1)+        if name_opt is none {+            msg.error_prefix()+            stdio.eprint("remote remove requires a name\n", {})+            layout.free_repo(repo)+            return 1+        }+        val name: mut bytes.Bytes = bytes.empty()+        if name_opt is some nv {+            name = bytes.from_cstr(nv)+        }+        val k: bytes.Bytes = remote.key_for(name, bytes.bytes(c"url", 3))+        val k2: bytes.Bytes = remote.key_for(name, bytes.bytes(c"key", 3))+        val k3: bytes.Bytes = remote.key_for(name, bytes.bytes(c"tls-pin", 7))+        config.remove(repo, k)+        config.remove(repo, k2)+        config.remove(repo, k3)+        bytes.free_ptr(k.ptr)+        bytes.free_ptr(k2.ptr)+        bytes.free_ptr(k3.ptr)+        layout.free_repo(repo)+        return 0+    }+    layout.free_repo(repo)+    msg.error_prefix()+    stdio.eprint("unknown remote subcommand: {s}\n", {str.from_cstr(sub)})+    return 1 }--- a/veins/src/cli/help_cmd.sx+++ b/veins/src/cli/help_cmd.sx@@ -14,6 +14,13 @@     stdio.puts("subcommands:")     stdio.puts("  init         create a repository")     stdio.puts("  git          import from or export to git")+    stdio.puts("  clone        clone a repository over the native protocol")+    stdio.puts("  fetch        fetch from a native remote")+    stdio.puts("  push         push a bookmark to a native remote")+    stdio.puts("  serve        run the native server over stdio or TLS")+    stdio.puts("  key          manage local Ed25519 keys")+    stdio.puts("  access       manage a served repository's access file")+    stdio.puts("  whoami       report the role granted by a server")     stdio.puts("  co           write a revision into the working directory; alias: checkout")     stdio.puts("  stat         show working-copy changes; alias: status")     stdio.puts("  ls           list tracked files")@@ -63,6 +70,10 @@     stdio.puts("  import [-source:<gitdir>] [path]")     stdio.puts("                            import reachable git commits and refs")     stdio.puts("  export [path]             export commits into the git mirror")+    stdio.puts("  fetch [<remote>] [path]   git fetch into the mirror, then import")+    stdio.puts("  push [<remote>] <bookmark> [path]")+    stdio.puts("                            export and git push a bookmark")+    stdio.puts("  remote <add|list|remove>  manage git remotes")     stdio.puts("")     stdio.puts("run 'vn help git <subcommand>' for details") }@@ -321,6 +332,50 @@     stdio.puts("")     stdio.puts("arguments:")     stdio.puts("  [command]                 command to describe")+}+++fn show_clone() void = trust {+    stdio.puts("usage: vn clone <url> [-blobs:<head|none|all>] [-key:<name>] [-pin:<sha256>] [path]")+    stdio.puts("")+    stdio.puts("clone a repository over file://, ssh://, or veins://")+}++fn show_fetch() void = trust {+    stdio.puts("usage: vn fetch [<remote>] [path]")+    stdio.puts("")+    stdio.puts("fetch new history and chunks from a configured native remote")+}++fn show_push() void = trust {+    stdio.puts("usage: vn push [<remote>] <bookmark> [path]")+    stdio.puts("")+    stdio.puts("push a bookmark to a configured native remote")+}++fn show_serve() void = trust {+    stdio.puts("usage: vn serve -stdio <repo>")+    stdio.puts("       vn serve -listen <addr:port> -root <dir> -tls-cert <file> -tls-key <file>")+    stdio.puts("")+    stdio.puts("run the native server over standard input/output or TLS 1.3")+}++fn show_key() void = trust {+    stdio.puts("usage: vn key <generate|list|show> [name]")+    stdio.puts("")+    stdio.puts("manage local Ed25519 keys in the user key directory")+}++fn show_access() void = trust {+    stdio.puts("usage: vn access <add|list|remove|anonymous> ...")+    stdio.puts("")+    stdio.puts("manage a served repository's .veins/access policy")+}++fn show_whoami() void = trust {+    stdio.puts("usage: vn whoami [<remote>|<url>]")+    stdio.puts("")+    stdio.puts("connect to a server and report the granted role and key fingerprint") }  pub fn run(args: list[ref u8], start: usize) i32 = trust {@@ -422,6 +477,34 @@     }     if cmd_is(cmd, c"op", 2) {         show_op()+        return 0+    }+    if cmd_is(cmd, c"clone", 5) {+        show_clone()+        return 0+    }+    if cmd_is(cmd, c"fetch", 5) {+        show_fetch()+        return 0+    }+    if cmd_is(cmd, c"push", 4) {+        show_push()+        return 0+    }+    if cmd_is(cmd, c"serve", 5) {+        show_serve()+        return 0+    }+    if cmd_is(cmd, c"key", 3) {+        show_key()+        return 0+    }+    if cmd_is(cmd, c"access", 6) {+        show_access()+        return 0+    }+    if cmd_is(cmd, c"whoami", 6) {+        show_whoami()         return 0     }     if cmd_is(cmd, c"git", 3) {@@ -434,6 +517,18 @@                 }                 if cmd_is(sub, c"export", 6) {                     show_git_export()+                    return 0+                }+                if cmd_is(sub, c"fetch", 5) {+                    stdio.puts("usage: vn git fetch [<remote>] [path]")+                    return 0+                }+                if cmd_is(sub, c"push", 4) {+                    stdio.puts("usage: vn git push [<remote>] <bookmark> [path]")+                    return 0+                }+                if cmd_is(sub, c"remote", 6) {+                    stdio.puts("usage: vn git remote <add|list|remove> ...")                     return 0                 }                 msg.error_prefix()--- /dev/null+++ b/veins/src/cli/key_cmd.sx@@ -0,0 +1,91 @@+/// `vn key`: manage local Ed25519 keys.++val stdio  = use("std/stdio")+val str    = use("std/string")+val bytes  = use("../core/bytes.sx")+val keys   = use("../auth/keys.sx")+val ed     = use("../crypto/ed25519.sx")+val cmsg   = use("../core/msg.sx")++fn print_key(k: keys.Key) void = trust {+    val pub_text: bytes.Bytes = ed.format_public(k.public_key)+    stdio.print("name: {s}\n", {str.view(k.name.ptr, k.name.len as i64)})+    stdio.print("public key: {s}\n", {str.view(pub_text.ptr, pub_text.len as i64)})+    stdio.print("fingerprint: {s}\n", {str.view(k.fingerprint.ptr, k.fingerprint.len as i64)})+    bytes.free_owned(pub_text)+}++pub fn run(args: list[ref u8], start: usize) i32 = trust {+    val sub_opt = @get(args, start)+    val sub: mut ref u8 = none+    match sub_opt {+        some s => {+            sub = s+        }+        none => {+            cmsg.error_prefix()+            stdio.eprint("expected key subcommand (generate, list, show, import)\n", {})+            return 1+        }+    }+    if @strcmp(sub, c"generate") == 0 {+        val name_opt = @get(args, start + 1)+        val name: mut bytes.Bytes = bytes.empty()+        if name_opt is some nv {+            name = bytes.from_cstr(nv)+        } else {+            cmsg.error_prefix()+            stdio.eprint("key generate requires a name\n", {})+            return 1+        }+        val k_opt = keys.generate(name)+        if k_opt is some k {+            print_key(k)+            keys.free_key(k)+            return 0+        }+        cmsg.error_prefix()+        stdio.eprint("cannot create key\n", {})+        return 1+    }+    if @strcmp(sub, c"list") == 0 {+        val names: list[bytes.Bytes] = keys.list_names()+        for n in names {+            val k_opt = keys.load(n)+            if k_opt is some k {+                print_key(k)+                keys.free_key(k)+            }+        }+        keys.free_names(names)+        return 0+    }+    if @strcmp(sub, c"show") == 0 {+        val name_opt = @get(args, start + 1)+        val name: mut bytes.Bytes = bytes.empty()+        if name_opt is some nv {+            name = bytes.from_cstr(nv)+        } else {+            cmsg.error_prefix()+            stdio.eprint("key show requires a name\n", {})+            return 1+        }+        val k_opt = keys.load(name)+        if k_opt is some k {+            print_key(k)+            keys.free_key(k)+            return 0+        }+        cmsg.error_prefix()+        stdio.eprint("key not found or has unsafe permissions\n", {})+        return 1+    }+    if @strcmp(sub, c"import") == 0 {+        cmsg.error_prefix()+        stdio.eprint("OpenSSH key import is not supported\n", {})+        return 1+    }+    cmsg.error_prefix()+    stdio.eprint("unknown key subcommand: {s}\n", {str.from_cstr(sub)})+    return 1+}--- /dev/null+++ b/veins/src/cli/push_cmd.sx@@ -0,0 +1,198 @@+/// `vn push`: native push.++val stdio   = use("std/stdio")+val str     = use("std/string")+val bytes   = use("../core/bytes.sx")+val lists   = use("../core/lists.sx")+val objid   = use("../object/id.sx")+val graph   = use("../object/graph.sx")+val view    = use("../object/view.sx")+val store   = use("../store/store.sx")+val state   = use("../store/state.sx")+val layout  = use("../store/layout.sx")+val remote_config = use("../git/remote.sx")+val client  = use("../protocol/client.sx")+val transfer = use("../protocol/transfer.sx")+val msg_refs = use("../protocol/messages.sx")+val cmsg    = use("../core/msg.sx")++fn find_server_target(refs: list[msg_refs.RefInfo], name: bytes.Bytes) bytes.Bytes = trust {+    for r in refs {+        if bytes.Bytes.eql(r.name, name) {+            return bytes.Bytes.dup(r.target)+        }+    }+    return bytes.empty()+}++pub fn run(args: list[ref u8], start: usize) i32 = trust {+    val remote_name: mut bytes.Bytes = bytes.Bytes.dup(bytes.bytes(c"origin", 6))+    val bookmark: mut bytes.Bytes = bytes.empty()+    val path: mut str.StringView = str.from_cstr(c".")+    val have_remote: mut bool = false+    val i: mut usize = start+    for i < @len(args) {+        val o = @get(args, i)+        if o is some a {+            val av: bytes.Bytes = bytes.from_cstr(a)+            if av.len > 0 && bytes.Bytes.at(av, 0) == 45 {+                cmsg.error_prefix()+                stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})+                return 1+            } elif !have_remote {+                remote_name = bytes.Bytes.dup(av)+                have_remote = true+            } elif bookmark.ptr == none {+                bookmark = bytes.Bytes.dup(av)+            } else {+                path = str.from_cstr(a)+            }+        }+        i+++    }+    if bookmark.ptr == none {+        cmsg.error_prefix()+        stdio.eprint("push requires a bookmark name\n", {})+        return 1+    }+    val repo_opt = layout.discover(path)+    val repo: mut layout.Repo = layout.Repo{root: bytes.empty()}+    match repo_opt {+        some r => {+            repo = r+        }+        none => {+            cmsg.error_prefix()+            stdio.eprint("not a veins repository\n", {})+            return 1+        }+    }+    val url_opt = remote_config.url_of(repo, remote_name)+    if url_opt is none {+        cmsg.error_prefix()+        stdio.eprint("unknown remote\n", {})+        layout.free_repo(repo)+        return 1+    }+    val url: mut bytes.Bytes = bytes.empty()+    match url_opt {+        some v => {+            url = v+        }+        none => {+            return 1+        }+    }+    val key_name = remote_config.key_name_of(repo, remote_name)+    val key: mut bytes.Bytes = bytes.empty()+    if key_name is some k {+        key = k+    }+    val pin_opt = remote_config.tls_pin_of(repo, remote_name)+    val pin: mut bytes.Bytes = bytes.empty()+    if pin_opt is some pv {+        pin = pv+    }+    val st: store.Store = store.open_all(repo)+    val v_opt = state.current_view(repo, st.handles)+    val v: mut ref view.View = none+    match v_opt {+        some x => {+            v = x+        }+        none => {+            v = state.empty_view()+        }+    }+    val target_opt = graph.resolve(st.handles, v, bookmark)+    if target_opt is none {+        cmsg.error_prefix()+        stdio.eprint("unknown bookmark: {s}\n", {str.view(bookmark.ptr, bookmark.len as i64)})+        view.free_view(v)+        store.close(st)+        layout.free_repo(repo)+        return 1+    }+    val target: mut objid.Id = objid.id_none()+    match target_opt {+        some tv => {+            target = graph.copy_id(tv)+        }+        none => {+            return 1+        }+    }+    val roots: mut list[objid.Id] = lists.new[objid.Id]()+    @append(roots, target)+    val commits: list[objid.Id] = graph.collect(st.handles, roots)+    val objects: list[objid.Id] = transfer.objects_for_commits(st.handles, commits)+    @listfree(roots)+    view.free_view(v)+    store.close(st)+    val repo_name: bytes.Bytes = client.url_repo_name(url)+    val c_opt = client.connect_pinned(url, key, repo_name, pin)+    bytes.free_owned(url)+    if key.ptr != none {+        bytes.free_owned(key)+    }+    if repo_name.ptr != none {+        bytes.free_owned(repo_name)+    }+    val c: mut ref client.Client = none+    match c_opt {+        some x => {+            c = x+        }+        none => {+            cmsg.error_prefix()+            stdio.eprint("cannot connect or authenticate\n", {})+            transfer.free_id_bytes(commits)+            transfer.free_id_bytes(objects)+            layout.free_repo(repo)+            return 1+        }+    }+    if !client.push_objects(c, repo, objects) {+        cmsg.error_prefix()+        stdio.eprint("push transfer failed\n", {})+        client.free_client(c)+        transfer.free_id_bytes(commits)+        transfer.free_id_bytes(objects)+        layout.free_repo(repo)+        return 1+    }+    val refs_opt = client.list_refs(c)+    val old: mut bytes.Bytes = bytes.empty()+    if refs_opt is some refs {+        old = find_server_target(refs, bookmark)+        msg_refs.free_refs(refs)+    }+    val updates: mut list[msg_refs.UpdateRef] = lists.new[msg_refs.UpdateRef]()+    @append(+        updates,+        msg_refs.UpdateRef{+            name: bytes.Bytes.dup(bookmark),+            expected: old,+            target: bytes.Bytes.dup(bytes.bytes(target.ptr, 32))+        }+    )+    val pushed: bool = client.update_refs(c, updates)+    msg_refs.free_updates(updates)+    client.free_client(c)+    transfer.free_id_bytes(commits)+    transfer.free_id_bytes(objects)+    layout.free_repo(repo)+    if !pushed {+        cmsg.error_prefix()+        stdio.eprint("ref update rejected\n", {})+        return 1+    }+    cmsg.info_prefix()+    stdio.print(+        "pushed {s} to {s}\n",+        {str.view(bookmark.ptr, bookmark.len as i64), str.view(remote_name.ptr, remote_name.len as i64)}+    )+    bytes.free_owned(bookmark)+    bytes.free_owned(remote_name)+    return 0+}--- a/veins/src/cli/selftest_cmd.sx+++ b/veins/src/cli/selftest_cmd.sx@@ -518,7 +518,8 @@         bookmarks: bookmarks,         tags: tags,         remote_refs: remotes,-        working_copies: wcs+        working_copies: wcs,+        owned: bytes.empty()     }     val body: bytes.Bytes = view.encode(@addr(v))     val decoded = view.decode(body)@@ -560,7 +561,8 @@         hostname: bytes.bytes(c"host", 4),         username: bytes.bytes(c"alice", 5),         description: bytes.bytes(c"selftest operation", 18),-        tags: tags+        tags: tags,+        owned: bytes.empty()     }     val body: bytes.Bytes = operation.encode(@addr(op))     val decoded = operation.decode(body)--- /dev/null+++ b/veins/src/cli/serve_cmd.sx@@ -0,0 +1,108 @@+/// `vn serve`: native server over stdio or TLS.++val stdio  = use("std/stdio")+val str    = use("std/string")+val bytes  = use("../core/bytes.sx")+val layout = use("../store/layout.sx")+val server = use("../server/serve.sx")+val cmsg   = use("../core/msg.sx")++pub fn run(args: list[ref u8], start: usize) i32 = trust {+    val stdio_mode: mut bool = false+    val listen: mut bytes.Bytes = bytes.empty()+    val root: mut str.StringView = str.from_cstr(c".")+    val cert: mut bytes.Bytes = bytes.empty()+    val key: mut bytes.Bytes = bytes.empty()+    val repo_path: mut str.StringView = str.from_cstr(c".")+    val i: mut usize = start+    for i < @len(args) {+        val o = @get(args, i)+        if o is some a {+            val av: bytes.Bytes = bytes.from_cstr(a)+            if bytes.Bytes.eql(av, bytes.bytes(c"-stdio", 6)) {+                stdio_mode = true+                if i + 1 < @len(args) {+                    val v = @get(args, i + 1)+                    if v is some r {+                        repo_path = str.from_cstr(r)+                        i+++                    }+                }+            } elif bytes.Bytes.eql(av, bytes.bytes(c"-listen", 7)) {+                if i + 1 < @len(args) {+                    val v = @get(args, i + 1)+                    if v is some r {+                        listen = bytes.Bytes.dup(bytes.from_cstr(r))+                        i+++                    }+                }+            } elif bytes.Bytes.eql(av, bytes.bytes(c"-root", 5)) {+                if i + 1 < @len(args) {+                    val v = @get(args, i + 1)+                    if v is some r {+                        root = str.from_cstr(r)+                        i+++                    }+                }+            } elif bytes.Bytes.eql(av, bytes.bytes(c"-tls-cert", 9)) {+                if i + 1 < @len(args) {+                    val v = @get(args, i + 1)+                    if v is some r {+                        cert = bytes.Bytes.dup(bytes.from_cstr(r))+                        i+++                    }+                }+            } elif bytes.Bytes.eql(av, bytes.bytes(c"-tls-key", 8)) {+                if i + 1 < @len(args) {+                    val v = @get(args, i + 1)+                    if v is some r {+                        key = bytes.Bytes.dup(bytes.from_cstr(r))+                        i+++                    }+                }+            } else {+                cmsg.error_prefix()+                stdio.eprint("unknown serve option: {s}\n", {str.from_cstr(a)})+                return 1+            }+        }+        i+++    }+    if stdio_mode {+        val repo_opt = layout.discover(repo_path)+        if repo_opt is none {+            cmsg.error_prefix()+            stdio.eprint("not a veins repository\n", {})+            return 1+        }+        val repo: mut layout.Repo = layout.Repo{root: bytes.empty()}+        match repo_opt {+            some r => {+                repo = r+            }+            none => {+                return 1+            }+        }+        return server.serve_stdio(repo)+    }+    if listen.ptr == none {+        cmsg.error_prefix()+        stdio.eprint("serve requires -stdio or -listen\n", {})+        return 1+    }+    if cert.ptr == none || key.ptr == none {+        cmsg.error_prefix()+        stdio.eprint("TLS requires -tls-cert and -tls-key\n", {})+        return 1+    }+    val root_repo: layout.Repo = layout.Repo{+        root: bytes.Bytes.dup(bytes.bytes(root.ptr, root.len))+    }+    val code: i32 = server.serve_listen(listen, root_repo, cert, key)+    layout.free_repo(root_repo)+    bytes.free_owned(listen)+    bytes.free_owned(cert)+    bytes.free_owned(key)+    return code+}--- /dev/null+++ b/veins/src/cli/whoami_cmd.sx@@ -0,0 +1,105 @@+/// `vn whoami`: report the role and fingerprint granted by a server.++val stdio  = use("std/stdio")+val str    = use("std/string")+val bytes  = use("../core/bytes.sx")+val layout = use("../store/layout.sx")+val remote_config = use("../git/remote.sx")+val ed = use("../crypto/ed25519.sx")+val client = use("../protocol/client.sx")+val cmsg   = use("../core/msg.sx")++fn role_text(role: u8) bytes.Bytes = {+    if role == 2 {+        return bytes.bytes(c"write", 5)+    }+    if role == 1 {+        return bytes.bytes(c"read", 4)+    }+    return bytes.bytes(c"anonymous", 9)+}++pub fn run(args: list[ref u8], start: usize) i32 = trust {+    val arg_opt = @get(args, start)+    val remote: mut bytes.Bytes = bytes.Bytes.dup(bytes.bytes(c"origin", 6))+    val url: mut bytes.Bytes = bytes.empty()+    val key: mut bytes.Bytes = bytes.empty()+    val repo_name: mut bytes.Bytes = bytes.empty()+    val pin: mut bytes.Bytes = bytes.empty()+    if arg_opt is some a {+        val av: bytes.Bytes = bytes.from_cstr(a)+        if bytes.Bytes.starts_with(av, bytes.bytes(c"file://", 7))+        || bytes.Bytes.starts_with(av, bytes.bytes(c"ssh://", 6))+        || bytes.Bytes.starts_with(av, bytes.bytes(c"veins://", 8)) {+            url = bytes.Bytes.dup(av)+            repo_name = client.url_repo_name(url)+        } else {+            remote = bytes.Bytes.dup(av)+        }+    }+    if url.ptr == none {+        val repo_opt = layout.discover(str.from_cstr(c"."))+        if repo_opt is none {+            cmsg.error_prefix()+            stdio.eprint("not a veins repository\n", {})+            return 1+        }+        val repo: mut layout.Repo = layout.Repo{root: bytes.empty()}+        match repo_opt {+            some r => {+                repo = r+            }+            none => {+                return 1+            }+        }+        val u = remote_config.url_of(repo, remote)+        if u is none {+            cmsg.error_prefix()+            stdio.eprint("unknown remote\n", {})+            layout.free_repo(repo)+            return 1+        }+        match u {+            some v => {+                url = v+            }+            none => {+            }+        }+        val kn = remote_config.key_name_of(repo, remote)+        if kn is some k {+            key = k+        }+        val pn = remote_config.tls_pin_of(repo, remote)+        if pn is some pv {+            pin = pv+        }+        repo_name = client.url_repo_name(url)+        layout.free_repo(repo)+    }+    val w = client.whoami_pinned(url, key, repo_name, pin)+    if url.ptr != none {+        bytes.free_owned(url)+    }+    if key.ptr != none {+        bytes.free_owned(key)+    }+    if repo_name.ptr != none {+        bytes.free_owned(repo_name)+    }+    if remote.ptr != none {+        bytes.free_owned(remote)+    }+    if w is some v {+        stdio.print("role: {s}\n", {str.view(role_text(v.role).ptr, role_text(v.role).len as i64)})+        val fp_text: bytes.Bytes = ed.base32_text(v.fingerprint)+        stdio.print("fingerprint: {s}\n", {str.view(fp_text.ptr, fp_text.len as i64)})+        bytes.free_owned(fp_text)+        bytes.free_ptr(v.fingerprint.ptr)+        return 0+    }+    cmsg.error_prefix()+    stdio.eprint("cannot authenticate\n", {})+    return 1+}--- a/veins/src/core/bytes.sx+++ b/veins/src/core/bytes.sx@@ -138,4 +138,20 @@         i++     }     return true+}++/// Release an owned byte span (frees the pointer, not the descriptor).+pub fn free_owned(b: Bytes) void = {+    if b.ptr != none {+        val p: mut ref void = b.ptr as ref void+        trust @free(p)+    }+}++/// Free a raw owned pointer.+pub fn free_ptr(p: ref u8) void = {+    if p != none {+        val q: mut ref void = p as ref void+        trust @free(q)+    } }--- a/veins/src/core/repoconfig.sx+++ b/veins/src/core/repoconfig.sx@@ -5,6 +5,7 @@ /// owned byte spans; callers release them with `bytes.free`-style helpers.  val bytes  = use("bytes.sx")+val buf    = use("buf.sx") val str    = use("std/string") val layout = use("../store/layout.sx") val files  = use("../io/files.sx")@@ -118,4 +119,87 @@ /// Read a text key. The result is owned by the caller. pub fn get_text(repo: layout.Repo, key: bytes.Bytes) option[bytes.Bytes] = trust {     return get(repo, key)+}++/// Set a key, replacing an existing value. The file is rewritten atomically.+pub fn set(repo: layout.Repo, key: bytes.Bytes, value: bytes.Bytes) bool = trust {+    val path: str.StringView = layout.config_path(repo)+    val data_opt = files.read_all(path)+    val b: mut buf.Buf = buf.new(256)+    if data_opt is some d {+        val pos: mut usize = 0+        val start: mut usize = 0+        for pos <= d.len {+            if pos == d.len || bytes.Bytes.at(d, pos) == 10 {+                val line: bytes.Bytes = bytes.Bytes.slice(d, start, pos)+                val t: bytes.Bytes = trim(line)+                val eq: i64 = index_of(t, 61)+                val is_key: bool = eq >= 0 && bytes.Bytes.eql(trim(bytes.Bytes.slice(t, 0, eq as usize)), key)+                if !is_key {+                    buf.Buf.put_bytes(b, line)+                    if pos < d.len {+                        buf.Buf.put_u8(b, 10)+                    }+                }+                start = pos + 1+            }+            pos+++        }+        files.free_buffer(d)+    }+    buf.Buf.put_bytes(b, key)+    buf.Buf.put_raw(b, c" = " as ref u8, 3)+    buf.Buf.put_bytes(b, value)+    buf.Buf.put_u8(b, 10)+    val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+    buf.Buf.free(b)+    val passed: bool = files.write_all(path, out)+    files.free_buffer(out)+    files.free_path(path)+    return passed+}++fn index_of(b: bytes.Bytes, needle: u8) i64 = trust {+    val i: mut usize = 0+    for i < b.len {+        if bytes.Bytes.at(b, i) == needle {+            return i as i64+        }+        i+++    }+    return -1+}++/// Remove a key from the configuration.+pub fn remove(repo: layout.Repo, key: bytes.Bytes) bool = trust {+    val path: str.StringView = layout.config_path(repo)+    val data_opt = files.read_all(path)+    val b: mut buf.Buf = buf.new(256)+    if data_opt is some d {+        val pos: mut usize = 0+        val start: mut usize = 0+        for pos <= d.len {+            if pos == d.len || bytes.Bytes.at(d, pos) == 10 {+                val line: bytes.Bytes = bytes.Bytes.slice(d, start, pos)+                val t: bytes.Bytes = trim(line)+                val eq: i64 = index_of(t, 61)+                val is_key: bool = eq >= 0 && bytes.Bytes.eql(trim(bytes.Bytes.slice(t, 0, eq as usize)), key)+                if !is_key {+                    buf.Buf.put_bytes(b, line)+                    if pos < d.len {+                        buf.Buf.put_u8(b, 10)+                    }+                }+                start = pos + 1+            }+            pos+++        }+        files.free_buffer(d)+    }+    val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+    buf.Buf.free(b)+    val passed: bool = files.write_all(path, out)+    files.free_buffer(out)+    files.free_path(path)+    return passed }--- /dev/null+++ b/veins/src/crypto/ed25519.sx@@ -0,0 +1,266 @@+/// Ed25519 signatures, key encoding, and fingerprints.+///+/// The primitives are provided by OpenSSL through the native shim.++val bytes = use("../core/bytes.sx")+val b3    = use("blake3.sx")++pub val SEED_LEN: usize = 32+pub val PUBLIC_LEN: usize = 32+pub val SIGNATURE_LEN: usize = 64+pub val FINGERPRINT_LEN: usize = 16++extern (C) fn vn_ed25519_public_from_seed(seed: ref u8, public_out: ref u8) i32 =+    "vn_ed25519_public_from_seed"+extern (C) fn vn_ed25519_sign(+    seed: ref u8,+    msg: ref u8,+    msg_len: usize,+    sig: ref u8+) i32 = "vn_ed25519_sign"+extern (C) fn vn_ed25519_verify(+    public_key: ref u8,+    msg: ref u8,+    msg_len: usize,+    sig: ref u8+) i32 = "vn_ed25519_verify"++pub fn public_from_seed(seed: bytes.Bytes) option[bytes.Bytes] = trust {+    if seed.len != SEED_LEN {+        return none+    }+    val out: ref u8 = @alloc(PUBLIC_LEN) as ref u8+    if vn_ed25519_public_from_seed(seed.ptr, out) != 1 {+        @free(out as ref void)+        return none+    }+    return some bytes.bytes(out, PUBLIC_LEN)+}++pub fn sign(seed: bytes.Bytes, msg: bytes.Bytes) option[bytes.Bytes] = trust {+    if seed.len != SEED_LEN {+        return none+    }+    val out: ref u8 = @alloc(SIGNATURE_LEN) as ref u8+    if vn_ed25519_sign(seed.ptr, msg.ptr, msg.len, out) != 1 {+        @free(out as ref void)+        return none+    }+    return some bytes.bytes(out, SIGNATURE_LEN)+}++pub fn verify(public_key: bytes.Bytes, msg: bytes.Bytes, sig: bytes.Bytes) bool = trust {+    if public_key.len != PUBLIC_LEN || sig.len != SIGNATURE_LEN {+        return false+    }+    return vn_ed25519_verify(public_key.ptr, msg.ptr, msg.len, sig.ptr) == 1+}++fn alphabet() ref u8 = {+    return c"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"+}++/// The raw 16-byte fingerprint for a public key.+pub fn fingerprint_bytes(public_key: bytes.Bytes) option[bytes.Bytes] = trust {+    if public_key.len != PUBLIC_LEN {+        return none+    }+    val input: ref u8 = @alloc(12 + PUBLIC_LEN) as ref u8+    @memcpy(input as ref void, c"veins/key/1", 12)+    @memcpy(@ptradd(input, 12) as ref void, public_key.ptr as ref void, PUBLIC_LEN)+    val digest: ref u8 = @alloc(32) as ref u8+    b3.hash(input, 12 + PUBLIC_LEN, digest)+    @free(input as ref void)+    val out: ref u8 = @alloc(FINGERPRINT_LEN) as ref u8+    @memcpy(out as ref void, digest as ref void, FINGERPRINT_LEN)+    @free(digest as ref void)+    return some bytes.bytes(out, FINGERPRINT_LEN)+}++/// The 26-character lowercase base32 fingerprint, NUL terminated.+pub fn fingerprint(public_key: bytes.Bytes) option[bytes.Bytes] = trust {+    val raw_opt = fingerprint_bytes(public_key)+    val raw: mut bytes.Bytes = bytes.empty()+    match raw_opt {+        some r => {+            raw = r+        }+        none => {+            return none+        }+    }+    val out: ref u8 = @alloc(27) as ref u8+    val bits: mut u64 = 0+    val nbits: mut usize = 0+    val oi: mut usize = 0+    val ri: mut usize = 0+    for ri < raw.len {+        val b: u8 = bytes.Bytes.at(raw, ri)+        bits = (bits << 8) | (b as u64)+        nbits = nbits + 8+        for nbits >= 5 {+            nbits = nbits - 5+            val idx: usize = ((bits >> (nbits as u64)) & 31) as usize+            @store8(@ptradd(out, oi as i64), @load8(@ptradd(alphabet(), idx as i64)))+            oi+++        }+        ri+++    }+    if nbits > 0 {+        val idx2: usize = ((bits << (5 - nbits)) & 31) as usize+        @store8(@ptradd(out, oi as i64), @load8(@ptradd(alphabet(), idx2 as i64)))+        oi+++    }+    @store8(@ptradd(out, oi as i64), 0)+    bytes.free_owned(raw)+    return some bytes.bytes(out, oi)+}++fn b64_value(c: u8) i32 = {+    if c >= 65 && c <= 90 {+        return (c - 65) as i32+    }+    if c >= 97 && c <= 122 {+        return (c - 71) as i32+    }+    if c >= 48 && c <= 57 {+        return (c + 4) as i32+    }+    if c == 45 {+        return 62+    }+    if c == 95 {+        return 63+    }+    return -1+}++fn b64_char(v: u8) u8 = {+    if v < 26 {+        return (65 + v) as u8+    }+    if v < 52 {+        return (97 + v - 26) as u8+    }+    if v < 62 {+        return (48 + v - 52) as u8+    }+    if v == 62 {+        return 45+    }+    return 95+}++/// Decode unpadded base64url. The result is owned by the caller.+pub fn base64url_decode(text: bytes.Bytes) option[bytes.Bytes] = trust {+    if text.len == 0 {+        return none+    }+    val out: ref u8 = @alloc(text.len + 1) as ref u8+    val acc: mut u32 = 0+    val bits: mut usize = 0+    val oi: mut usize = 0+    val i: mut usize = 0+    for i < text.len {+        val v: i32 = b64_value(bytes.Bytes.at(text, i))+        if v < 0 {+            @free(out as ref void)+            return none+        }+        acc = (acc << 6) | (v as u32)+        bits = bits + 6+        if bits >= 8 {+            bits = bits - 8+            @store8(@ptradd(out, oi as i64), ((acc >> (bits as u32)) & 255) as u8)+            oi+++        }+        i+++    }+    return some bytes.bytes(out, oi)+}++/// Encode as unpadded base64url. The result is owned by the caller.+pub fn base64url_encode(data: bytes.Bytes) bytes.Bytes = trust {+    val out: ref u8 = @alloc((data.len * 4) / 3 + 5) as ref u8+    val acc: mut u32 = 0+    val bits: mut usize = 0+    val oi: mut usize = 0+    val di: mut usize = 0+    for di < data.len {+        val b: u8 = bytes.Bytes.at(data, di)+        acc = (acc << 8) | (b as u32)+        bits = bits + 8+        for bits >= 6 {+            bits = bits - 6+            @store8(@ptradd(out, oi as i64), b64_char(((acc >> (bits as u32)) & 63) as u8))+            oi+++        }+        di+++    }+    if bits > 0 {+        @store8(@ptradd(out, oi as i64), b64_char(((acc << (6 - bits)) & 63) as u8))+        oi+++    }+    @store8(@ptradd(out, oi as i64), 0)+    return bytes.bytes(out, oi)+}++/// Parse `ed25519:<base64url>` into raw public key bytes.+pub fn parse_public(text: bytes.Bytes) option[bytes.Bytes] = trust {+    val prefix: bytes.Bytes = bytes.bytes(c"ed25519:", 8)+    if !bytes.Bytes.starts_with(text, prefix) {+        return none+    }+    val encoded: bytes.Bytes = bytes.Bytes.slice(text, 8, text.len)+    val decoded = base64url_decode(encoded)+    match decoded {+        some raw => {+            if raw.len != PUBLIC_LEN {+                bytes.free_owned(raw)+                return none+            }+            return some raw+        }+        none => {+            return none+        }+    }+}++/// Render a public key as `ed25519:<base64url>`. The result is owned.+pub fn format_public(public_key: bytes.Bytes) bytes.Bytes = trust {+    val enc: bytes.Bytes = base64url_encode(public_key)+    val out: ref u8 = @alloc(8 + enc.len) as ref u8+    @memcpy(out as ref void, c"ed25519:", 8)+    @memcpy(@ptradd(out, 8) as ref void, enc.ptr as ref void, enc.len)+    bytes.free_owned(enc)+    return bytes.bytes(out, 8 + enc.len)+}++/// Lowercase unpadded base32 text for raw bytes. The result is owned.+pub fn base32_text(raw: bytes.Bytes) bytes.Bytes = trust {+    val out: ref u8 = @alloc((raw.len * 8) / 5 + 4) as ref u8+    val bits: mut u64 = 0+    val nbits: mut usize = 0+    val oi: mut usize = 0+    val ri: mut usize = 0+    for ri < raw.len {+        val b: u8 = bytes.Bytes.at(raw, ri)+        bits = (bits << 8) | (b as u64)+        nbits = nbits + 8+        for nbits >= 5 {+            nbits = nbits - 5+            val idx: usize = ((bits >> (nbits as u64)) & 31) as usize+            @store8(@ptradd(out, oi as i64), @load8(@ptradd(alphabet(), idx as i64)))+            oi+++        }+        ri+++    }+    if nbits > 0 {+        val idx2: usize = ((bits << (5 - nbits)) & 31) as usize+        @store8(@ptradd(out, oi as i64), @load8(@ptradd(alphabet(), idx2 as i64)))+        oi+++    }+    @store8(@ptradd(out, oi as i64), 0)+    return bytes.bytes(out, oi)+}--- /dev/null+++ b/veins/src/crypto/openssl_c.c@@ -0,0 +1,205 @@+/* OpenSSL-backed primitives for veins: Ed25519, TLS 1.3, and TCP connect. */++#include <stddef.h>+#include <stdint.h>+#include <string.h>+#include <stdio.h>++#include <openssl/evp.h>+#include <openssl/ssl.h>+#include <openssl/err.h>+#include <openssl/x509.h>++#include <sys/types.h>+#include <sys/socket.h>+#include <netdb.h>+#include <unistd.h>+#include <sys/stat.h>++int vn_ed25519_public_from_seed(const unsigned char *seed, unsigned char *pub) {+    EVP_PKEY *pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, NULL, seed, 32);+    if (!pkey) return 0;+    size_t len = 32;+    int ok = EVP_PKEY_get_raw_public_key(pkey, pub, &len);+    EVP_PKEY_free(pkey);+    return ok == 1 && len == 32;+}++int vn_ed25519_sign(const unsigned char *seed, const unsigned char *msg,+                    size_t msg_len, unsigned char *sig) {+    EVP_PKEY *pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, NULL, seed, 32);+    if (!pkey) return 0;+    EVP_MD_CTX *ctx = EVP_MD_CTX_new();+    if (!ctx) { EVP_PKEY_free(pkey); return 0; }+    int ok = 0;+    size_t sig_len = 64;+    if (EVP_DigestSignInit(ctx, NULL, NULL, NULL, pkey) == 1) {+        if (EVP_DigestSign(ctx, sig, &sig_len, msg, msg_len) == 1 && sig_len == 64) ok = 1;+    }+    EVP_MD_CTX_free(ctx);+    EVP_PKEY_free(pkey);+    return ok;+}++int vn_ed25519_verify(const unsigned char *pub, const unsigned char *msg,+                      size_t msg_len, const unsigned char *sig) {+    EVP_PKEY *pkey = EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519, NULL, pub, 32);+    if (!pkey) return 0;+    EVP_MD_CTX *ctx = EVP_MD_CTX_new();+    if (!ctx) { EVP_PKEY_free(pkey); return 0; }+    int ok = 0;+    if (EVP_DigestVerifyInit(ctx, NULL, NULL, NULL, pkey) == 1) {+        if (EVP_DigestVerify(ctx, sig, 64, msg, msg_len) == 1) ok = 1;+    }+    EVP_MD_CTX_free(ctx);+    EVP_PKEY_free(pkey);+    return ok;+}++static void vn_ssl_error(char *err, size_t cap) {+    if (!err || cap == 0) {+        ERR_clear_error();+        return;+    }+    unsigned long code = ERR_get_error();+    if (code == 0) {+        if (cap > 0) err[0] = 0;+        return;+    }+    ERR_error_string_n(code, err, cap);+}++void *vn_tls_server_ctx(const char *cert, const char *key) {+    SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());+    if (!ctx) return NULL;+    if (SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION) != 1) goto fail;+    if (SSL_CTX_use_certificate_chain_file(ctx, cert) != 1) goto fail;+    if (SSL_CTX_use_PrivateKey_file(ctx, key, SSL_FILETYPE_PEM) != 1) goto fail;+    if (SSL_CTX_check_private_key(ctx) != 1) goto fail;+    return ctx;+fail:+    SSL_CTX_free(ctx);+    return NULL;+}++void *vn_tls_client_ctx(void) {+    SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());+    if (!ctx) return NULL;+    if (SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION) != 1) {+        SSL_CTX_free(ctx);+        return NULL;+    }+    SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);+    if (SSL_CTX_set_default_verify_paths(ctx) != 1) {+        SSL_CTX_free(ctx);+        return NULL;+    }+    return ctx;+}++void *vn_tls_client_ctx_pinned(void) {+    SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());+    if (!ctx) return NULL;+    if (SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION) != 1) {+        SSL_CTX_free(ctx);+        return NULL;+    }+    SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);+    return ctx;+}++void *vn_tls_accept(void *ctx, int fd, char *err, size_t err_cap) {+    SSL *ssl = SSL_new((SSL_CTX *)ctx);+    if (!ssl) { vn_ssl_error(err, err_cap); return NULL; }+    SSL_set_fd(ssl, fd);+    if (SSL_accept(ssl) != 1) {+        vn_ssl_error(err, err_cap);+        SSL_free(ssl);+        return NULL;+    }+    return ssl;+}++void *vn_tls_connect(void *ctx, int fd, const char *host, char *err, size_t err_cap) {+    SSL *ssl = SSL_new((SSL_CTX *)ctx);+    if (!ssl) { vn_ssl_error(err, err_cap); return NULL; }+    SSL_set_fd(ssl, fd);+    if (host && host[0]) {+        SSL_set_tlsext_host_name(ssl, host);+        SSL_set1_host(ssl, host);+    }+    if (SSL_connect(ssl) != 1) {+        vn_ssl_error(err, err_cap);+        SSL_free(ssl);+        return NULL;+    }+    return ssl;+}++long vn_tls_read(void *ssl, void *buf, size_t len) {+    int n = SSL_read((SSL *)ssl, buf, (int)len);+    if (n <= 0) return -1;+    return n;+}++long vn_tls_write(void *ssl, const void *buf, size_t len) {+    int n = SSL_write((SSL *)ssl, buf, (int)len);+    if (n <= 0) return -1;+    return n;+}++int vn_tls_exporter(void *ssl, unsigned char *out, size_t len) {+    static const char label[] = "EXPORTER-veins-auth/1";+    return SSL_export_keying_material((SSL *)ssl, out, len, label,+                                      sizeof(label) - 1, NULL, 0, 0) == 1;+}++int vn_tls_peer_sha256(void *ssl, unsigned char out[32]) {+    X509 *cert = SSL_get1_peer_certificate((SSL *)ssl);+    if (!cert) return 0;+    unsigned int len = 0;+    int ok = X509_digest(cert, EVP_sha256(), out, &len) == 1 && len == 32;+    X509_free(cert);+    return ok;+}++void vn_tls_free(void *ssl) {+    if (!ssl) return;+    SSL_shutdown((SSL *)ssl);+    SSL_free((SSL *)ssl);+}++void vn_tls_ctx_free(void *ctx) {+    if (ctx) SSL_CTX_free((SSL_CTX *)ctx);+}++int vn_tcp_connect(const char *host, int port) {+    struct addrinfo hints;+    struct addrinfo *res = NULL;+    char service[16];+    memset(&hints, 0, sizeof(hints));+    hints.ai_family = AF_UNSPEC;+    hints.ai_socktype = SOCK_STREAM;+    snprintf(service, sizeof(service), "%d", port);+    if (getaddrinfo(host, service, &hints, &res) != 0) return -1;+    int fd = -1;+    for (struct addrinfo *it = res; it != NULL; it = it->ai_next) {+        fd = socket(it->ai_family, it->ai_socktype, it->ai_protocol);+        if (fd < 0) continue;+        if (connect(fd, it->ai_addr, it->ai_addrlen) == 0) break;+        close(fd);+        fd = -1;+    }+    freeaddrinfo(res);+    return fd;+}++int vn_file_mode(const char *path) {+    struct stat st;+    if (stat(path, &st) != 0) return -1;+    return (int)(st.st_mode & 07777);+}++int vn_chmod(const char *path, int mode) {+    return chmod(path, (mode_t)mode);+}--- /dev/null+++ b/veins/src/crypto/tls.sx@@ -0,0 +1,140 @@+/// TLS 1.3 transport and TCP connection helpers backed by OpenSSL.++val bytes = use("../core/bytes.sx")++pub val ERR_CAP: usize = 256++extern (C) fn vn_tls_server_ctx(cert: ref u8, key: ref u8) ref void = "vn_tls_server_ctx"+extern (C) fn vn_tls_client_ctx() ref void = "vn_tls_client_ctx"+extern (C) fn vn_tls_client_ctx_pinned() ref void = "vn_tls_client_ctx_pinned"+extern (C) fn vn_tls_accept(+    ctx: ref void,+    fd: i32,+    errbuf: ref u8,+    errcap: usize+) ref void = "vn_tls_accept"+extern (C) fn vn_tls_connect(+    ctx: ref void,+    fd: i32,+    host: ref u8,+    errbuf: ref u8,+    errcap: usize+) ref void = "vn_tls_connect"+extern (C) fn vn_tls_read(ssl: ref void, buf: ref void, len: usize) i64 = "vn_tls_read"+extern (C) fn vn_tls_write(ssl: ref void, buf: ref void, len: usize) i64 = "vn_tls_write"+extern (C) fn vn_tls_exporter(ssl: ref void, out: ref u8, len: usize) i32 =+    "vn_tls_exporter"+extern (C) fn vn_tls_peer_sha256(ssl: ref void, out: ref u8) i32 = "vn_tls_peer_sha256"+extern (C) fn vn_tls_free(ssl: ref void) void = "vn_tls_free"+extern (C) fn vn_tls_ctx_free(ctx: ref void) void = "vn_tls_ctx_free"+extern (C) fn vn_tcp_connect(host: ref u8, port: i32) i32 = "vn_tcp_connect"+extern (C) fn vn_file_mode(path: ref u8) i32 = "vn_file_mode"+extern (C) fn vn_chmod(path: ref u8, mode: i32) i32 = "vn_chmod"++pub type Conn = {+    fd: mut i32+    ssl: mut ref void+    secure: mut bool+}++pub fn server_ctx(cert: ref u8, key: ref u8) ref void = trust {+    return vn_tls_server_ctx(cert, key)+}++pub fn client_ctx() ref void = trust {+    return vn_tls_client_ctx()+}++pub fn client_ctx_pinned() ref void = trust {+    return vn_tls_client_ctx_pinned()+}++pub fn accept(ctx: ref void, fd: i32) ref void = trust {+    return vn_tls_accept(ctx, fd, none, 0)+}++pub fn connect(ctx: ref void, fd: i32, host: ref u8) ref void = trust {+    return vn_tls_connect(ctx, fd, host, none, 0)+}++pub fn read(ssl: ref void, buf: ref u8, n: usize) i64 = trust {+    return vn_tls_read(ssl, buf as ref void, n)+}++pub fn write(ssl: ref void, buf: ref u8, n: usize) i64 = trust {+    return vn_tls_write(ssl, buf as ref void, n)+}++pub fn exporter(ssl: ref void, out: ref u8, n: usize) bool = trust {+    return vn_tls_exporter(ssl, out, n) == 1+}++pub fn peer_sha256(ssl: ref void, out: ref u8) bool = trust {+    return vn_tls_peer_sha256(ssl, out) == 1+}++pub fn free(ssl: ref void) void = trust {+    vn_tls_free(ssl)+}++pub fn free_ctx(ctx: ref void) void = trust {+    vn_tls_ctx_free(ctx)+}++pub fn tcp_connect(host: ref u8, port: i32) i32 = trust {+    return vn_tcp_connect(host, port)+}++pub fn file_mode(path: ref u8) i32 = trust {+    return vn_file_mode(path)+}++pub fn chmod(path: ref u8, mode: i32) i32 = trust {+    return vn_chmod(path, mode)+}++pub fn to_hex(data: bytes.Bytes) bytes.Bytes = trust {+    val out: ref u8 = @alloc(data.len * 2 + 1) as ref u8+    val hex: ref u8 = c"0123456789abcdef"+    val i: mut usize = 0+    for i < data.len {+        val v: u8 = bytes.Bytes.at(data, i)+        @store8(@ptradd(out, (i * 2) as i64), @load8(@ptradd(hex, ((v >> 4) as i64))))+        @store8(@ptradd(out, (i * 2 + 1) as i64), @load8(@ptradd(hex, ((v & 15) as i64))))+        i+++    }+    @store8(@ptradd(out, (data.len * 2) as i64), 0)+    return bytes.bytes(out, data.len * 2)+}++/// Compare two hex digests, ignoring colons and case.+pub fn hex_equal(a: bytes.Bytes, b: bytes.Bytes) bool = trust {+    val ai: mut usize = 0+    val bi: mut usize = 0+    for {+        for ai < a.len && bytes.Bytes.at(a, ai) == 58 {+            ai+++        }+        for bi < b.len && bytes.Bytes.at(b, bi) == 58 {+            bi+++        }+        if ai >= a.len || bi >= b.len {+            return ai >= a.len && bi >= b.len+        }+        val ca: u8 = lower(bytes.Bytes.at(a, ai))+        val cb: u8 = lower(bytes.Bytes.at(b, bi))+        if ca != cb {+            return false+        }+        ai+++        bi+++    }+    return true+}++fn lower(c: u8) u8 = {+    if c >= 65 && c <= 90 {+        return (c + 32) as u8+    }+    return c+}--- a/veins/src/git/export.sx+++ b/veins/src/git/export.sx@@ -687,7 +687,7 @@         val o = @get(all_ids, i0)         if o is some id {             val m: mut ref Mark = @alloc(@sizeof(Mark)) as ref Mark-            m.id = id+            m.id = copy_id(id)             m.expanded = false             @append(stack, m)         }@@ -696,6 +696,9 @@     for @len(stack) > 0 {         val m: mut ref Mark = @remove(stack, @len(stack) - 1)         if contains(visited, m.id) {+            if m.id.ptr != none {+                @free(m.id.ptr as ref void)+            }             @free(m as ref void)             continue         }@@ -722,6 +725,9 @@         } else {             @append(visited, copy_id(m.id))             @append(ordered, copy_id(m.id))+            if m.id.ptr != none {+                @free(m.id.ptr as ref void)+            }             @free(m as ref void)         }     }@@ -886,6 +892,7 @@     val blobs: mut oidmap.OidMap = oidmap.new(64)     match commits_opt {         ok m => {+            oidmap.free(commits)             commits = m         }         err _ => {@@ -893,6 +900,7 @@     }     match trees_opt {         ok m => {+            oidmap.free(trees)             trees = m         }         err _ => {@@ -900,6 +908,7 @@     }     match blobs_opt {         ok m => {+            oidmap.free(blobs)             blobs = m         }         err _ => {--- a/veins/src/git/format.sx+++ b/veins/src/git/format.sx@@ -421,6 +421,10 @@ }  pub fn free_parsed_commit(c: ref ParsedCommit) void = trust {+    if c.tree.ptr != none {+        val tp: mut ref void = c.tree.ptr as ref void+        @free(tp)+    }     for p in c.parents {         if p.ptr != none {             val pp: mut ref void = p.ptr as ref void--- a/veins/src/git/import.sx+++ b/veins/src/git/import.sx@@ -186,7 +186,7 @@     val id: objid.Id = lazy.blob_id(oid)     put_id(ctx.blobs_map, oid, id)     ctx.new_blobs++-    return some dup_id(id)+    return some id }  fn import_tree(ctx: mut ImportCtx, oid: bytes.Bytes) option[objid.Id] = trust {@@ -312,10 +312,9 @@         rsave.body = copy         @append(ctx.raw_saves, rsave)     }-    val out2: objid.Id = dup_id(id)     format.free_parsed_tree(parsed)     object.free_object(obj)-    return some out2+    return some id }  fn add_branch_target(@@ -436,6 +435,98 @@     t.name = bytes.Bytes.dup(name)     t.target = id     @append(v.tags, t)+}++fn set_remote_ref(+    v: mut ref view.View,+    remote: bytes.Bytes,+    name: bytes.Bytes,+    id: objid.Id+) void = trust {+    val i: mut usize = 0+    for i < @len(v.remote_refs) {+        val o = @get(v.remote_refs, i)+        if o is some rr {+            if bytes.Bytes.eql(rr.remote, remote) && bytes.Bytes.eql(rr.name, name) {+                rr.target = id+                return+            }+        }+        i+++    }+    val rr: mut ref view.RemoteRef = @alloc(@sizeof(view.RemoteRef)) as ref view.RemoteRef+    rr.remote = bytes.Bytes.dup(remote)+    rr.name = bytes.Bytes.dup(name)+    rr.target = id+    @append(v.remote_refs, rr)+}++fn sort_remote_refs(xs: mut list[ref view.RemoteRef]) void = trust {+    val n: usize = @len(xs)+    val i: mut usize = 1+    for i < n {+        val cur = @get(xs, i)+        val c: mut ref view.RemoteRef = none+        if cur is some v {+            c = v+        }+        val j: mut usize = i+        for j > 0 {+            val prev_opt = @get(xs, j - 1)+            val prev: mut ref view.RemoteRef = none+            if prev_opt is some v2 {+                prev = v2+            }+            val cmp: i64 = bytes.Bytes.cmp(prev.remote, c.remote)+            val ord: mut i64 = cmp+            if cmp == 0 {+                ord = bytes.Bytes.cmp(prev.name, c.name)+            }+            if ord <= 0 {+                break+            }+            @set(xs, j, prev)+            j--+        }+        @set(xs, j, c)+        i+++    }+}++fn var_has_bookmark(v: mut ref view.View, name: bytes.Bytes, id: objid.Id) void = trust {+    val i: mut usize = 0+    for i < @len(v.bookmarks) {+        val o = @get(v.bookmarks, i)+        if o is some bm {+            if bytes.Bytes.eql(bm.name, name) {+                return+            }+        }+        i+++    }+    set_bookmark(v, name, id)+}++type RemoteSplit = {+    remote: mut bytes.Bytes+    name: mut bytes.Bytes+}++fn split_remote(full: bytes.Bytes) RemoteSplit = trust {+    val i: mut usize = 0+    for i < full.len {+        if bytes.Bytes.at(full, i) == 47 {+            return RemoteSplit{+                remote: bytes.Bytes.slice(full, 0, i),+                name: bytes.Bytes.slice(full, i + 1, full.len)+            }+        }+        i+++    }+    return RemoteSplit{+        remote: bytes.Bytes.dup(full),+        name: bytes.Bytes.dup(bytes.bytes(c"main", 4))+    } }  fn set_workspace(v: mut ref view.View, name: bytes.Bytes, id: objid.Id) void = trust {@@ -456,30 +547,56 @@     @append(v.working_copies, w) } -fn clear_view_view(v: mut ref view.View) void = trust {+fn clear_view_view(v: mut ref view.View, free_names: bool) void = trust {     @listfree(v.heads)     for bm in v.bookmarks {         @listfree(bm.targets.adds)         @listfree(bm.targets.removes)+        if free_names && bm.name.ptr != none {+            val np: mut ref void = bm.name.ptr as ref void+            @free(np)+        }         val bp: mut ref void = bm as ref void         @free(bp)     }     @listfree(v.bookmarks)     for t in v.tags {+        if free_names && t.name.ptr != none {+            val np: mut ref void = t.name.ptr as ref void+            @free(np)+        }         val tp: mut ref void = t as ref void         @free(tp)     }     @listfree(v.tags)     for rr in v.remote_refs {-        val rp: mut ref void = rr as ref void-        @free(rp)+        if free_names {+            if rr.remote.ptr != none {+                val rp: mut ref void = rr.remote.ptr as ref void+                @free(rp)+            }+            if rr.name.ptr != none {+                val np: mut ref void = rr.name.ptr as ref void+                @free(np)+            }+        }+        val rp2: mut ref void = rr as ref void+        @free(rp2)     }     @listfree(v.remote_refs)     for w in v.working_copies {+        if free_names && w.workspace.ptr != none {+            val wp2: mut ref void = w.workspace.ptr as ref void+            @free(wp2)+        }         val wp: mut ref void = w as ref void         @free(wp)     }     @listfree(v.working_copies)+    if v.owned.ptr != none {+        val ob: mut ref void = v.owned.ptr as ref void+        @free(ob)+    }     @free(v as ref void) } @@ -579,6 +696,7 @@     val maps_ok: mut bool = true     match commits_map_opt {         ok m => {+            oidmap.free(commits_map)             commits_map = m         }         err _ => {@@ -587,6 +705,7 @@     }     match trees_map_opt {         ok m2 => {+            oidmap.free(trees_map)             trees_map = m2         }         err _ => {@@ -595,6 +714,7 @@     }     match blobs_map_opt {         ok m3 => {+            oidmap.free(blobs_map)             blobs_map = m3         }         err _ => {@@ -640,6 +760,7 @@      val branches: mut list[ref ImportNamedTarget] = lists.new[ref ImportNamedTarget]()     val tags: mut list[ref ImportNamedTarget] = lists.new[ref ImportNamedTarget]()+    val remotes: mut list[ref ImportNamedTarget] = lists.new[ref ImportNamedTarget]()     val tips: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()     for b in refset.branches {         val peeled = peel_to_commit(ctx.git, b.oid)@@ -653,6 +774,13 @@         if peeled2 is some c2 {             add_branch_target(tags, t.name, c2)             @append(tips, bytes.Bytes.dup(c2))+        }+    }+    for rr in refset.remotes {+        val peeled3 = peel_to_commit(ctx.git, rr.oid)+        if peeled3 is some c3 {+            add_branch_target(remotes, rr.name, c3)+            @append(tips, bytes.Bytes.dup(c3))         }     }     val head_commit: mut option[bytes.Bytes] = none@@ -829,11 +957,13 @@         free_commit_records(records)         free_named_targets(branches)         free_named_targets(tags)+        free_named_targets(remotes)         if head_commit is some h2 {             val hp: mut ref void = h2.ptr as ref void             @free(hp)         }         refs.free(refset)+        writer.abort(ctx.writer)         free_raw_saves(ctx.raw_saves)         oidmap.free(ctx.commits_map)         oidmap.free(ctx.trees_map)@@ -945,6 +1075,10 @@         if cid.ptr != none && rec.parsed.change_id.ptr == none {             val cp5: mut ref void = cid.ptr as ref void             @free(cp5)+        }+        if cid_out.ptr != none {+            val co: mut ref void = cid_out.ptr as ref void+            @free(co)         }         oi++     }@@ -962,11 +1096,13 @@         free_commit_records(records)         free_named_targets(branches)         free_named_targets(tags)+        free_named_targets(remotes)         if head_commit is some h3 {             val hp2: mut ref void = h3.ptr as ref void             @free(hp2)         }         refs.free(refset)+        writer.abort(ctx.writer)         free_raw_saves(ctx.raw_saves)         oidmap.free(ctx.commits_map)         oidmap.free(ctx.trees_map)@@ -981,11 +1117,13 @@         free_commit_records(records)         free_named_targets(branches)         free_named_targets(tags)+        free_named_targets(remotes)         if head_commit is some h4 {             val hp3: mut ref void = h4.ptr as ref void             @free(hp3)         }         refs.free(refset)+        writer.abort(ctx.writer)         free_raw_saves(ctx.raw_saves)         oidmap.free(ctx.commits_map)         oidmap.free(ctx.trees_map)@@ -999,9 +1137,11 @@     val current = state.current_view(repo, store_handle.handles)     val v: mut ref view.View = none     val old_encoded: mut bytes.Bytes = bytes.empty()+    val view_from_store: mut bool = false     match current {         some cv => {             v = cv+            view_from_store = true             old_encoded = view.encode(v)         }         none => {@@ -1019,10 +1159,19 @@         val id = get_id(ctx.commits_map, t.oid)         if id is some tid {             set_tag(v, t.name, tid)+        }+    }+    for r in remotes {+        val id = get_id(ctx.commits_map, r.oid)+        if id is some rid {+            val parts = split_remote(r.name)+            set_remote_ref(v, parts.remote, parts.name, rid)+            var_has_bookmark(v, parts.name, rid)         }     }     sort_bookmarks(v.bookmarks)     sort_tags(v.tags)+    sort_remote_refs(v.remote_refs)      @listfree(v.heads)     val new_heads: mut list[objid.Id] = lists.new[objid.Id]()@@ -1030,6 +1179,12 @@         val id = get_id(ctx.commits_map, b.oid)         if id is some bid {             add_unique_head(new_heads, bid)+        }+    }+    for r in remotes {+        val id = get_id(ctx.commits_map, r.oid)+        if id is some rid {+            add_unique_head(new_heads, rid)         }     }     if @len(new_heads) == 0 {@@ -1073,15 +1228,17 @@             val np: mut ref void = new_encoded.ptr as ref void             @free(np)         }-        clear_view_view(v)+        clear_view_view(v, !view_from_store)         free_commit_records(records)         free_named_targets(branches)         free_named_targets(tags)+        free_named_targets(remotes)         if head_commit is some h5 {             val hp4: mut ref void = h5.ptr as ref void             @free(hp4)         }         refs.free(refset)+        writer.abort(ctx.writer)         free_raw_saves(ctx.raw_saves)         oidmap.free(ctx.commits_map)         oidmap.free(ctx.trees_map)@@ -1118,10 +1275,16 @@     op.username = username     op.description = bytes.bytes(c"git import", 10)     op.tags = op_tags+    op.owned = bytes.empty()     val op_body: bytes.Bytes = operation.encode(op)     val op_id: objid.Id = append_object(ctx, types.OPERATION, op_body)     @listfree(op.tags)+    @free(cmd_kv as ref void)     @free(op as ref void)+    if view_id.ptr != none {+        val vp: mut ref void = view_id.ptr as ref void+        @free(vp)+    }     if hostname.ptr != none {         val hp5: mut ref void = hostname.ptr as ref void         @free(hp5)@@ -1139,7 +1302,7 @@             val op2: mut ref void = old_encoded.ptr as ref void             @free(op2)         }-        clear_view_view(v)+        clear_view_view(v, !view_from_store)         for ph2 in op_parents {             if ph2.ptr != none {                 val pp: mut ref void = ph2.ptr as ref void@@ -1150,9 +1313,14 @@         free_commit_records(records)         free_named_targets(branches)         free_named_targets(tags)+        free_named_targets(remotes)         if head_commit is some h6 {             val hp6: mut ref void = h6.ptr as ref void             @free(hp6)+        }+        if op_id.ptr != none {+            val oip: mut ref void = op_id.ptr as ref void+            @free(oip)         }         refs.free(refset)         free_raw_saves(ctx.raw_saves)@@ -1193,7 +1361,7 @@         val op3: mut ref void = old_encoded.ptr as ref void         @free(op3)     }-    clear_view_view(v)+    clear_view_view(v, !view_from_store)     for ph4 in op_parents {         if ph4.ptr != none {             val pp2: mut ref void = ph4.ptr as ref void@@ -1204,9 +1372,14 @@     free_commit_records(records)     free_named_targets(branches)     free_named_targets(tags)+        free_named_targets(remotes)     if head_commit is some h7 {         val hp7: mut ref void = h7.ptr as ref void         @free(hp7)+    }+    if op_id.ptr != none {+        val oip2: mut ref void = op_id.ptr as ref void+        @free(oip2)     }     refs.free(refset)     free_raw_saves(ctx.raw_saves)--- a/veins/src/git/object.sx+++ b/veins/src/git/object.sx@@ -4,7 +4,6 @@ /// and v2 pack indexes. The importer uses this instead of shelling out to git.  link "-lz"-lib "crypto"  val str   = use("std/string") val bytes = use("../core/bytes.sx")--- a/veins/src/git/refs.sx+++ b/veins/src/git/refs.sx@@ -13,6 +13,7 @@ pub type RefSet = {     branches: mut list[ref Ref]     tags: mut list[ref Ref]+    remotes: mut list[ref Ref]     head: mut bytes.Bytes } @@ -94,6 +95,10 @@         val o = @get(refs, i)         if o is some r {             if bytes.Bytes.eql(r.name, name) {+                if r.oid.ptr != none {+                    val old: mut ref void = r.oid.ptr as ref void+                    @free(old)+                }                 r.oid = oid                 return             }@@ -181,8 +186,9 @@             if content_opt is some content {                 val oid_opt = parse_hex_oid(content)                 if oid_opt is some oid {-                    replace_ref(refs, bytes.Bytes.dup(bytes.from_cstr(child_rel.ptr)), oid)+                    replace_ref(refs, bytes.from_cstr(child_rel.ptr), oid)                 }+                files.free_buffer(content)             }         }         files.free_path(child_rel)@@ -254,8 +260,12 @@     val tags_base: str.StringView = files.join(git_dir, str.from_cstr(c"refs/tags"))     read_ref_dir(tags_base, str.view(none, 0), tags)     files.free_path(tags_base)+    val remotes: mut list[ref Ref] = lists.new[ref Ref]()+    val remotes_base: str.StringView = files.join(git_dir, str.from_cstr(c"refs/remotes"))+    read_ref_dir(remotes_base, str.view(none, 0), remotes)+    files.free_path(remotes_base)     val head: bytes.Bytes = resolve_head(git_dir, branches, tags)-    return RefSet{branches: branches, tags: tags, head: head}+    return RefSet{branches: branches, tags: tags, remotes: remotes, head: head} }  fn free_refs(refs: list[ref Ref]) void = trust {@@ -277,6 +287,7 @@ pub fn free(set: RefSet) void = trust {     free_refs(set.branches)     free_refs(set.tags)+    free_refs(set.remotes)     if set.head.ptr != none {         val hp: mut ref void = set.head.ptr as ref void         @free(hp)--- /dev/null+++ b/veins/src/git/remote.sx@@ -0,0 +1,249 @@+/// Git bridge remotes: fetch and push through the `.veins/git` mirror.++val stdio  = use("std/stdio")+val str    = use("std/string")+val os     = use("std/os")+val bytes  = use("../core/bytes.sx")+val buf    = use("../core/buf.sx")+val lists  = use("../core/lists.sx")+val layout = use("../store/layout.sx")+val files  = use("../io/files.sx")+val config = use("../core/repoconfig.sx")+val import = use("import.sx")+val export = use("export.sx")+val stream = use("../net/stream.sx")+val cmsg   = use("../core/msg.sx")++pub fn key_for(remote: bytes.Bytes, field: bytes.Bytes) bytes.Bytes = trust {+    val prefix: bytes.Bytes = bytes.bytes(c"remote.", 7)+    val out: ref u8 = @alloc(prefix.len + remote.len + 1 + field.len) as ref u8+    @memcpy(out as ref void, prefix.ptr as ref void, prefix.len)+    @memcpy(@ptradd(out, prefix.len as i64) as ref void, remote.ptr as ref void, remote.len)+    @store8(@ptradd(out, (prefix.len + remote.len) as i64), 46)+    @memcpy(+        @ptradd(out, (prefix.len + remote.len + 1) as i64) as ref void,+        field.ptr as ref void,+        field.len+    )+    return bytes.bytes(out, prefix.len + remote.len + 1 + field.len)+}++pub fn url_of(repo: layout.Repo, remote: bytes.Bytes) option[bytes.Bytes] = trust {+    val k: bytes.Bytes = key_for(remote, bytes.bytes(c"url", 3))+    val v = config.get(repo, k)+    bytes.free_owned(k)+    return v+}++pub fn key_name_of(repo: layout.Repo, remote: bytes.Bytes) option[bytes.Bytes] = trust {+    val k: bytes.Bytes = key_for(remote, bytes.bytes(c"key", 3))+    val v = config.get(repo, k)+    bytes.free_owned(k)+    return v+}++pub fn tls_pin_of(repo: layout.Repo, remote: bytes.Bytes) option[bytes.Bytes] = trust {+    val k: bytes.Bytes = key_for(remote, bytes.bytes(c"tls-pin", 7))+    val v = config.get(repo, k)+    bytes.free_owned(k)+    return v+}++fn git_command(repo: layout.Repo, args: list[bytes.Bytes]) bytes.Bytes = trust {+    val out: mut buf.Buf = buf.new(128)+    buf.Buf.put_raw(out, c"git" as ref u8, 3)+    val gitdir: str.StringView = layout.git_dir(repo)+    val gz: ref u8 = bytes.Bytes.to_cstr(bytes.bytes(gitdir.ptr, gitdir.len))+    buf.Buf.put_raw(out, c" -C " as ref u8, 4)+    val q: bytes.Bytes = stream.quote(bytes.from_cstr(gz))+    buf.Buf.put_bytes(out, q)+    bytes.free_owned(q)+    @free(gz as ref void)+    files.free_path(gitdir)+    for a in args {+        buf.Buf.put_u8(out, 32)+        val qa: bytes.Bytes = stream.quote(a)+        buf.Buf.put_bytes(out, qa)+        bytes.free_owned(qa)+    }+    val r: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(out))+    buf.Buf.free(out)+    return r+}++fn run_git(repo: layout.Repo, args: list[bytes.Bytes]) i32 = trust {+    val cmd: bytes.Bytes = git_command(repo, args)+    val z: ref u8 = bytes.Bytes.to_cstr(cmd)+    val code: i32 = os.run(z)+    @free(z as ref void)+    bytes.free_owned(cmd)+    return code+}++/// Make sure the bare mirror exists and knows about `remote`.+pub fn configure_mirror(repo: layout.Repo, remote: bytes.Bytes, url: bytes.Bytes) bool = trust {+    val gitdir: str.StringView = layout.git_dir(repo)+    if !files.exists_dir(gitdir) {+        files.free_path(gitdir)+        return false+    }+    files.free_path(gitdir)+    val args: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    @append(args, bytes.Bytes.dup(bytes.bytes(c"remote", 6)))+    @append(args, bytes.Bytes.dup(bytes.bytes(c"remove", 6)))+    @append(args, bytes.Bytes.dup(remote))+    run_git(repo, args)+    free_args(args)+    val add: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    @append(add, bytes.Bytes.dup(bytes.bytes(c"remote", 6)))+    @append(add, bytes.Bytes.dup(bytes.bytes(c"add", 3)))+    @append(add, bytes.Bytes.dup(remote))+    @append(add, bytes.Bytes.dup(url))+    val code: i32 = run_git(repo, add)+    free_args(add)+    return code == 0+}++fn free_args(args: list[bytes.Bytes]) void = trust {+    for a in args {+        if a.ptr != none {+            bytes.free_owned(a)+        }+    }+    @listfree(args)+}++pub fn fetch(repo: layout.Repo, remote: bytes.Bytes) i32 = trust {+    val url_opt = url_of(repo, remote)+    if url_opt is none {+        cmsg.error_prefix()+        stdio.eprint("unknown remote: {s}\n", {str.view(remote.ptr, remote.len as i64)})+        return 1+    }+    val url: mut bytes.Bytes = bytes.empty()+    match url_opt {+        some v => {+            url = v+        }+        none => {+            return 1+        }+    }+    val configured: bool = configure_mirror(repo, remote, url)+    bytes.free_owned(url)+    if !configured {+        cmsg.error_prefix()+        stdio.eprint("cannot configure git mirror\n", {})+        return 1+    }+    val args: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    @append(args, bytes.Bytes.dup(bytes.bytes(c"fetch", 5)))+    @append(args, bytes.Bytes.dup(bytes.bytes(c"--prune", 7)))+    @append(args, bytes.Bytes.dup(remote))+    val code: i32 = run_git(repo, args)+    free_args(args)+    if code != 0 {+        cmsg.error_prefix()+        stdio.eprint("git fetch failed\n", {})+        return 1+    }+    return import.run(repo)+}++pub fn push(repo: layout.Repo, remote: bytes.Bytes, bookmark: bytes.Bytes) i32 = trust {+    val url_opt = url_of(repo, remote)+    if url_opt is none {+        cmsg.error_prefix()+        stdio.eprint("unknown remote: {s}\n", {str.view(remote.ptr, remote.len as i64)})+        return 1+    }+    val url: mut bytes.Bytes = bytes.empty()+    match url_opt {+        some v => {+            url = v+        }+        none => {+            return 1+        }+    }+    val configured: bool = configure_mirror(repo, remote, url)+    bytes.free_owned(url)+    if !configured {+        cmsg.error_prefix()+        stdio.eprint("cannot configure git mirror\n", {})+        return 1+    }+    val ex: i32 = export.run(repo)+    if ex != 0 {+        return ex+    }+    val refspec: ref u8 = @fmtalloc(+        "refs/heads/{s}:refs/heads/{s}",+        {str.view(bookmark.ptr, bookmark.len as i64), str.view(bookmark.ptr, bookmark.len as i64)}+    )+    val args: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    @append(args, bytes.Bytes.dup(bytes.bytes(c"push", 4)))+    @append(args, bytes.Bytes.dup(remote))+    @append(args, bytes.from_cstr(refspec))+    val code: i32 = run_git(repo, args)+    free_args(args)+    if code != 0 {+        cmsg.error_prefix()+        stdio.eprint("git push failed\n", {})+        return 1+    }+    stdio.print(+        "pushed {s} to {s}\n",+        {str.view(bookmark.ptr, bookmark.len as i64), str.view(remote.ptr, remote.len as i64)}+    )+    return 0+}++/// List configured remote names.+pub fn list_remotes(repo: layout.Repo) list[bytes.Bytes] = trust {+    val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    val p: str.StringView = layout.config_path(repo)+    val data_opt = files.read_all(p)+    files.free_path(p)+    if data_opt is some d {+        val start: mut usize = 0+        val i: mut usize = 0+        for i <= d.len {+            if i == d.len || bytes.Bytes.at(d, i) == 10 {+                val line: bytes.Bytes = bytes.Bytes.slice(d, start, i)+                if find_sub(line, bytes.bytes(c"remote.", 7)) == 0 {+                    val dot: i64 = find_sub_from(line, bytes.bytes(c".url", 4), 7)+                    if dot > 7 {+                        @append(+                            out,+                            bytes.Bytes.dup(bytes.Bytes.slice(line, 7, dot as usize))+                        )+                    }+                }+                start = i + 1+            }+            i+++        }+        files.free_buffer(d)+    }+    return out+}++fn find_sub(hay: bytes.Bytes, needle: bytes.Bytes) i64 = trust {+    return find_sub_from(hay, needle, 0)+}++fn find_sub_from(hay: bytes.Bytes, needle: bytes.Bytes, from: usize) i64 = trust {+    if needle.len > hay.len {+        return -1+    }+    val i: mut usize = from+    for i <= hay.len - needle.len {+        if bytes.Bytes.eql(bytes.Bytes.slice(hay, i, i + needle.len), needle) {+            return i as i64+        }+        i+++    }+    return -1+}+--- a/veins/src/io/files.sx+++ b/veins/src/io/files.sx@@ -174,16 +174,28 @@ /// List directory entry names. Each name is an owned NUL-terminated string. /// The caller releases the result with `free_names`. pub fn list_dir(p: str.StringView) list[ref u8] = {+    val out: mut list[ref u8] = lists.new[ref u8]()     val z: str.ZString = trust str.zstr_from[allocators.HeapAllocator](heap(), p)     if z.ptr == none {-        return lists.new[ref u8]()+        return out     }-    val result = trust fs.walk_dir_cstr[allocators.HeapAllocator](heap(), z.ptr)-    trust str.zstr_free[allocators.HeapAllocator](heap(), z)-    if result is some names {-        return names+    val arena_r = trust allocators.ScopedArena.new(4096 as usize)+    match arena_r {+        ok sa => {+            val la: allocators.ListArena = allocators.ListArena{arena: sa}+            val names = trust fs.walk_dir_cstr[allocators.ListArena](la, z.ptr)+            if names is some entries {+                for n in entries {+                    @append(out, n)+                }+            }+            trust allocators.ScopedArena.free(sa)+        }+        err _ => {+        }     }-    return lists.new[ref u8]()+    trust str.zstr_free[allocators.HeapAllocator](heap(), z)+    return out }  pub fn free_names(names: list[ref u8]) void = {--- a/veins/src/main.sx+++ b/veins/src/main.sx@@ -1,8 +1,9 @@ link "-lz"-lib "crypto"  val stdio        = use("std/stdio") val str          = use("std/string")+val os           = use("std/os")+val testing      = use("std/testing") val msg          = use("core/msg.sx") val bytes        = use("core/bytes.sx") val init_cmd     = use("cli/init_cmd.sx")@@ -9,6 +10,13 @@ val fsck_cmd     = use("cli/fsck_cmd.sx") val selftest_cmd = use("cli/selftest_cmd.sx") val git_cmd      = use("cli/git_cmd.sx")+val clone_cmd    = use("cli/clone_cmd.sx")+val fetch_cmd    = use("cli/fetch_cmd.sx")+val push_cmd     = use("cli/push_cmd.sx")+val serve_cmd    = use("cli/serve_cmd.sx")+val key_cmd      = use("cli/key_cmd.sx")+val access_cmd   = use("cli/access_cmd.sx")+val whoami_cmd   = use("cli/whoami_cmd.sx") val checkout_cmd = use("cli/checkout_cmd.sx") val help_cmd     = use("cli/help_cmd.sx") val bench_cmd    = use("cli/bench_cmd.sx")@@ -29,6 +37,9 @@ val ex_cmd       = use("cli/ex_cmd.sx") val lists        = use("core/lists.sx") val layout       = use("store/layout.sx")++extern (C) fn c_malloc(size: usize) ref void = "malloc"+extern (C) fn c_free(p: ref void) void = "free"  fn cmd_is(a: ref u8, text: ref u8, len: usize) bool = {     if a == none {@@ -740,7 +751,59 @@     return status } -pub fn main() i32 = trust {+fn leak_report() void = trust {+    val capacity: usize = 262144+    val copy: ref u8 = c_malloc(capacity) as ref u8+    val d = @dumpmemleaks()+    stdio.print(+        "leak-check: enabled={d} live_allocations={d} live_bytes={d} allocations={d} frees={d} peak_bytes={d} invalid_frees={d}\n",+        {+            d.enabled,+            d.live_allocations,+            d.live_bytes,+            d.total_allocations,+            d.total_frees,+            d.peak_live_bytes,+            d.invalid_frees+        }+    )+    val max_records: i64 = (capacity / (@sizeof(testing.LeakRecord) as usize)) as i64+    val count: i64 = d.record_count+    val to_copy: mut i64 = count+    if to_copy > max_records {+        to_copy = max_records+    }+    if to_copy > 0 && d.records != none {+        @memcpy(copy as ref void, d.records as ref void, (to_copy * (@sizeof(testing.LeakRecord) as i64)) as usize)+    }+    val i: mut i64 = 0+    for i < to_copy {+        val rec = @ptradd(+            copy,+            (i * (@sizeof(testing.LeakRecord) as i64))+        ) as ref testing.LeakRecord+        stdio.print(+            "leak-check: {d} bytes at {s}:{d} ({p})\n",+            {rec.size, rec.file, rec.line, rec.address}+        )+        i+++    }+    c_free(copy as ref void)+}++fn leak_report_requested() bool = trust {+    val v = os.env(c"VEINS_LEAK_REPORT")+    match v {+        some _ => {+            return true+        }+        none => {+            return false+        }+    }+}++fn run_main() i32 = trust {     val args: list[ref u8] = @args()     if @len(args) < 2 {         help_cmd.usage()@@ -763,6 +826,27 @@     }     if cmd_is(cmd, c"git", 3) {         return git_cmd.run(args, 2)+    }+    if cmd_is(cmd, c"clone", 5) {+        return clone_cmd.run(args, 2)+    }+    if cmd_is(cmd, c"fetch", 5) {+        return fetch_cmd.run(args, 2)+    }+    if cmd_is(cmd, c"push", 4) {+        return push_cmd.run(args, 2)+    }+    if cmd_is(cmd, c"serve", 5) {+        return serve_cmd.run(args, 2)+    }+    if cmd_is(cmd, c"key", 3) {+        return key_cmd.run(args, 2)+    }+    if cmd_is(cmd, c"access", 6) {+        return access_cmd.run(args, 2)+    }+    if cmd_is(cmd, c"whoami", 6) {+        return whoami_cmd.run(args, 2)     }     if cmd_is(cmd, c"co", 2) || cmd_is(cmd, c"checkout", 8) {         return checkout_cmd.run(args, 2)@@ -848,4 +932,13 @@     stdio.eprint("unknown command: {s}\n", {str.from_cstr(cmd)})     help_cmd.usage()     return 1+}++pub fn main() i32 = trust {+    val requested: bool = leak_report_requested()+    val status: i32 = run_main()+    if requested {+        leak_report()+    }+    return status }--- /dev/null+++ b/veins/src/net/stream.sx@@ -0,0 +1,203 @@+/// Reliable byte streams over a plain fd, TLS, stdio, or a child process.++val bytes = use("../core/bytes.sx")+val tls   = use("../crypto/tls.sx")+val native = use("../io/native.sx")++extern (C) fn c_pipe(fds: ref i32) i32 = "pipe"+extern (C) fn c_fork() i32 = "fork"+extern (C) fn c_dup2(oldfd: i32, newfd: i32) i32 = "dup2"+extern (C) fn c_execl(path: ref u8, arg0: ref u8, ...) i32 = "execl"+extern (C) fn c_waitpid(pid: i32, status: ref i32, options: i32) i32 = "waitpid"+extern (C) fn c_close(fd: i32) i32 = "close"+extern (C) fn c__exit(code: i32) void = "_exit"+extern (C) fn c_readlink(path: ref u8, buf: ref u8, cap: usize) i64 = "readlink"++pub val K_FD: u8 = 0+pub val K_TLS: u8 = 1+pub val K_STDIO: u8 = 2+pub val K_PROC: u8 = 3++pub type Stream = {+    kind: mut u8+    fd_in: mut i32+    fd_out: mut i32+    ssl: mut ref void+    pid: mut i32+}++pub fn stdio_stream() Stream = {+    return Stream{kind: K_STDIO, fd_in: 0, fd_out: 1, ssl: none, pid: 0}+}++pub fn fd_stream(fd: i32) Stream = {+    return Stream{kind: K_FD, fd_in: fd, fd_out: fd, ssl: none, pid: 0}+}++pub fn tls_stream(fd: i32, ssl: ref void) Stream = {+    return Stream{kind: K_TLS, fd_in: fd, fd_out: fd, ssl: ssl, pid: 0}+}++fn close_fd(fd: i32) void = trust {+    if fd > 2 {+        c_close(fd)+    }+}++pub fn close(s: Stream) void = trust {+    if s.kind == K_TLS && s.ssl != none {+        tls.free(s.ssl)+    }+    if s.kind == K_PROC {+        close_fd(s.fd_in)+        close_fd(s.fd_out)+        if s.pid > 0 {+            val status: mut i32 = 0+            c_waitpid(s.pid, @addr(status), 0)+        }+    } elif s.kind == K_FD {+        close_fd(s.fd_in)+    }+}++/// Read up to `n` bytes. Returns 0 at end of stream, -1 on error.+pub fn read(s: Stream, buf: ref u8, n: usize) i64 = trust {+    if n == 0 {+        return 0+    }+    if s.kind == K_TLS {+        return tls.read(s.ssl, buf, n)+    }+    val fd: mut i32 = s.fd_in+    if s.kind == K_STDIO {+        fd = 0+    }+    return native.read_fd(fd, buf, n)+}++pub fn write_all(s: Stream, data: bytes.Bytes) bool = trust {+    if s.kind == K_STDIO {+        return native.write_fd_all(1, data)+    }+    if s.kind == K_TLS {+        val off: mut usize = 0+        for off < data.len {+            val n: i64 = tls.write(+                s.ssl,+                @ptradd(data.ptr, off as i64) as ref u8,+                data.len - off+            )+            if n <= 0 {+                return false+            }+            off = off + n as usize+        }+        return true+    }+    return native.write_fd_all(s.fd_out, data)+}++pub fn write_bytes(s: Stream, ptr: ref u8, n: usize) bool = trust {+    return write_all(s, bytes.bytes(ptr, n))+}++type PipePair = {+    read_fd: mut i32+    write_fd: mut i32+    valid: mut bool+}++fn pipe_pair() PipePair = trust {+    val fds: ref i32 = @alloc(8) as ref i32+    val rc: i32 = c_pipe(fds)+    if rc != 0 {+        @free(fds as ref void)+        return PipePair{read_fd: -1, write_fd: -1, valid: false}+    }+    val a: i32 = @load32(fds)+    val b: i32 = @load32(@ptradd(fds, 4) as ref i32)+    @free(fds as ref void)+    return PipePair{read_fd: a, write_fd: b, valid: true}+}++/// Start `/bin/sh -c <command>` with pipes on stdin and stdout.+pub fn spawn(command: bytes.Bytes) option[Stream] = trust {+    val ip: PipePair = pipe_pair()+    val op: PipePair = pipe_pair()+    if !ip.valid || !op.valid {+        return none+    }+    val cmd_z: ref u8 = bytes.Bytes.to_cstr(command)+    val pid: i32 = c_fork()+    if pid == 0 {+        val rc1: i32 = c_dup2(ip.read_fd, 0)+        val rc2: i32 = c_dup2(op.write_fd, 1)+        close_fd(ip.read_fd)+        close_fd(ip.write_fd)+        close_fd(op.read_fd)+        close_fd(op.write_fd)+        val rc3: i32 = c_execl(c"/bin/sh", c"sh", c"-c", cmd_z, none)+        if rc1 == 0 && rc2 == 0 && rc3 == 0 {+            c__exit(0)+        }+        c__exit(127)+    }+    @free(cmd_z as ref void)+    close_fd(ip.read_fd)+    close_fd(op.write_fd)+    if pid < 0 {+        close_fd(op.read_fd)+        close_fd(ip.write_fd)+        return none+    }+    val s: Stream = Stream{+        kind: K_PROC,+        fd_in: op.read_fd,+        fd_out: ip.write_fd,+        ssl: none,+        pid: pid+    }+    return some s+}++/// Return a single-quoted shell word. The result is owned by the caller.+pub fn quote(word: bytes.Bytes) bytes.Bytes = trust {+    val quote: u8 = 39+    val joined: ref u8 = @alloc(word.len * 4 + 4) as ref u8+    val mut_len: mut usize = 0+    @store8(@ptradd(joined, mut_len as i64), quote)+    mut_len+++    val i: mut usize = 0+    for i < word.len {+        val c: u8 = bytes.Bytes.at(word, i)+        if c == quote {+            @store8(@ptradd(joined, mut_len as i64), quote)+            mut_len+++            @store8(@ptradd(joined, mut_len as i64), 92)+            mut_len+++            @store8(@ptradd(joined, mut_len as i64), quote)+            mut_len+++            @store8(@ptradd(joined, mut_len as i64), quote)+            mut_len+++        } else {+            @store8(@ptradd(joined, mut_len as i64), c)+            mut_len+++        }+        i+++    }+    @store8(@ptradd(joined, mut_len as i64), quote)+    mut_len+++    return bytes.bytes(joined, mut_len)+}++/// Resolve the running executable, for spawning a local stdio server.+pub fn self_exe() bytes.Bytes = trust {+    val buf: ref u8 = @alloc(4096) as ref u8+    val n: i64 = c_readlink(c"/proc/self/exe", buf, 4095)+    if n > 0 {+        @store8(@ptradd(buf, n), 0)+        return bytes.bytes(buf, n as usize)+    }+    @free(buf as ref void)+    return bytes.Bytes.dup(bytes.bytes(c"vn", 2))+}--- a/veins/src/object/content.sx+++ b/veins/src/object/content.sx@@ -11,6 +11,7 @@ val lazy   = use("../git/lazy.sx") val object = use("../git/object.sx") val txnmod = use("../store/txn.sx")+val promisor = use("../protocol/promisor.sx")  fn read_body_any(     handles: list[ref store.Handle],@@ -88,7 +89,14 @@     } elif b.form == blob.FORM_LEAF {         for e in b.entries {             val chunk_opt = read_body_any(handles, e.id, types.CHUNK, use_cache, tx)-            match chunk_opt {+            val chunk2: mut option[bytes.Bytes] = chunk_opt+            if chunk2 is none {+                promisor.ensure(handles)+                if promisor.is_active() {+                    chunk2 = promisor.fetch_chunk(e.id)+                }+            }+            match chunk2 {                 some chunk => {                     buf.Buf.put_bytes(out, chunk)                     files.free_buffer(chunk)--- a/veins/src/object/operation.sx+++ b/veins/src/object/operation.sx@@ -17,6 +17,7 @@     username: mut bytes.Bytes     description: mut bytes.Bytes     tags: mut list[ref prim.KeyValue]+    owned: mut bytes.Bytes }  fn new_kv(key: bytes.Bytes, value: bytes.Bytes) ref prim.KeyValue = {@@ -58,6 +59,7 @@ pub fn decode(body: bytes.Bytes) result[ref Operation, derr.DecodeError] = {     val r: mut reader.Reader = reader.new(body.ptr, body.len)     val op: mut ref Operation = @alloc(@sizeof(Operation)) as ref Operation+    op.owned = bytes.empty()     op.parents = read_parents(r)?     val v: ref u8 = reader.Reader.read_id(r)?     op.view = objid.id(v)@@ -111,6 +113,10 @@         trust @free(p)     }     @listfree(op.tags)+    if op.owned.ptr != none {+        val ob: mut ref void = op.owned.ptr as ref void+        trust @free(ob)+    }     val p2: mut ref void = op as ref void     trust @free(p2) }--- a/veins/src/object/view.sx+++ b/veins/src/object/view.sx@@ -40,6 +40,7 @@     tags: mut list[ref TagRef]     remote_refs: mut list[ref RemoteRef]     working_copies: mut list[ref WorkspaceRef]+    owned: mut bytes.Bytes }  pub fn empty_target_set() TargetSet = {@@ -316,6 +317,7 @@ pub fn decode(body: bytes.Bytes) result[ref View, derr.DecodeError] = {     val r: mut reader.Reader = reader.new(body.ptr, body.len)     val v: mut ref View = @alloc(@sizeof(View)) as ref View+    v.owned = bytes.empty()     v.heads = read_heads(r)?     v.bookmarks = read_bookmarks(r)?     v.tags = read_tags(r)?@@ -398,6 +400,10 @@         trust @free(p)     }     @listfree(v.working_copies)+    if v.owned.ptr != none {+        val ob: mut ref void = v.owned.ptr as ref void+        trust @free(ob)+    }     val p2: mut ref void = v as ref void     trust @free(p2) }--- /dev/null+++ b/veins/src/protocol/client.sx@@ -0,0 +1,856 @@++val time     = use("std/time")+val bytes    = use("../core/bytes.sx")+val buf      = use("../core/buf.sx")+val lists    = use("../core/lists.sx")+val reader   = use("../core/reader.sx")+val objid    = use("../object/id.sx")+val store    = use("../store/store.sx")+val state    = use("../store/state.sx")+val layout   = use("../store/layout.sx")+val writer   = use("../store/writer.sx")+val zstd     = use("../store/zstd.sx")+val stream   = use("../net/stream.sx")+val wire     = use("../protocol/wire.sx")+val msg      = use("../protocol/messages.sx")+val ed       = use("../crypto/ed25519.sx")+val tls      = use("../crypto/tls.sx")+val keys     = use("../auth/keys.sx")+val handshake = use("../auth/handshake.sx")+val b3       = use("../crypto/blake3.sx")+val random   = use("std/crypto/random")++pub type Client = {+    s: mut stream.Stream+    binding: mut bytes.Bytes+    version: mut u16+    role: mut u8+    authed: mut bool+    fingerprint: mut bytes.Bytes+    repo_name: mut bytes.Bytes+}++pub type WhoAmI = {+    role: mut u8+    fingerprint: mut bytes.Bytes+}++type Url = {+    tls: mut bool+    host: mut bytes.Bytes+    port: mut i32+    path: mut bytes.Bytes+    ssh: mut bool+}++type Authority = {+    host: mut bytes.Bytes+    port: mut i32+}++type IncomingRecord = {+    id: mut bytes.Bytes+    kind: mut u8+    body: mut bytes.Bytes+}++fn copy_bytes(b: bytes.Bytes) bytes.Bytes = trust {+    return bytes.Bytes.dup(b)+}++fn parse_port(text: bytes.Bytes) option[i32] = trust {+    if text.len == 0 {+        return none+    }+    val port: mut i32 = 0+    val i: mut usize = 0+    for i < text.len {+        val c: u8 = bytes.Bytes.at(text, i)+        if c < 48 || c > 57 {+            return none+        }+        port = port * 10 + (c - 48) as i32+        i+++    }+    return some port+}++fn find_char(b: bytes.Bytes, needle: u8) i64 = trust {+    val i: mut usize = 0+    for i < b.len {+        if bytes.Bytes.at(b, i) == needle {+            return i as i64+        }+        i+++    }+    return -1+}++fn parse_authority(+    authority: bytes.Bytes,+    default_port: i32,+    strip_user: bool+) Authority = trust {+    val hp: mut bytes.Bytes = authority+    if strip_user {+        val at: i64 = find_char(authority, 64)+        if at >= 0 {+            hp = bytes.Bytes.slice(authority, (at as usize) + 1, authority.len)+        }+    }+    val colon: i64 = find_char(hp, 58)+    val host: mut bytes.Bytes = hp+    val port: mut i32 = default_port+    if colon >= 0 {+        host = bytes.Bytes.slice(hp, 0, colon as usize)+        val po = parse_port(bytes.Bytes.slice(hp, (colon as usize) + 1, hp.len))+        if po is some p {+            port = p+        }+    }+    return Authority{host: bytes.Bytes.dup(host), port: port}+}++pub fn parse_url(url: bytes.Bytes) option[Url] = trust {+    if bytes.Bytes.starts_with(url, bytes.bytes(c"file://", 7)) {+        return some Url{+            tls: false,+            host: bytes.empty(),+            port: 0,+            path: bytes.Bytes.dup(bytes.Bytes.slice(url, 7, url.len)),+            ssh: false+        }+    }+    if bytes.Bytes.starts_with(url, bytes.bytes(c"ssh://", 6)) {+        val rest: bytes.Bytes = bytes.Bytes.slice(url, 6, url.len)+        val slash: i64 = find_char(rest, 47)+        if slash < 0 {+            return none+        }+        val auth: bytes.Bytes = bytes.Bytes.slice(rest, 0, slash as usize)+        val path: bytes.Bytes = bytes.Bytes.slice(rest, (slash as usize) + 1, rest.len)+        val parsed = parse_authority(auth, 22, true)+        return some Url{+            tls: false,+            host: parsed.host,+            port: parsed.port,+            path: bytes.Bytes.dup(path),+            ssh: true+        }+    }+    if bytes.Bytes.starts_with(url, bytes.bytes(c"veins://", 8)) {+        val rest: bytes.Bytes = bytes.Bytes.slice(url, 8, url.len)+        val slash: i64 = find_char(rest, 47)+        if slash < 0 {+            return none+        }+        val auth: bytes.Bytes = bytes.Bytes.slice(rest, 0, slash as usize)+        val path: bytes.Bytes = bytes.Bytes.slice(rest, (slash as usize) + 1, rest.len)+        val parsed = parse_authority(auth, 7419, false)+        return some Url{+            tls: true,+            host: parsed.host,+            port: parsed.port,+            path: bytes.Bytes.dup(path),+            ssh: false+        }+    }+    return none+}++fn build_command(parts: list[bytes.Bytes]) bytes.Bytes = trust {+    val out: mut buf.Buf = buf.new(128)+    for p in parts {+        if out.len > 0 {+            buf.Buf.put_u8(out, 32)+        }+        val q: bytes.Bytes = stream.quote(p)+        buf.Buf.put_bytes(out, q)+        bytes.free_owned(q)+    }+    val r: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(out))+    buf.Buf.free(out)+    return r+}++fn connect_stream(u: Url, tls_pin: bytes.Bytes) option[stream.Stream] = trust {+    if u.ssh {+        val parts: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+        @append(parts, copy_bytes(bytes.bytes(c"ssh", 3)))+        if u.port != 22 {+            @append(parts, copy_bytes(bytes.bytes(c"-p", 2)))+            val ps: ref u8 = @fmtalloc("{d}", {u.port})+            @append(parts, bytes.from_cstr(ps))+            @free(ps as ref void)+        }+        val host_z: ref u8 = bytes.Bytes.to_cstr(u.host)+        @append(parts, copy_bytes(bytes.from_cstr(host_z)))+        @free(host_z as ref void)+        @append(parts, copy_bytes(bytes.bytes(c"vn", 2)))+        @append(parts, copy_bytes(bytes.bytes(c"serve", 5)))+        @append(parts, copy_bytes(bytes.bytes(c"-stdio", 6)))+        @append(parts, copy_bytes(u.path))+        val cmd: bytes.Bytes = build_command(parts)+        free_parts(parts)+        val res = stream.spawn(cmd)+        bytes.free_owned(cmd)+        return res+    }+    if u.tls {+        val host_z2: ref u8 = bytes.Bytes.to_cstr(u.host)+        val fd: i32 = tls.tcp_connect(host_z2, u.port)+        if fd < 0 {+            @free(host_z2 as ref void)+            return none+        }+        val ctx: mut ref void = tls.client_ctx()+        if tls_pin.len > 0 {+            ctx = tls.client_ctx_pinned()+        }+        if ctx == none {+            @free(host_z2 as ref void)+            native_close(fd)+            return none+        }+        val ssl: ref void = tls.connect(ctx, fd, host_z2)+        tls.free_ctx(ctx)+        @free(host_z2 as ref void)+        if ssl == none {+            native_close(fd)+            return none+        }+        return some stream.tls_stream(fd, ssl)+    }+    val exe: bytes.Bytes = stream.self_exe()+    val parts2: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    @append(parts2, exe)+    @append(parts2, copy_bytes(bytes.bytes(c"serve", 5)))+    @append(parts2, copy_bytes(bytes.bytes(c"-stdio", 6)))+    @append(parts2, copy_bytes(u.path))+    val cmd2: bytes.Bytes = build_command(parts2)+    free_parts(parts2)+    val res2 = stream.spawn(cmd2)+    bytes.free_owned(cmd2)+    return res2+}++fn free_parts(parts: list[bytes.Bytes]) void = trust {+    for p in parts {+        if p.ptr != none {+            bytes.free_owned(p)+        }+    }+    @listfree(parts)+}++extern (C) fn close(fd: i32) i32 = "close"++fn native_close(fd: i32) void = trust {+    close(fd)+}++fn free_hello_fields(h: msg.Hello) void = trust {+    msg.free_hello(h)+}++/// Connect and authenticate. Empty key name means anonymous unless required.+pub fn connect(+    url: bytes.Bytes,+    key_name: bytes.Bytes,+    repo_name: bytes.Bytes+) option[Client] = trust {+    return connect_pinned(url, key_name, repo_name, bytes.empty())+}++pub fn connect_pinned(+    url: bytes.Bytes,+    key_name: bytes.Bytes,+    repo_name: bytes.Bytes,+    tls_pin: bytes.Bytes+) option[Client] = trust {+    val u_opt = parse_url(url)+    val u: mut Url = Url{+        tls: false,+        host: bytes.empty(),+        port: 0,+        path: bytes.empty(),+        ssh: false+    }+    match u_opt {+        some v => {+            u = v+        }+        none => {+            return none+        }+    }+    val st_opt = connect_stream(u, tls_pin)+    if u.host.ptr != none {+        bytes.free_ptr(u.host.ptr)+    }+    if u.path.ptr != none {+        bytes.free_ptr(u.path.ptr)+    }+    val st: mut stream.Stream = stream.stdio_stream()+    match st_opt {+        some v => {+            st = v+        }+        none => {+            return none+        }+    }+    val binding: mut bytes.Bytes = bytes.empty()+    if st.kind == stream.K_TLS {+        val b: ref u8 = @alloc(32) as ref u8+        if tls.exporter(st.ssl, b, 32) {+            binding = bytes.bytes(b, 32)+        } else {+            @free(b as ref void)+        }+        if tls_pin.len > 0 {+            val digest: ref u8 = @alloc(32) as ref u8+            val got: bool = tls.peer_sha256(st.ssl, digest)+            val hex: bytes.Bytes = tls.to_hex(bytes.bytes(digest, 32))+            val matched: bool = got && tls.hex_equal(hex, tls_pin)+            bytes.free_ptr(hex.ptr)+            bytes.free_ptr(digest)+            if !matched {+                stream.close(st)+                if binding.ptr != none {+                    @free(binding.ptr as ref void)+                }+                return none+            }+        }+    }+    val cn: ref u8 = @alloc(32) as ref u8+    random.random_bytes(cn as ref void, 32)+    val client_nonce: bytes.Bytes = bytes.Bytes.dup(bytes.bytes(cn, 32))+    @free(cn as ref void)+    val caps: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    @append(caps, copy_bytes(bytes.bytes(c"zstd-records", 12)))+    @append(caps, copy_bytes(bytes.bytes(c"lazy-chunks", 11)))+    @append(caps, copy_bytes(bytes.bytes(c"push", 4)))+    @append(caps, copy_bytes(bytes.bytes(c"auth-ed25519", 12)))+    val hello: msg.Hello = msg.Hello{+        min_version: msg.PROTOCOL_VERSION,+        max_version: msg.PROTOCOL_VERSION,+        capabilities: caps,+        repo: bytes.Bytes.dup(repo_name),+        client_nonce: bytes.Bytes.dup(client_nonce)+    }+    val hello_body: bytes.Bytes = msg.encode_hello(hello)+    free_hello_fields(hello)+    if !wire.write_frame(st, wire.HELLO, 1, hello_body) {+        stream.close(st)+        bytes.free_owned(client_nonce)+        if binding.ptr != none {+            bytes.free_owned(binding)+        }+        return none+    }+    val f_opt = wire.read_frame(st)+    val f: mut wire.Frame = wire.Frame{+        kind: 0,+        request_id: 0,+        payload: bytes.empty(),+        base: bytes.empty()+    }+    match f_opt {+        some x => {+            f = x+        }+        none => {+            stream.close(st)+            bytes.free_owned(client_nonce)+            if binding.ptr != none {+                bytes.free_owned(binding)+            }+            return none+        }+    }+    if f.kind != wire.HELLO_OK {+        wire.free_frame(f)+        stream.close(st)+        bytes.free_owned(client_nonce)+        if binding.ptr != none {+            bytes.free_owned(binding)+        }+        return none+    }+    val hd = msg.decode_hello_ok(f.payload)+    val hok: mut msg.HelloOk = msg.HelloOk{+        version: 0,+        capabilities: lists.new[bytes.Bytes](),+        server_nonce: bytes.empty(),+        auth_required: 0+    }+    val parsed_ok: mut bool = false+    match hd {+        ok v => {+            hok = v+            parsed_ok = true+        }+        err _ => {+        }+    }+    wire.free_frame(f)+    if !parsed_ok {+        stream.close(st)+        bytes.free_owned(client_nonce)+        if binding.ptr != none {+            bytes.free_owned(binding)+        }+        return none+    }+    val key_sel: mut bytes.Bytes = key_name+    if key_sel.len == 0 && hok.auth_required != 0 {+        key_sel = bytes.bytes(c"default", 7)+    }+    val c: mut ref Client = @alloc(@sizeof(Client)) as ref Client+    c.s = st+    c.binding = binding+    c.version = hok.version+    c.role = 0+    c.authed = false+    c.fingerprint = bytes.empty()+    c.repo_name = bytes.Bytes.dup(repo_name)+    if key_sel.len > 0 {+        val key_opt = keys.load(key_sel)+        if key_opt is some key {+            val message: bytes.Bytes = handshake.auth_message(+                hok.version,+                repo_name,+                hok.server_nonce,+                client_nonce,+                binding+            )+            val sig_opt = ed.sign(key.seed, message)+            bytes.free_owned(message)+            if sig_opt is some sig {+                val a: msg.Auth = msg.Auth{+                    public_key: bytes.Bytes.dup(key.public_key),+                    signature: bytes.Bytes.dup(sig)+                }+                val ab: bytes.Bytes = msg.encode_auth(a)+                bytes.free_ptr(a.public_key.ptr)+                bytes.free_ptr(a.signature.ptr)+                bytes.free_owned(sig)+                wire.write_frame(st, wire.AUTH, 2, ab)+                val af = wire.read_frame(st)+                if af is some afr {+                    if afr.kind == wire.AUTH_OK {+                        val ad = msg.decode_auth_ok(afr.payload)+                        if ad is ok aok {+                            c.role = aok.role+                            c.authed = true+                            c.fingerprint = bytes.Bytes.dup(aok.fingerprint)+                            if aok.fingerprint.ptr != none {+                                bytes.free_ptr(aok.fingerprint.ptr)+                            }+                        }+                    }+                    wire.free_frame(afr)+                }+            }+            keys.free_key(key)+        }+    }+    val auth_req: bool = hok.auth_required != 0+    msg.free_hello_ok(hok)+    bytes.free_owned(client_nonce)+    if auth_req && !c.authed {+        free_client(c)+        return none+    }+    return some c+}++pub fn free_client(c: mut ref Client) void = trust {+    stream.close(c.s)+    if c.binding.ptr != none {+        bytes.free_ptr(c.binding.ptr)+    }+    if c.fingerprint.ptr != none {+        bytes.free_ptr(c.fingerprint.ptr)+    }+    if c.repo_name.ptr != none {+        bytes.free_ptr(c.repo_name.ptr)+    }+    @free(c as ref void)+}++fn request(c: ref Client, kind: u8, payload: bytes.Bytes) option[wire.Frame] = trust {+    val rid: u32 = (time.unix_now_millis() & 0x7fffffff) as u32+    if !wire.write_frame(c.s, kind, rid, payload) {+        return none+    }+    return wire.read_frame(c.s)+}++pub fn list_refs(c: ref Client) option[list[msg.RefInfo]] = trust {+    val f_opt = request(c, wire.LIST_REFS, bytes.empty())+    if f_opt is some f {+        if f.kind != wire.REFS {+            wire.free_frame(f)+            return none+        }+        val dec = msg.decode_refs(f.payload)+        wire.free_frame(f)+        if dec is ok v {+            return some v+        }+    }+    return none+}++pub fn negotiate(c: ref Client, wants: list[bytes.Bytes], haves: list[bytes.Bytes]) bool = trust {+    val body: bytes.Bytes = msg.encode_negotiate(wants, haves)+    val f_opt = request(c, wire.NEGOTIATE, body)+    if f_opt is some f {+        val passed: bool = f.kind == wire.NEGOTIATE_OK+        wire.free_frame(f)+        return passed+    }+    return false+}++fn parse_record(data: bytes.Bytes) option[IncomingRecord] = trust {+    if data.len < 35 {+        return none+    }+    val r: mut reader.Reader = reader.new(data.ptr, data.len)+    val idp: ref u8 = reader.Reader.read_id(r)?+    val kind: u8 = reader.Reader.read_u8(r)?+    val comp: u8 = reader.Reader.read_u8(r)?+    val raw_len: u64 = reader.Reader.read_varint(r)?+    val stored_len: u64 = reader.Reader.read_varint(r)?+    if raw_len == 0 || raw_len > 67108864 {+        return none+    }+    val stored: bytes.Bytes = reader.Reader.read_raw(r, stored_len as usize)?+    if !reader.Reader.at_end(r) {+        return none+    }+    val idcopy: ref u8 = @alloc(32) as ref u8+    @memcpy(idcopy as ref void, idp as ref void, 32)+    if comp == 0 {+        if stored.len != raw_len as usize {+            @free(idcopy as ref void)+            return none+        }+        return some IncomingRecord{+            id: bytes.bytes(idcopy, 32),+            kind: kind,+            body: bytes.Bytes.dup(stored)+        }+    }+    val dec = zstd.decompress(stored, raw_len as usize)+    if dec is some d {+        return some IncomingRecord{+            id: bytes.bytes(idcopy, 32),+            kind: kind,+            body: d+        }+    }+    @free(idcopy as ref void)+    return none+}++fn receive_stream(c: ref Client, w: mut ref writer.Writer) bool = trust {+    val hash: ref void = @alloc(b3.hasher_state_size()) as ref void+    b3.hasher_init(hash)+    val good: mut bool = true+    for {+        val f_opt = wire.read_frame(c.s)+        val f: mut wire.Frame = wire.Frame{+            kind: 0,+            request_id: 0,+            payload: bytes.empty(),+            base: bytes.empty()+        }+        match f_opt {+            some x => {+                f = x+            }+            none => {+                good = false+                break+            }+        }+        if f.kind == wire.END {+            val digest: ref u8 = @alloc(32) as ref u8+            b3.hasher_final(hash, digest)+            if f.payload.len != 32 || !bytes.Bytes.eql(bytes.bytes(digest, 32), f.payload) {+                good = false+            }+            bytes.free_ptr(digest)+            wire.free_frame(f)+            break+        }+        if f.kind == wire.ERROR {+            wire.free_frame(f)+            good = false+            break+        }+        if f.kind != wire.RECORDS {+            wire.free_frame(f)+            good = false+            break+        }+        b3.hasher_update(hash, f.payload.ptr, f.payload.len)+        val pr = parse_record(f.payload)+        if pr is none {+        }+        if pr is some rec {+            val computed: objid.Id = objid.object_id(rec.kind, rec.body)+            if !objid.Id.eql(computed, objid.id(rec.id.ptr)) {+                good = false+            } else {+                writer.add_known(w, rec.kind, objid.id(rec.id.ptr), rec.body)+            }+            bytes.free_ptr(computed.ptr)+            bytes.free_ptr(rec.id.ptr)+        } else {+            good = false+        }+        wire.free_frame(f)+        if !good {+            break+        }+    }+    @free(hash as ref void)+    return good+}++fn open_writer(repo: layout.Repo) option[ref writer.Writer] = trust {+    return writer.open(repo)+}++pub fn fetch_skeleton(c: ref Client, repo: layout.Repo, wants: list[bytes.Bytes]) bool = trust {+    val body: bytes.Bytes = msg.encode_ids(wants)+    val rid: u32 = (time.unix_now_millis() & 0x7fffffff) as u32+    if !wire.write_frame(c.s, wire.FETCH_SKELETON, rid, body) {+        return false+    }+    val w_opt = open_writer(repo)+    val w: mut ref writer.Writer = none+    match w_opt {+        some x => {+            w = x+        }+        none => {+            return false+        }+    }+    val passed: bool = receive_stream(c, w)+    if !passed {+        writer.abort(w)+        return false+    }+    return writer.finish(w)+}++pub fn get_chunks(c: ref Client, repo: layout.Repo, ids: list[bytes.Bytes]) bool = trust {+    if @len(ids) == 0 {+        return true+    }+    val body: bytes.Bytes = msg.encode_ids(ids)+    val rid: u32 = (time.unix_now_millis() & 0x7fffffff) as u32+    if !wire.write_frame(c.s, wire.GET_CHUNKS, rid, body) {+        return false+    }+    val w_opt = open_writer(repo)+    val w: mut ref writer.Writer = none+    match w_opt {+        some x => {+            w = x+        }+        none => {+            return false+        }+    }+    val passed: bool = receive_stream(c, w)+    if !passed {+        writer.abort(w)+        return false+    }+    return writer.finish(w)+}++pub fn have_query(c: ref Client, ids: list[bytes.Bytes]) option[list[u64]] = trust {+    val body: bytes.Bytes = msg.encode_ids(ids)+    val f_opt = request(c, wire.HAVE_QUERY, body)+    if f_opt is some f {+        if f.kind == wire.HAVE_BITMAP {+            val dec = msg.decode_bitmap(f.payload)+            wire.free_frame(f)+            if dec is ok v {+                return some v+            }+        } else {+            wire.free_frame(f)+        }+    }+    return none+}++fn type_of(handles: list[ref store.Handle], id: objid.Id) u8 = trust {+    val loc: mut store.Loc = store.Loc{pack_index: 0, record_index: 0, kind: 0}+    if store.find_handles(handles, id, loc) {+        return loc.kind+    }+    return 0+}++fn make_record(id: objid.Id, kind: u8, body: bytes.Bytes) bytes.Bytes = trust {+    val b: mut buf.Buf = buf.new(body.len + 64)+    buf.Buf.put_raw(b, id.ptr, 32)+    buf.Buf.put_u8(b, kind)+    buf.Buf.put_u8(b, 0)+    buf.Buf.put_varint(b, body.len as u64)+    buf.Buf.put_varint(b, body.len as u64)+    buf.Buf.put_bytes(b, body)+    val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+    buf.Buf.free(b)+    return out+}++pub fn push_objects(c: ref Client, repo: layout.Repo, ids: list[objid.Id]) bool = trust {+    val rid: u32 = (time.unix_now_millis() & 0x7fffffff) as u32+    if !wire.write_frame(c.s, wire.PUT_RECORDS, rid, bytes.empty()) {+        return false+    }+    val st: store.Store = store.open_all(repo)+    val hash: ref void = @alloc(b3.hasher_state_size()) as ref void+    b3.hasher_init(hash)+    val good: mut bool = true+    for id in ids {+        val kind: u8 = type_of(st.handles, id)+        if kind == 0 {+            good = false+            break+        }+        val body_opt = state.read_body(st.handles, id, kind)+        val body: mut bytes.Bytes = bytes.empty()+        if body_opt is some b {+            body = b+        } else {+            good = false+            break+        }+        val rec: bytes.Bytes = make_record(id, kind, body)+        b3.hasher_update(hash, rec.ptr, rec.len)+        if !wire.write_frame(c.s, wire.RECORDS, rid, rec) {+            good = false+            break+        }+        files_free(body)+    }+    val digest: ref u8 = @alloc(32) as ref u8+    b3.hasher_final(hash, digest)+    if good {+        wire.write_frame(c.s, wire.END, rid, bytes.bytes(digest, 32))+    } else {+        bytes.free_ptr(digest)+    }+    @free(hash as ref void)+    store.close(st)+    if !good {+        return false+    }+    val ack = wire.read_frame(c.s)+    if ack is some f {+        val passed: bool = f.kind == wire.END+        wire.free_frame(f)+        return passed+    }+    return false+}++fn files_free(b: bytes.Bytes) void = trust {+    if b.ptr != none {+        bytes.free_owned(b)+    }+}++pub fn update_refs(c: ref Client, updates: list[msg.UpdateRef]) bool = trust {+    val body: bytes.Bytes = msg.encode_update_refs(updates)+    val f_opt = request(c, wire.UPDATE_REFS, body)+    if f_opt is some f {+        val passed: bool = f.kind == wire.UPDATE_REFS_OK+        wire.free_frame(f)+        return passed+    }+    return false+}++pub fn whoami(+    url: bytes.Bytes,+    key_name: bytes.Bytes,+    repo_name: bytes.Bytes+) option[WhoAmI] = trust {+    return whoami_pinned(url, key_name, repo_name, bytes.empty())+}++pub fn whoami_pinned(+    url: bytes.Bytes,+    key_name: bytes.Bytes,+    repo_name: bytes.Bytes,+    tls_pin: bytes.Bytes+) option[WhoAmI] = trust {+    val c_opt = connect_pinned(url, key_name, repo_name, tls_pin)+    val c: mut ref Client = none+    match c_opt {+        some v => {+            c = v+        }+        none => {+            return none+        }+    }+    val f_opt = request(c, wire.WHOAMI, bytes.empty())+    if f_opt is some f {+        if f.kind == wire.WHOAMI_OK {+            val r: mut reader.Reader = reader.new(f.payload.ptr, f.payload.len)+            val role: u8 = reader.Reader.read_u8(r)?+            val fp: bytes.Bytes = reader.Reader.read_bytes(r, 64)?+            val out: WhoAmI = WhoAmI{+                role: role,+                fingerprint: bytes.Bytes.dup(fp)+            }+            wire.free_frame(f)+            free_client(c)+            return some out+        }+        wire.free_frame(f)+    }+    free_client(c)+    return none+}++/// The repository name to send in HELLO for a URL.+pub fn url_repo_name(url: bytes.Bytes) bytes.Bytes = trust {+    val u_opt = parse_url(url)+    val u: mut Url = Url{tls: false, host: bytes.empty(), port: 0, path: bytes.empty(), ssh: false}+    match u_opt {+        some uv => {+            u = uv+        }+        none => {+            return bytes.empty()+        }+    }+    val out: mut bytes.Bytes = bytes.empty()+    if u.tls {+        out = bytes.Bytes.dup(u.path)+    }+    if u.host.ptr != none {+        bytes.free_ptr(u.host.ptr)+    }+    if u.path.ptr != none {+        bytes.free_ptr(u.path.ptr)+    }+    return out+}--- /dev/null+++ b/veins/src/protocol/messages.sx@@ -0,0 +1,443 @@+/// Encoding for the native protocol's structured messages.++val bytes  = use("../core/bytes.sx")+val buf    = use("../core/buf.sx")+val reader = use("../core/reader.sx")+val lists  = use("../core/lists.sx")+val derr   = use("../core/error.sx")++pub val PROTOCOL_VERSION: u16 = 1++pub type Hello = {+    min_version: mut u16+    max_version: mut u16+    capabilities: mut list[bytes.Bytes]+    repo: mut bytes.Bytes+    client_nonce: mut bytes.Bytes+}++pub type HelloOk = {+    version: mut u16+    capabilities: mut list[bytes.Bytes]+    server_nonce: mut bytes.Bytes+    auth_required: mut u8+}++pub type Auth = {+    public_key: mut bytes.Bytes+    signature: mut bytes.Bytes+}++pub type AuthOk = {+    role: mut u8+    fingerprint: mut bytes.Bytes+}++pub type RefInfo = {+    name: mut bytes.Bytes+    target: mut bytes.Bytes+    change_id: mut bytes.Bytes+    kind: mut u8+}++pub type UpdateRef = {+    name: mut bytes.Bytes+    expected: mut bytes.Bytes+    target: mut bytes.Bytes+}++pub type Negotiate = {+    wants: mut list[bytes.Bytes]+    haves: mut list[bytes.Bytes]+}++fn put_u16_be(b: mut buf.Buf, v: u16) void = {+    buf.Buf.put_u8(b, ((v >> 8) & 255) as u8)+    buf.Buf.put_u8(b, (v & 255) as u8)+}++fn read_u16_be(r: mut reader.Reader) result[u16, derr.DecodeError] = {+    val a: u8 = reader.Reader.read_u8(r)?+    val c: u8 = reader.Reader.read_u8(r)?+    return ok (((a as u16) << 8) | (c as u16))+}++fn put_list(b: mut buf.Buf, xs: list[bytes.Bytes]) void = {+    buf.Buf.put_varint(b, @len(xs) as u64)+    for x in xs {+        buf.Buf.put_length_prefixed(b, x)+    }+}++fn read_list(r: mut reader.Reader, max: usize) result[list[bytes.Bytes], derr.DecodeError] = {+    val n: usize = reader.Reader.read_list_len(r, max)?+    val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    val i: mut usize = 0+    for i < n {+        val v: bytes.Bytes = reader.Reader.read_bytes(r, 4096)?+        @append(out, bytes.Bytes.dup(v))+        i+++    }+    return ok out+}++fn optional_id(b: mut buf.Buf, id: bytes.Bytes) void = {+    if id.ptr == none || id.len != 32 {+        buf.Buf.put_u8(b, 0)+    } else {+        buf.Buf.put_u8(b, 1)+        buf.Buf.put_raw(b, id.ptr, 32)+    }+}++fn read_optional_id(r: mut reader.Reader) result[bytes.Bytes, derr.DecodeError] = {+    val tag: u8 = reader.Reader.read_u8(r)?+    if tag == 0 {+        return ok bytes.empty()+    }+    if tag != 1 {+        return err derr.fail(derr.ErrorKind.InvalidValue, reader.Reader.offset(r) - 1)+    }+    val p: ref u8 = reader.Reader.read_id(r)?+    return ok bytes.Bytes.slice(bytes.bytes(p, 32), 0, 32)+}++pub fn encode_hello(h: Hello) bytes.Bytes = {+    val b: mut buf.Buf = buf.new(128)+    put_u16_be(b, h.min_version)+    put_u16_be(b, h.max_version)+    put_list(b, h.capabilities)+    buf.Buf.put_length_prefixed(b, h.repo)+    buf.Buf.put_length_prefixed(b, h.client_nonce)+    val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+    buf.Buf.free(b)+    return out+}++pub fn decode_hello(data: bytes.Bytes) result[Hello, derr.DecodeError] = {+    val r: mut reader.Reader = reader.new(data.ptr, data.len)+    val mn: u16 = read_u16_be(r)?+    val mx: u16 = read_u16_be(r)?+    val caps: list[bytes.Bytes] = read_list(r, 64)?+    val repo_raw: bytes.Bytes = reader.Reader.read_bytes(r, 4096)?+    val nonce_raw: bytes.Bytes = reader.Reader.read_bytes(r, 64)?+    reader.Reader.finish(r)?+    return ok Hello{+        min_version: mn,+        max_version: mx,+        capabilities: caps,+        repo: bytes.Bytes.dup(repo_raw),+        client_nonce: bytes.Bytes.dup(nonce_raw)+    }+}++pub fn encode_hello_ok(h: HelloOk) bytes.Bytes = {+    val b: mut buf.Buf = buf.new(128)+    put_u16_be(b, h.version)+    put_list(b, h.capabilities)+    buf.Buf.put_length_prefixed(b, h.server_nonce)+    buf.Buf.put_u8(b, h.auth_required)+    val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+    buf.Buf.free(b)+    return out+}++pub fn decode_hello_ok(data: bytes.Bytes) result[HelloOk, derr.DecodeError] = {+    val r: mut reader.Reader = reader.new(data.ptr, data.len)+    val v: u16 = read_u16_be(r)?+    val caps: list[bytes.Bytes] = read_list(r, 64)?+    val nonce: bytes.Bytes = reader.Reader.read_bytes(r, 64)?+    val auth: u8 = reader.Reader.read_u8(r)?+    reader.Reader.finish(r)?+    return ok HelloOk{+        version: v,+        capabilities: caps,+        server_nonce: bytes.Bytes.dup(nonce),+        auth_required: auth+    }+}++pub fn encode_auth(a: Auth) bytes.Bytes = {+    val b: mut buf.Buf = buf.new(128)+    buf.Buf.put_length_prefixed(b, a.public_key)+    buf.Buf.put_length_prefixed(b, a.signature)+    val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+    buf.Buf.free(b)+    return out+}++pub fn decode_auth(data: bytes.Bytes) result[Auth, derr.DecodeError] = {+    val r: mut reader.Reader = reader.new(data.ptr, data.len)+    val pub_raw: bytes.Bytes = reader.Reader.read_bytes(r, 64)?+    val sig: bytes.Bytes = reader.Reader.read_bytes(r, 128)?+    reader.Reader.finish(r)?+    return ok Auth{+        public_key: bytes.Bytes.dup(pub_raw),+        signature: bytes.Bytes.dup(sig)+    }+}++pub fn encode_auth_ok(a: AuthOk) bytes.Bytes = {+    val b: mut buf.Buf = buf.new(64)+    buf.Buf.put_u8(b, a.role)+    buf.Buf.put_length_prefixed(b, a.fingerprint)+    val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+    buf.Buf.free(b)+    return out+}++pub fn decode_auth_ok(data: bytes.Bytes) result[AuthOk, derr.DecodeError] = {+    val r: mut reader.Reader = reader.new(data.ptr, data.len)+    val role: u8 = reader.Reader.read_u8(r)?+    val fp: bytes.Bytes = reader.Reader.read_bytes(r, 64)?+    reader.Reader.finish(r)?+    return ok AuthOk{role: role, fingerprint: bytes.Bytes.dup(fp)}+}++pub fn encode_refs(refs: list[RefInfo]) bytes.Bytes = {+    val b: mut buf.Buf = buf.new(256)+    buf.Buf.put_varint(b, @len(refs) as u64)+    for r in refs {+        buf.Buf.put_length_prefixed(b, r.name)+        buf.Buf.put_raw(b, r.target.ptr, 32)+        buf.Buf.put_length_prefixed(b, r.change_id)+        buf.Buf.put_u8(b, r.kind)+    }+    val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+    buf.Buf.free(b)+    return out+}++pub fn decode_refs(data: bytes.Bytes) result[list[RefInfo], derr.DecodeError] = {+    val r: mut reader.Reader = reader.new(data.ptr, data.len)+    val n: usize = reader.Reader.read_list_len(r, 1000000)?+    val out: mut list[RefInfo] = lists.new[RefInfo]()+    val i: mut usize = 0+    for i < n {+        val name: bytes.Bytes = reader.Reader.read_bytes(r, 4096)?+        val p: ref u8 = reader.Reader.read_id(r)?+        val cid: bytes.Bytes = reader.Reader.read_bytes(r, 64)?+        val rkind: u8 = reader.Reader.read_u8(r)?+        val target: ref u8 = @alloc(32) as ref u8+        trust {+            @memcpy(target as ref void, p as ref void, 32)+        }+        @append(+            out,+            RefInfo{+                name: bytes.Bytes.dup(name),+                target: bytes.bytes(target, 32),+                change_id: bytes.Bytes.dup(cid),+                kind: rkind+            }+        )+        i+++    }+    reader.Reader.finish(r)?+    return ok out+}++pub fn encode_ids(ids: list[bytes.Bytes]) bytes.Bytes = {+    val b: mut buf.Buf = buf.new(ids.len * 32 + 8)+    buf.Buf.put_varint(b, @len(ids) as u64)+    for id in ids {+        buf.Buf.put_raw(b, id.ptr, 32)+    }+    val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+    buf.Buf.free(b)+    return out+}++pub fn decode_ids(data: bytes.Bytes, max: usize) result[list[bytes.Bytes], derr.DecodeError] = {+    val r: mut reader.Reader = reader.new(data.ptr, data.len)+    val n: usize = reader.Reader.read_list_len(r, max)?+    val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    val i: mut usize = 0+    for i < n {+        val p: ref u8 = reader.Reader.read_id(r)?+        val copy: ref u8 = @alloc(32) as ref u8+        trust {+            @memcpy(copy as ref void, p as ref void, 32)+        }+        @append(out, bytes.bytes(copy, 32))+        i+++    }+    reader.Reader.finish(r)?+    return ok out+}++pub fn encode_negotiate(wants: list[bytes.Bytes], haves: list[bytes.Bytes]) bytes.Bytes = {+    val b: mut buf.Buf = buf.new(256)+    buf.Buf.put_varint(b, @len(wants) as u64)+    for id in wants {+        buf.Buf.put_raw(b, id.ptr, 32)+    }+    buf.Buf.put_varint(b, @len(haves) as u64)+    for id in haves {+        buf.Buf.put_raw(b, id.ptr, 32)+    }+    val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+    buf.Buf.free(b)+    return out+}++pub fn decode_negotiate(+    data: bytes.Bytes+) result[Negotiate, derr.DecodeError] = {+    val r: mut reader.Reader = reader.new(data.ptr, data.len)+    val nw: usize = reader.Reader.read_list_len(r, 1000000)?+    val wants: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    val i: mut usize = 0+    for i < nw {+        val p: ref u8 = reader.Reader.read_id(r)?+        val copy: ref u8 = @alloc(32) as ref u8+        trust {+            @memcpy(copy as ref void, p as ref void, 32)+        }+        @append(wants, bytes.bytes(copy, 32))+        i+++    }+    val nh: usize = reader.Reader.read_list_len(r, 1000000)?+    val haves: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    val j: mut usize = 0+    for j < nh {+        val p2: ref u8 = reader.Reader.read_id(r)?+        val copy2: ref u8 = @alloc(32) as ref u8+        trust {+            @memcpy(copy2 as ref void, p2 as ref void, 32)+        }+        @append(haves, bytes.bytes(copy2, 32))+        j+++    }+    reader.Reader.finish(r)?+    return ok Negotiate{wants: wants, haves: haves}+}++pub fn encode_negotiate_ok(known: list[u64], enough: u8) bytes.Bytes = {+    val b: mut buf.Buf = buf.new(64)+    buf.Buf.put_u8(b, enough)+    buf.Buf.put_varint(b, @len(known) as u64)+    for k in known {+        buf.Buf.put_u8(b, k)+    }+    val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+    buf.Buf.free(b)+    return out+}++pub fn encode_bitmap(bits: list[u64]) bytes.Bytes = {+    val b: mut buf.Buf = buf.new(bits.len + 8)+    buf.Buf.put_varint(b, @len(bits) as u64)+    for x in bits {+        buf.Buf.put_u8(b, x as u8)+    }+    val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+    buf.Buf.free(b)+    return out+}++pub fn decode_bitmap(data: bytes.Bytes) result[list[u64], derr.DecodeError] = {+    val r: mut reader.Reader = reader.new(data.ptr, data.len)+    val n: usize = reader.Reader.read_list_len(r, 1000000)?+    val out: mut list[u64] = lists.new[u8]()+    val i: mut usize = 0+    for i < n {+        val bv: u8 = reader.Reader.read_u8(r)?+        @append(out, bv as u64)+        i+++    }+    reader.Reader.finish(r)?+    return ok out+}++pub fn encode_update_refs(updates: list[UpdateRef]) bytes.Bytes = {+    val b: mut buf.Buf = buf.new(256)+    buf.Buf.put_varint(b, @len(updates) as u64)+    for u in updates {+        buf.Buf.put_length_prefixed(b, u.name)+        optional_id(b, u.expected)+        optional_id(b, u.target)+    }+    val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+    buf.Buf.free(b)+    return out+}++pub fn decode_update_refs(data: bytes.Bytes) result[list[UpdateRef], derr.DecodeError] = {+    val r: mut reader.Reader = reader.new(data.ptr, data.len)+    val n: usize = reader.Reader.read_list_len(r, 1000000)?+    val out: mut list[UpdateRef] = lists.new[UpdateRef]()+    val i: mut usize = 0+    for i < n {+        val name: bytes.Bytes = reader.Reader.read_bytes(r, 4096)?+        val expected: bytes.Bytes = read_optional_id(r)?+        val target: bytes.Bytes = read_optional_id(r)?+        @append(+            out,+            UpdateRef{+                name: bytes.Bytes.dup(name),+                expected: bytes.Bytes.dup(expected),+                target: bytes.Bytes.dup(target)+            }+        )+        i+++    }+    reader.Reader.finish(r)?+    return ok out+}++pub fn free_hello(h: Hello) void = trust {+    free_list(h.capabilities)+    if h.repo.ptr != none {+        bytes.free_ptr(h.repo.ptr)+    }+    if h.client_nonce.ptr != none {+        bytes.free_ptr(h.client_nonce.ptr)+    }+}++pub fn free_hello_ok(h: HelloOk) void = trust {+    free_list(h.capabilities)+    if h.server_nonce.ptr != none {+        bytes.free_ptr(h.server_nonce.ptr)+    }+}++pub fn free_refs(rs: list[RefInfo]) void = trust {+    for r in rs {+        if r.name.ptr != none {+            bytes.free_ptr(r.name.ptr)+        }+        if r.target.ptr != none {+            bytes.free_ptr(r.target.ptr)+        }+        if r.change_id.ptr != none {+            bytes.free_ptr(r.change_id.ptr)+        }+    }+    @listfree(rs)+}++pub fn free_updates(us: list[UpdateRef]) void = trust {+    for u in us {+        if u.name.ptr != none {+            bytes.free_ptr(u.name.ptr)+        }+        if u.expected.ptr != none {+            bytes.free_ptr(u.expected.ptr)+        }+        if u.target.ptr != none {+            bytes.free_ptr(u.target.ptr)+        }+    }+    @listfree(us)+}++fn free_list(xs: list[bytes.Bytes]) void = trust {+    for x in xs {+        if x.ptr != none {+            bytes.free_owned(x)+        }+    }+    @listfree(xs)+}--- /dev/null+++ b/veins/src/protocol/promisor.sx@@ -0,0 +1,153 @@+/// Lazy chunk fetching for repositories cloned with promised blobs.++val bytes   = use("../core/bytes.sx")+val lists   = use("../core/lists.sx")+val objid   = use("../object/id.sx")+val store   = use("../store/store.sx")+val layout  = use("../store/layout.sx")+val config = use("../core/repoconfig.sx")+val client  = use("../protocol/client.sx")++fn key_for(remote: bytes.Bytes, field: bytes.Bytes) bytes.Bytes = trust {+    val out: ref u8 = @alloc(7 + remote.len + 1 + field.len) as ref u8+    @memcpy(out as ref void, c"remote." as ref void, 7)+    @memcpy(@ptradd(out, 7) as ref void, remote.ptr as ref void, remote.len)+    @store8(@ptradd(out, (7 + remote.len) as i64), 46)+    @memcpy(@ptradd(out, (8 + remote.len) as i64) as ref void, field.ptr as ref void, field.len)+    return bytes.bytes(out, 7 + remote.len + 1 + field.len)+}++val active: mut bool = false+val repo_ref: mut layout.Repo = @zeroed+val remote_ref: mut bytes.Bytes = @zeroed++pub fn configure(repo: layout.Repo, remote: bytes.Bytes) void = trust {+    if active {+        layout.free_repo(repo_ref)+        bytes.free_owned(remote_ref)+    }+    repo_ref.root = bytes.Bytes.dup(repo.root)+    remote_ref = bytes.Bytes.dup(remote)+    active = true+}++pub fn is_active() bool = {+    return active+}++fn find_sub(hay: bytes.Bytes, needle: bytes.Bytes) i64 = trust {+    if needle.len > hay.len {+        return -1+    }+    val i: mut usize = 0+    for i <= hay.len - needle.len {+        if bytes.Bytes.eql(bytes.Bytes.slice(hay, i, i + needle.len), needle) {+            return i as i64+        }+        i+++    }+    return -1+}++/// Enable lazy fetching based on the repository's promisor configuration.+pub fn ensure(handles: list[ref store.Handle]) void = trust {+    if active || @len(handles) == 0 {+        return+    }+    val h = store.handle_list_at(handles, 0)+    val path_b: bytes.Bytes = bytes.bytes(h.path.ptr, h.path.len)+    val marker: bytes.Bytes = bytes.bytes(c"/.veins/store/packs/", 20)+    val at: i64 = find_sub(path_b, marker)+    if at <= 0 {+        return+    }+    val root_b: bytes.Bytes = bytes.Bytes.slice(path_b, 0, at as usize)+    val r: layout.Repo = layout.Repo{root: bytes.Bytes.dup(root_b)}+    val pk: bytes.Bytes = bytes.bytes(c"promisor", 8)+    val pv = config.get(r, pk)+    if pv is some remote {+        configure(r, remote)+        bytes.free_owned(remote)+    }+    layout.free_repo(r)+}++fn load_chunk(id: objid.Id) option[bytes.Bytes] = trust {+    val st: store.Store = store.open_all(repo_ref)+    val loc: mut store.Loc = store.Loc{pack_index: 0, record_index: 0, kind: 0}+    val found: bool = store.find_handles(st.handles, id, loc)+    val out: mut option[bytes.Bytes] = none+    if found {+        val body = store.get_handles(st.handles, loc)+        if body is ok b {+            out = some bytes.Bytes.dup(b)+            bytes.free_owned(b)+        }+    }+    store.close(st)+    return out+}++/// Fetch one missing chunk from the promisor remote.+pub fn fetch_chunk(id: objid.Id) option[bytes.Bytes] = trust {+    if !active {+        return none+    }+    val cached = load_chunk(id)+    if cached is some c {+        return some c+    }+    val uk: bytes.Bytes = key_for(remote_ref, bytes.bytes(c"url", 3))+    val url_opt = config.get(repo_ref, uk)+    bytes.free_owned(uk)+    if url_opt is none {+        return none+    }+    val url: mut bytes.Bytes = bytes.empty()+    match url_opt {+        some uv => {+            url = uv+        }+        none => {+            return none+        }+    }+    val kk: bytes.Bytes = key_for(remote_ref, bytes.bytes(c"key", 3))+    val key_opt = config.get(repo_ref, kk)+    bytes.free_owned(kk)+    val key: mut bytes.Bytes = bytes.empty()+    if key_opt is some k {+        key = k+    }+    val pk: bytes.Bytes = key_for(remote_ref, bytes.bytes(c"tls-pin", 7))+    val pin_opt = config.get(repo_ref, pk)+    bytes.free_owned(pk)+    val pin: mut bytes.Bytes = bytes.empty()+    if pin_opt is some p {+        pin = p+    }+    val repo_name: bytes.Bytes = client.url_repo_name(url)+    val c_opt = client.connect_pinned(url, key, repo_name, pin)+    bytes.free_owned(url)+    bytes.free_owned(key)+    bytes.free_owned(pin)+    bytes.free_owned(repo_name)+    val c: mut ref client.Client = none+    match c_opt {+        some v => {+            c = v+        }+        none => {+            return none+        }+    }+    val ids: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    @append(ids, bytes.bytes(id.ptr, 32))+    val fetched: bool = client.get_chunks(c, repo_ref, ids)+    @listfree(ids)+    client.free_client(c)+    if !fetched {+        return none+    }+    return load_chunk(id)+}--- /dev/null+++ b/veins/src/protocol/transfer.sx@@ -0,0 +1,343 @@+/// View construction and chunk selection shared by clone and fetch.++val bytes   = use("../core/bytes.sx")+val lists   = use("../core/lists.sx")+val objid   = use("../object/id.sx")+val types   = use("../object/types.sx")+val tree    = use("../object/tree.sx")+val blob    = use("../object/blob.sx")+val conflict = use("../object/conflict.sx")+val graph   = use("../object/graph.sx")+val store   = use("../store/store.sx")+val state   = use("../store/state.sx")+val layout  = use("../store/layout.sx")+val idmap   = use("../store/idmap.sx")+val txnmod  = use("../store/txn.sx")+val viewops = use("../store/viewops.sx")+val view    = use("../object/view.sx")+val files   = use("../io/files.sx")+val msg_refs = use("../protocol/messages.sx")++type ChunkWalk = {+    handles: mut list[ref store.Handle]+    blobs: mut idmap.IdSet+    conflicts: mut idmap.IdSet+    chunks: mut idmap.IdSet+    out: mut list[bytes.Bytes]+    objects: mut idmap.IdSet+    obj_out: mut list[objid.Id]+}++fn id_bytes(id: objid.Id) bytes.Bytes = trust {+    return bytes.bytes(id.ptr, 32)+}++fn add_object(cw: mut ref ChunkWalk, id: objid.Id) void = trust {+    if idmap.put(cw.objects, id_bytes(id)) {+        @append(cw.obj_out, viewops.copy_id(id))+    }+}++fn walk_blob(cw: mut ref ChunkWalk, id: objid.Id) void = trust {+    if !idmap.put(cw.blobs, id_bytes(id)) {+        return+    }+    add_object(cw, id)+    val body_opt = state.read_body(cw.handles, id, types.BLOB)+    val body: mut bytes.Bytes = bytes.empty()+    if body_opt is some b {+        body = b+    } else {+        return+    }+    val dec = blob.decode(body)+    if dec is ok bl {+        if bl.form == blob.FORM_LEAF {+            for e in bl.entries {+                if idmap.put(cw.chunks, id_bytes(e.id)) {+                    val copy: ref u8 = @alloc(32) as ref u8+                    @memcpy(copy as ref void, e.id.ptr as ref void, 32)+                    @append(cw.out, bytes.bytes(copy, 32))+                    add_object(cw, e.id)+                }+            }+        } elif bl.form == blob.FORM_INTERIOR {+            for e in bl.entries {+                walk_blob(cw, e.id)+            }+        }+        blob.free_blob(bl)+    }+    files.free_buffer(body)+}++fn walk_conflict(cw: mut ref ChunkWalk, id: objid.Id) void = trust {+    if !idmap.put(cw.conflicts, id_bytes(id)) {+        return+    }+    add_object(cw, id)+    val body_opt = state.read_body(cw.handles, id, types.CONFLICT)+    val body: mut bytes.Bytes = bytes.empty()+    if body_opt is some b {+        body = b+    } else {+        return+    }+    val dec = conflict.decode(body)+    if dec is ok c {+        for v in c.adds {+            if v.target.ptr != none {+                walk_value(cw, v.kind, v.target)+            }+        }+        for v in c.removes {+            if v.target.ptr != none {+                walk_value(cw, v.kind, v.target)+            }+        }+        conflict.free_conflict(c)+    }+    files.free_buffer(body)+}++fn walk_value(cw: mut ref ChunkWalk, kind: u8, id: objid.Id) void = trust {+    if kind == tree.KIND_SUBTREE {+        walk_tree(cw, id)+    } elif kind == tree.KIND_CONFLICT {+        walk_conflict(cw, id)+    } else {+        walk_blob(cw, id)+    }+}++fn walk_tree(cw: mut ref ChunkWalk, id: objid.Id) void = trust {+    add_object(cw, id)+    val body_opt = state.read_body(cw.handles, id, types.TREE)+    val body: mut bytes.Bytes = bytes.empty()+    if body_opt is some b {+        body = b+    } else {+        return+    }+    val dec = tree.decode(body)+    if dec is ok t {+        for e in t.entries {+            if e.kind == tree.KIND_SUBTREE {+                walk_tree(cw, e.target)+            } elif e.kind == tree.KIND_CONFLICT {+                walk_conflict(cw, e.target)+            } elif e.kind != tree.KIND_SUBMODULE {+                walk_blob(cw, e.target)+            }+        }+        tree.free_tree(t)+    }+    files.free_buffer(body)+}++/// Collect the leaf chunk IDs needed by the given commits.+pub fn chunks_for_commits(+    handles: list[ref store.Handle],+    commits: list[objid.Id]+) list[bytes.Bytes] = trust {+    val cw: mut ChunkWalk = ChunkWalk{+        handles: handles,+        blobs: idmap.new(256),+        conflicts: idmap.new(64),+        chunks: idmap.new(256),+        out: lists.new[bytes.Bytes](),+        objects: idmap.new(256),+        obj_out: lists.new[objid.Id]()+    }+    for c in commits {+        val lc_opt = graph.load_commit(handles, c)+        if lc_opt is some lc {+            walk_tree(cw, lc.c.root_tree)+            graph.free_loaded(lc)+        }+    }+    idmap.free(cw.blobs)+    idmap.free(cw.conflicts)+    idmap.free(cw.chunks)+    idmap.free(cw.objects)+    free_ids_keep(cw.obj_out)+    return cw.out+}++fn free_ids_keep(xs: list[objid.Id]) void = trust {+    for x in xs {+        if x.ptr != none {+            bytes.free_owned(x)+        }+    }+    @listfree(xs)+}++/// Collect every object reachable from the given commits, including chunks.+pub fn objects_for_commits(+    handles: list[ref store.Handle],+    commits: list[objid.Id]+) list[objid.Id] = trust {+    val cw: mut ChunkWalk = ChunkWalk{+        handles: handles,+        blobs: idmap.new(256),+        conflicts: idmap.new(64),+        chunks: idmap.new(256),+        out: lists.new[bytes.Bytes](),+        objects: idmap.new(256),+        obj_out: lists.new[objid.Id]()+    }+    for c in commits {+        add_object(cw, c)+        val lc_opt = graph.load_commit(handles, c)+        if lc_opt is some lc {+            walk_tree(cw, lc.c.root_tree)+            graph.free_loaded(lc)+        }+    }+    idmap.free(cw.blobs)+    idmap.free(cw.conflicts)+    idmap.free(cw.chunks)+    idmap.free(cw.objects)+    free_id_bytes(cw.out)+    return cw.obj_out+}++pub fn free_id_bytes(xs: list[bytes.Bytes]) void = trust {+    for x in xs {+        if x.ptr != none {+            bytes.free_owned(x)+        }+    }+    @listfree(xs)+}++fn set_bookmark(v: mut ref view.View, name: bytes.Bytes, id: objid.Id) void = trust {+    val i: mut usize = 0+    for i < @len(v.bookmarks) {+        val o = @get(v.bookmarks, i)+        if o is some bm {+            if bytes.Bytes.eql(bm.name, name) {+                @listfree(bm.targets.adds)+                @listfree(bm.targets.removes)+                bm.targets = view.empty_target_set()+                @append(bm.targets.adds, viewops.copy_id(id))+                return+            }+        }+        i+++    }+    val bm: mut ref view.Bookmark = @alloc(@sizeof(view.Bookmark)) as ref view.Bookmark+    bm.name = bytes.Bytes.dup(name)+    bm.targets = view.empty_target_set()+    @append(bm.targets.adds, viewops.copy_id(id))+    @append(v.bookmarks, bm)+}++fn set_tag(v: mut ref view.View, name: bytes.Bytes, id: objid.Id) void = trust {+    val i: mut usize = 0+    for i < @len(v.tags) {+        val o = @get(v.tags, i)+        if o is some t {+            if bytes.Bytes.eql(t.name, name) {+                t.target = viewops.copy_id(id)+                return+            }+        }+        i+++    }+    val t: mut ref view.TagRef = @alloc(@sizeof(view.TagRef)) as ref view.TagRef+    t.name = bytes.Bytes.dup(name)+    t.target = viewops.copy_id(id)+    @append(v.tags, t)+}++fn set_remote(v: mut ref view.View, remote: bytes.Bytes, name: bytes.Bytes, id: objid.Id) void = trust {+    val i: mut usize = 0+    for i < @len(v.remote_refs) {+        val o = @get(v.remote_refs, i)+        if o is some rr {+            if bytes.Bytes.eql(rr.remote, remote) && bytes.Bytes.eql(rr.name, name) {+                rr.target = viewops.copy_id(id)+                return+            }+        }+        i+++    }+    val rr: mut ref view.RemoteRef = @alloc(@sizeof(view.RemoteRef)) as ref view.RemoteRef+    rr.remote = bytes.Bytes.dup(remote)+    rr.name = bytes.Bytes.dup(name)+    rr.target = viewops.copy_id(id)+    @append(v.remote_refs, rr)+}++fn has_bookmark(v: ref view.View, name: bytes.Bytes) bool = trust {+    for bm in v.bookmarks {+        if bytes.Bytes.eql(bm.name, name) {+            return true+        }+    }+    return false+}++fn set_workspace(v: mut ref view.View, id: objid.Id) void = trust {+    viewops.set_workspace(v, id)+}++pub fn default_target(refs: list[msg_refs.RefInfo]) option[objid.Id] = trust {+    for r in refs {+        if r.kind == 0 && (bytes.Bytes.eql(r.name, bytes.bytes(c"main", 4)) || bytes.Bytes.eql(r.name, bytes.bytes(c"master", 6))) {+            return some objid.id(r.target.ptr)+        }+    }+    for r in refs {+        if r.kind == 0 {+            return some objid.id(r.target.ptr)+        }+    }+    return none+}++/// Apply remote refs to the local view in one operation.+pub fn apply_refs(+    repo: layout.Repo,+    refs: list[msg_refs.RefInfo],+    remote: bytes.Bytes,+    clone: bool+) i32 = trust {+    val tx_opt = txnmod.begin(repo)+    val tx: mut ref txnmod.Txn = none+    match tx_opt {+        some t => {+            tx = t+        }+        none => {+            return 1+        }+    }+    for r in refs {+        if r.target.ptr == none {+            continue+        }+        val id: objid.Id = objid.id(r.target.ptr)+        if r.kind == 1 {+            set_tag(tx.view, r.name, id)+        } elif clone {+            set_bookmark(tx.view, r.name, id)+        } else {+            set_remote(tx.view, remote, r.name, id)+            if !has_bookmark(tx.view, r.name) {+                set_bookmark(tx.view, r.name, id)+            }+        }+    }+    viewops.rebuild_heads(tx.view)+    if clone {+        val dt = default_target(refs)+        if dt is some id2 {+            set_workspace(tx.view, id2)+        }+    }+    return txnmod.finish(tx, bytes.bytes(c"clone", 5))+}+--- /dev/null+++ b/veins/src/protocol/wire.sx@@ -0,0 +1,242 @@+/// Native protocol framing and message encoding helpers.++val bytes  = use("../core/bytes.sx")+val buf    = use("../core/buf.sx")+val reader = use("../core/reader.sx")+val lists  = use("../core/lists.sx")+val stream = use("../net/stream.sx")+val derr   = use("../core/error.sx")++pub val MAX_FRAME: usize = 16777216++pub val HELLO: u8 = 1+pub val HELLO_OK: u8 = 2+pub val AUTH: u8 = 3+pub val AUTH_OK: u8 = 4+pub val WHOAMI: u8 = 5+pub val WHOAMI_OK: u8 = 6+pub val LIST_REFS: u8 = 7+pub val REFS: u8 = 8+pub val NEGOTIATE: u8 = 9+pub val NEGOTIATE_OK: u8 = 10+pub val FETCH_SKELETON: u8 = 11+pub val GET_CHUNKS: u8 = 12+pub val HAVE_QUERY: u8 = 13+pub val HAVE_BITMAP: u8 = 14+pub val PUT_RECORDS: u8 = 15+pub val UPDATE_REFS: u8 = 16+pub val UPDATE_REFS_OK: u8 = 17+pub val RECORDS: u8 = 18+pub val END: u8 = 19+pub val ERROR: u8 = 20++pub val ERR_UNSUPPORTED_VERSION: u8 = 1+pub val ERR_BAD_FRAME: u8 = 2+pub val ERR_NOT_FOUND: u8 = 3+pub val ERR_HASH_MISMATCH: u8 = 4+pub val ERR_NON_CANONICAL: u8 = 5+pub val ERR_MISSING_CLOSURE: u8 = 6+pub val ERR_REF_CONFLICT: u8 = 7+pub val ERR_REJECTED: u8 = 8+pub val ERR_INTERNAL: u8 = 9+pub val ERR_UNAUTHENTICATED: u8 = 10+pub val ERR_FORBIDDEN: u8 = 11+pub val ERR_AUTH_FAILED: u8 = 12++pub type Frame = {+    kind: mut u8+    request_id: mut u32+    payload: mut bytes.Bytes+    base: mut bytes.Bytes+}++pub fn free_frame(f: Frame) void = trust {+    if f.base.ptr != none {+        bytes.free_ptr(f.base.ptr)+    }+}++fn read_exact(s: stream.Stream, out: ref u8, n: usize) bool = trust {+    val got: mut usize = 0+    for got < n {+        val r: i64 = stream.read(s, @ptradd(out, got as i64) as ref u8, n - got)+        if r <= 0 {+            return false+        }+        got = got + r as usize+    }+    return true+}++fn read_u32_be(s: stream.Stream) option[u32] = trust {+    val b: ref u8 = @alloc(4) as ref u8+    if !read_exact(s, b, 4) {+        @free(b as ref void)+        return none+    }+    val v: u32 = ((@load8(b) as u32) << 24)+    | ((@load8(@ptradd(b, 1)) as u32) << 16)+    | ((@load8(@ptradd(b, 2)) as u32) << 8)+    | (@load8(@ptradd(b, 3)) as u32)+    @free(b as ref void)+    return some v+}++fn put_u32_be(out: ref u8, v: u32) void = trust {+    @store8(out, ((v >> 24) & 255) as u8)+    @store8(@ptradd(out, 1), ((v >> 16) & 255) as u8)+    @store8(@ptradd(out, 2), ((v >> 8) & 255) as u8)+    @store8(@ptradd(out, 3), (v & 255) as u8)+}++/// Read one frame. Frames larger than MAX_FRAME are rejected.+pub fn read_frame(s: stream.Stream) option[Frame] = trust {+    val len_opt = read_u32_be(s)+    val len: mut u32 = 0+    match len_opt {+        some v => {+            len = v+        }+        none => {+            return none+        }+    }+    if len < 5 || len as usize > MAX_FRAME {+        return none+    }+    val body: ref u8 = @alloc(len as usize) as ref u8+    if !read_exact(s, body, len as usize) {+        @free(body as ref void)+        return none+    }+    val kind: u8 = @load8(body)+    val rid: u32 = ((@load8(@ptradd(body, 1)) as u32) << 24)+    | ((@load8(@ptradd(body, 2)) as u32) << 16)+    | ((@load8(@ptradd(body, 3)) as u32) << 8)+    | (@load8(@ptradd(body, 4)) as u32)+    val payload: mut bytes.Bytes = bytes.empty()+    if len == 5 {+        return some Frame{+            kind: kind,+            request_id: rid,+            payload: bytes.empty(),+            base: bytes.bytes(body, len as usize)+        }+    }+    payload = bytes.bytes(@ptradd(body, 5), (len - 5) as usize)+    return some Frame{+        kind: kind,+        request_id: rid,+        payload: payload,+        base: bytes.bytes(body, len as usize)+    }+}++/// Write one frame and release `payload`.+pub fn write_frame(+    s: stream.Stream,+    kind: u8,+    request_id: u32,+    payload: bytes.Bytes+) bool = trust {+    val total: u32 = 5 as u32 + payload.len as u32+    val head: ref u8 = @alloc(5) as ref u8+    put_u32_be(head, total)+    @store8(@ptradd(head, 4), kind)+    val header_bytes: bytes.Bytes = bytes.bytes(head, 5)+    val rid: ref u8 = @alloc(4) as ref u8+    put_u32_be(rid, request_id)+    val passed: bool = stream.write_all(s, header_bytes)+    && stream.write_all(s, bytes.bytes(rid, 4))+    && stream.write_all(s, payload)+    @free(head as ref void)+    @free(rid as ref void)+    if payload.ptr != none {+        bytes.free_owned(payload)+    }+    return passed+}++pub fn write_simple(s: stream.Stream, kind: u8, request_id: u32) bool = trust {+    return write_frame(s, kind, request_id, bytes.empty())+}++pub fn write_error(+    s: stream.Stream,+    request_id: u32,+    code: u8,+    message: bytes.Bytes+) bool = trust {+    val b: mut buf.Buf = buf.new(64)+    buf.Buf.put_u8(b, code)+    buf.Buf.put_length_prefixed(b, message)+    val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+    buf.Buf.free(b)+    return write_frame(s, ERROR, request_id, out)+}++pub fn read_error(payload: bytes.Bytes) u8 = {+    if payload.len == 0 {+        return ERR_INTERNAL+    }+    return bytes.Bytes.at(payload, 0)+}++pub fn put_bytes_list(b: mut buf.Buf, xs: list[bytes.Bytes]) void = trust {+    buf.Buf.put_varint(b, @len(xs) as u64)+    for x in xs {+        buf.Buf.put_length_prefixed(b, x)+    }+}++pub fn put_id_list(b: mut buf.Buf, xs: list[bytes.Bytes]) void = trust {+    buf.Buf.put_varint(b, @len(xs) as u64)+    for x in xs {+        buf.Buf.put_raw(b, x.ptr, 32)+    }+}++pub fn read_bytes_list(+    data: bytes.Bytes,+    max: usize+) result[list[bytes.Bytes], derr.DecodeError] = trust {+    val r: mut reader.Reader = reader.new(data.ptr, data.len)+    val n: usize = reader.Reader.read_list_len(r, max)?+    val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    val i: mut usize = 0+    for i < n {+        val v: bytes.Bytes = reader.Reader.read_bytes(r, MAX_FRAME)?+        @append(out, bytes.Bytes.dup(v))+        i+++    }+    reader.Reader.finish(r)?+    return ok out+}++pub fn read_id_list(+    data: bytes.Bytes,+    max: usize+) result[list[bytes.Bytes], derr.DecodeError] = trust {+    val r: mut reader.Reader = reader.new(data.ptr, data.len)+    val n: usize = reader.Reader.read_list_len(r, max)?+    val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    val i: mut usize = 0+    for i < n {+        val p: ref u8 = reader.Reader.read_id(r)?+        val copy: ref u8 = @alloc(32) as ref u8+        @memcpy(copy as ref void, p as ref void, 32)+        @append(out, bytes.bytes(copy, 32))+        i+++    }+    reader.Reader.finish(r)?+    return ok out+}++pub fn free_bytes_list(xs: list[bytes.Bytes]) void = trust {+    for x in xs {+        if x.ptr != none {+            bytes.free_owned(x)+        }+    }+    @listfree(xs)+}--- /dev/null+++ b/veins/src/server/serve.sx@@ -0,0 +1,1412 @@+/// Native veins server: stdio and TLS transports.++val stdio   = use("std/stdio")+val str     = use("std/string")+val cmsg    = use("../core/msg.sx")+val reader  = use("../core/reader.sx")+val random  = use("std/crypto/random")+val time    = use("std/time")+val bytes   = use("../core/bytes.sx")+val buf     = use("../core/buf.sx")+val lists   = use("../core/lists.sx")+val objid   = use("../object/id.sx")+val types   = use("../object/types.sx")+val tree    = use("../object/tree.sx")+val blob    = use("../object/blob.sx")+val conflict = use("../object/conflict.sx")+val commit = use("../object/commit.sx")+val view    = use("../object/view.sx")+val graph   = use("../object/graph.sx")+val store   = use("../store/store.sx")+val state   = use("../store/state.sx")+val layout  = use("../store/layout.sx")+val idmap   = use("../store/idmap.sx")+val writer  = use("../store/writer.sx")+val txnmod  = use("../store/txn.sx")+val viewops = use("../store/viewops.sx")+val zstd    = use("../store/zstd.sx")+val files   = use("../io/files.sx")+val stream  = use("../net/stream.sx")+val net     = use("std/net")+val allocators = use("std/allocators")+val wire    = use("../protocol/wire.sx")+val msg     = use("../protocol/messages.sx")+val ed      = use("../crypto/ed25519.sx")+val tls     = use("../crypto/tls.sx")+val access  = use("../auth/access.sx")+val handshake = use("../auth/handshake.sx")+val b3      = use("../crypto/blake3.sx")++val MAX_CHUNKS_PER_REQUEST: usize = 4096++type Session = {+    s: mut stream.Stream+    repo: mut layout.Repo+    repo_present: mut bool+    handles: mut list[ref store.Handle]+    store_open: mut bool+    access: mut access.Access+    hello_repo: mut bytes.Bytes+    server_nonce: mut bytes.Bytes+    client_nonce: mut bytes.Bytes+    binding: mut bytes.Bytes+    version: mut u16+    authed: mut bool+    role: mut u8+    public_key: mut bytes.Bytes+    fingerprint: mut bytes.Bytes+    haves: mut list[bytes.Bytes]+    failed_auth: mut i32+    closing: mut bool+}++fn copy_id(id: objid.Id) objid.Id = trust {+    val out: ref u8 = @alloc(32) as ref u8+    @memcpy(out as ref void, id.ptr as ref void, 32)+    return objid.id(out)+}++fn free_bytes_list(xs: list[bytes.Bytes]) void = trust {+    for x in xs {+        if x.ptr != none {+            bytes.free_owned(x)+        }+    }+    @listfree(xs)+}++fn effective_role(s: ref Session) u8 = trust {+    if s.authed {+        return s.role+    }+    if s.access.valid && s.access.anonymous_read && s.repo_present {+        return access.ROLE_READ+    }+    return access.ROLE_ANONYMOUS+}++fn deny(s: mut ref Session, rid: u32, write: bool) bool = trust {+    val role: u8 = effective_role(s)+    if write {+        if role == access.ROLE_WRITE {+            return false+        }+        if !s.authed {+            wire.write_error(s.s, rid, wire.ERR_UNAUTHENTICATED, bytes.bytes(c"authentication required", 23))+        } else {+            wire.write_error(s.s, rid, wire.ERR_FORBIDDEN, bytes.bytes(c"write role required", 19))+        }+        return true+    }+    if role == access.ROLE_READ || role == access.ROLE_WRITE {+        return false+    }+    if !s.authed {+        wire.write_error(s.s, rid, wire.ERR_UNAUTHENTICATED, bytes.bytes(c"authentication required", 23))+    } else {+        wire.write_error(s.s, rid, wire.ERR_FORBIDDEN, bytes.bytes(c"read role required", 18))+    }+    return true+}++fn log_line(s: ref Session, text: bytes.Bytes) void = trust {+    if !s.repo_present {+        return+    }+    val dir: str.StringView = layout.veins_dir(s.repo)+    val p: str.StringView = files.join(dir, str.from_cstr(c"server.log"))+    files.append_all(p, text)+    files.free_path(p)+    files.free_path(dir)+}++fn log_outcome(s: mut ref Session, outcome: bytes.Bytes) void = trust {+    if !s.repo_present {+        return+    }+    val who: bytes.Bytes = handshake.role_name(effective_role(s))+    val line: ref u8 = @fmtalloc(+        "{d} {s} {s} {s}\n",+        {+            time.unix_now_millis(),+            str.view(who.ptr, who.len as i64),+            str.view(outcome.ptr, outcome.len as i64),+            str.view(s.hello_repo.ptr, s.hello_repo.len as i64)+        }+    )+    log_line(s, bytes.from_cstr(line))+    @free(line as ref void)+}++fn safe_repo_name(name: bytes.Bytes) bool = trust {+    if name.len == 0 || name.len > 4096 {+        return false+    }+    if bytes.Bytes.at(name, 0) == 47 {+        return false+    }+    val i: mut usize = 0+    for i < name.len {+        val c: u8 = bytes.Bytes.at(name, i)+        if c == 0 || c == 92 {+            return false+        }+        i+++    }+    // Reject any path component equal to "..".+    val start: mut usize = 0+    val j: mut usize = 0+    for j <= name.len {+        if j == name.len || bytes.Bytes.at(name, j) == 47 {+            if j - start == 2+            && bytes.Bytes.at(name, start) == 46+            && bytes.Bytes.at(name, start + 1) == 46 {+                return false+            }+            start = j + 1+        }+        j+++    }+    return true+}++fn open_session_store(s: mut ref Session) void = trust {+    if s.store_open {+        return+    }+    val st: store.Store = store.open_all(s.repo)+    s.handles = st.handles+    s.store_open = true+}++fn select_repo(s: mut ref Session, root: option[layout.Repo]) void = trust {+    if s.repo_present {+        return+    }+    if root is some r {+        if !safe_repo_name(s.hello_repo) {+            return+        }+        val joined: str.StringView = files.join(+            layout.root_view(r),+            str.view(s.hello_repo.ptr, s.hello_repo.len as i64)+        )+        val found = layout.discover(joined)+        files.free_path(joined)+        if found is some repo {+            s.repo = repo+            s.repo_present = true+        }+    }+}++fn read_body(s: mut ref Session, id: objid.Id, kind: u8) option[bytes.Bytes] = trust {+    return state.read_body(s.handles, id, kind)+}++fn make_record(id: objid.Id, kind: u8, body: bytes.Bytes) bytes.Bytes = trust {+    val b: mut buf.Buf = buf.new(body.len + 64)+    buf.Buf.put_raw(b, id.ptr, 32)+    buf.Buf.put_u8(b, kind)+    buf.Buf.put_u8(b, 0)+    buf.Buf.put_varint(b, body.len as u64)+    buf.Buf.put_varint(b, body.len as u64)+    buf.Buf.put_bytes(b, body)+    val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+    buf.Buf.free(b)+    return out+}++type SendState = {+    s: mut ref Session+    rid: mut u32+    hash: mut ref void+    failed: mut bool+}++fn send_record_id(ss: mut ref SendState, id: objid.Id, kind: u8, body: bytes.Bytes) bool = trust {+    val rec: bytes.Bytes = make_record(id, kind, body)+    if ss.hash != none {+        b3.hasher_update(ss.hash, rec.ptr, rec.len)+    }+    return wire.write_frame(ss.s.s, wire.RECORDS, ss.rid, rec)+}++fn send_end(ss: mut ref SendState) bool = trust {+    val digest: ref u8 = @alloc(32) as ref u8+    b3.hasher_final(ss.hash, digest)+    val out: bytes.Bytes = bytes.bytes(digest, 32)+    val passed: bool = wire.write_frame(ss.s.s, wire.END, ss.rid, out)+    return passed+}++fn collect_tree(+    ss: mut ref SendState,+    id: objid.Id,+    seen: mut idmap.IdSet,+    send: bool+) void = trust {+    if !idmap.put(seen, copy_id_bytes(id)) {+        return+    }+    val body_opt = read_body(ss.s, id, types.TREE)+    val body: mut bytes.Bytes = bytes.empty()+    match body_opt {+        some b => {+            body = b+        }+        none => {+            ss.failed = true+            return+        }+    }+    if send {+        if !send_record_id(ss, id, types.TREE, body) {+            ss.failed = true+        }+    }+    val decoded = tree.decode(body)+    match decoded {+        ok t => {+            for e in t.entries {+                if e.kind == tree.KIND_SUBTREE {+                    collect_tree(ss, e.target, seen, send)+                } elif e.kind == tree.KIND_CONFLICT {+                    collect_object(ss, e.target, types.CONFLICT, seen, send)+                } elif e.kind != tree.KIND_SUBMODULE {+                    collect_object(ss, e.target, types.BLOB, seen, send)+                }+            }+            tree.free_tree(t)+        }+        err _ => {+            ss.failed = true+        }+    }+    files.free_buffer(body)+}++fn collect_object(+    ss: mut ref SendState,+    id: objid.Id,+    kind: u8,+    seen: mut idmap.IdSet,+    send: bool+) void = trust {+    if !idmap.put(seen, copy_id_bytes(id)) {+        return+    }+    val body_opt = read_body(ss.s, id, kind)+    val body: mut bytes.Bytes = bytes.empty()+    match body_opt {+        some b => {+            body = b+        }+        none => {+            ss.failed = true+            return+        }+    }+    if send {+        if !send_record_id(ss, id, kind, body) {+            ss.failed = true+        }+    }+    if kind == types.BLOB {+        val dec = blob.decode(body)+        if dec is ok b {+            if b.form == blob.FORM_INTERIOR {+                for e in b.entries {+                    collect_object(ss, e.id, types.BLOB, seen, send)+                }+            }+            blob.free_blob(b)+        } else {+            ss.failed = true+        }+    } elif kind == types.CONFLICT {+        val dec2 = conflict.decode(body)+        if dec2 is ok c {+            for v in c.adds {+                if v.target.ptr != none {+                    val child_kind: u8 = value_kind_to_type(v.kind)+                    if child_kind != 0 {+                        collect_object(ss, v.target, child_kind, seen, send)+                    }+                }+            }+            for v in c.removes {+                if v.target.ptr != none {+                    val child_kind2: u8 = value_kind_to_type(v.kind)+                    if child_kind2 != 0 {+                        collect_object(ss, v.target, child_kind2, seen, send)+                    }+                }+            }+            conflict.free_conflict(c)+        } else {+            ss.failed = true+        }+    }+    files.free_buffer(body)+}++fn value_kind_to_type(kind: u8) u8 = {+    if kind == tree.KIND_SUBTREE {+        return types.TREE+    }+    if kind == tree.KIND_CONFLICT {+        return types.CONFLICT+    }+    if kind == tree.KIND_FILE || kind == tree.KIND_EXECUTABLE || kind == tree.KIND_SYMLINK {+        return types.BLOB+    }+    return 0+}++fn copy_id_bytes(id: objid.Id) bytes.Bytes = trust {+    return bytes.bytes(id.ptr, 32)+}++fn handle_hello(s: mut ref Session, f: wire.Frame, root: option[layout.Repo]) bool = trust {+    val dec = msg.decode_hello(f.payload)+    val h: mut msg.Hello = msg.Hello{+        min_version: 0,+        max_version: 0,+        capabilities: lists.new[bytes.Bytes](),+        repo: bytes.empty(),+        client_nonce: bytes.empty()+    }+    match dec {+        ok v => {+            h = v+        }+        err _ => {+            wire.write_error(s.s, f.request_id, wire.ERR_BAD_FRAME, bytes.bytes(c"bad HELLO", 9))+            return false+        }+    }+    if h.min_version > msg.PROTOCOL_VERSION || h.max_version < msg.PROTOCOL_VERSION {+        wire.write_error(s.s, f.request_id, wire.ERR_UNSUPPORTED_VERSION, bytes.bytes(c"no common version", 17))+        msg.free_hello(h)+        return false+    }+    s.version = msg.PROTOCOL_VERSION+    if s.hello_repo.ptr != none {+        bytes.free_ptr(s.hello_repo.ptr)+    }+    s.hello_repo = bytes.Bytes.dup(h.repo)+    if s.client_nonce.ptr != none {+        bytes.free_ptr(s.client_nonce.ptr)+    }+    s.client_nonce = bytes.Bytes.dup(h.client_nonce)+    select_repo(s, root)+    if s.repo_present {+        s.access = access.load(s.repo)+        if !s.access.valid {+            cmsg.error_prefix()+            stdio.eprint(+                "access file error at line {d} in {s}\n",+                {s.access.error_line, layout.root_view(s.repo)}+            )+            wire.write_error(s.s, f.request_id, wire.ERR_INTERNAL, bytes.bytes(c"invalid access file", 19))+            msg.free_hello(h)+            return false+        }+        open_session_store(s)+    }+    val nonce: ref u8 = @alloc(32) as ref u8+    random.random_bytes(nonce as ref void, 32)+    s.server_nonce = bytes.bytes(nonce, 32)+    val caps: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    @append(caps, bytes.Bytes.dup(bytes.bytes(c"zstd-records", 12)))+    @append(caps, bytes.Bytes.dup(bytes.bytes(c"lazy-chunks", 11)))+    @append(caps, bytes.Bytes.dup(bytes.bytes(c"push", 4)))+    @append(caps, bytes.Bytes.dup(bytes.bytes(c"auth-ed25519", 12)))+    val auth_required: mut u8 = 1+    if s.repo_present && s.access.anonymous_read {+        auth_required = 0+    }+    val fine: msg.HelloOk = msg.HelloOk{+        version: s.version,+        capabilities: caps,+        server_nonce: s.server_nonce,+        auth_required: auth_required+    }+    val body: bytes.Bytes = msg.encode_hello_ok(fine)+    val wrote: bool = wire.write_frame(s.s, wire.HELLO_OK, f.request_id, body)+    free_caps(caps)+    msg.free_hello(h)+    return wrote+}++fn free_caps(caps: list[bytes.Bytes]) void = trust {+    for c in caps {+        if c.ptr != none {+            bytes.free_owned(c)+        }+    }+    @listfree(caps)+}++fn handle_auth(s: mut ref Session, f: wire.Frame) bool = trust {+    if s.authed {+        wire.write_error(s.s, f.request_id, wire.ERR_BAD_FRAME, bytes.bytes(c"repeated AUTH", 13))+        s.closing = true+        return false+    }+    val dec = msg.decode_auth(f.payload)+    val a: mut msg.Auth = msg.Auth{public_key: bytes.empty(), signature: bytes.empty()}+    match dec {+        ok v => {+            a = v+        }+        err _ => {+            s.failed_auth+++            wire.write_error(s.s, f.request_id, wire.ERR_AUTH_FAILED, bytes.bytes(c"authentication failed", 21))+            return false+        }+    }+    val role: mut u8 = 255+    if s.repo_present && s.access.valid {+        role = access.role_for(s.access, a.public_key)+    }+    val message: bytes.Bytes = handshake.auth_message(+        s.version,+        s.hello_repo,+        s.server_nonce,+        s.client_nonce,+        s.binding+    )+    val sig_ok: bool = role != 255 && ed.verify(a.public_key, message, a.signature)+    bytes.free_owned(message)+    if !sig_ok {+        s.failed_auth+++        wire.write_error(s.s, f.request_id, wire.ERR_AUTH_FAILED, bytes.bytes(c"authentication failed", 21))+        if a.public_key.ptr != none {+            bytes.free_ptr(a.public_key.ptr)+        }+        if a.signature.ptr != none {+            bytes.free_ptr(a.signature.ptr)+        }+        if s.failed_auth >= 3 {+            s.closing = true+        }+        return false+    }+    val fp_opt = ed.fingerprint_bytes(a.public_key)+    val fp: mut bytes.Bytes = bytes.empty()+    match fp_opt {+        some v => {+            fp = v+        }+        none => {+        }+    }+    s.authed = true+    s.role = role+    s.public_key = bytes.Bytes.dup(a.public_key)+    s.fingerprint = fp+    val fine: msg.AuthOk = msg.AuthOk{role: role, fingerprint: fp}+    val body: bytes.Bytes = msg.encode_auth_ok(fine)+    val wrote: bool = wire.write_frame(s.s, wire.AUTH_OK, f.request_id, body)+    if a.public_key.ptr != none {+        bytes.free_ptr(a.public_key.ptr)+    }+    if a.signature.ptr != none {+        bytes.free_ptr(a.signature.ptr)+    }+    log_outcome(s, bytes.bytes(c"auth-ok", 7))+    return wrote+}++fn handle_whoami(s: mut ref Session, f: wire.Frame) bool = trust {+    val role: u8 = effective_role(s)+    val b: mut buf.Buf = buf.new(64)+    buf.Buf.put_u8(b, role)+    buf.Buf.put_length_prefixed(b, s.fingerprint)+    val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+    buf.Buf.free(b)+    return wire.write_frame(s.s, wire.WHOAMI_OK, f.request_id, out)+}++fn change_id_of(s: mut ref Session, id: objid.Id) bytes.Bytes = trust {+    val lc_opt = graph.load_commit(s.handles, id)+    if lc_opt is some lc {+        val out: bytes.Bytes = bytes.Bytes.dup(+            bytes.bytes(lc.c.change_id.ptr, 16)+        )+        graph.free_loaded(lc)+        return out+    }+    return bytes.empty()+}++fn handle_list_refs(s: mut ref Session, f: wire.Frame) bool = trust {+    if deny(s, f.request_id, false) {+        return true+    }+    val v_opt = state.current_view(s.repo, s.handles)+    val v: mut ref view.View = none+    match v_opt {+        some x => {+            v = x+        }+        none => {+            v = state.empty_view()+        }+    }+    val out: mut list[msg.RefInfo] = lists.new[msg.RefInfo]()+    for bm in v.bookmarks {+        if @len(bm.targets.adds) == 1 {+            val o = @get(bm.targets.adds, 0)+            if o is some target {+                @append(+                    out,+                    msg.RefInfo{+                        name: bytes.Bytes.dup(bm.name),+                        target: bytes.Bytes.dup(bytes.bytes(target.ptr, 32)),+                        change_id: change_id_of(s, target),+                        kind: 0+                    }+                )+            }+        }+    }+    for t in v.tags {+        @append(+            out,+            msg.RefInfo{+                name: bytes.Bytes.dup(t.name),+                target: bytes.Bytes.dup(bytes.bytes(t.target.ptr, 32)),+                change_id: change_id_of(s, t.target),+                kind: 1+            }+        )+    }+    view.free_view(v)+    val body: bytes.Bytes = msg.encode_refs(out)+    msg.free_refs(out)+    log_outcome(s, bytes.bytes(c"list-refs", 9))+    return wire.write_frame(s.s, wire.REFS, f.request_id, body)+}++fn handle_negotiate(s: mut ref Session, f: wire.Frame) bool = trust {+    if deny(s, f.request_id, false) {+        return true+    }+    val dec = msg.decode_negotiate(f.payload)+    val wants: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    val haves: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    match dec {+        ok v => {+            wants = v.wants+            haves = v.haves+        }+        err _ => {+            wire.write_error(s.s, f.request_id, wire.ERR_BAD_FRAME, bytes.bytes(c"bad NEGOTIATE", 13))+            return true+        }+    }+    free_bytes_list(s.haves)+    s.haves = lists.new[bytes.Bytes]()+    val known: mut list[u64] = lists.new[u64]()+    val any_known: mut bool = false+    for h in haves {+        val found: mut bool = false+        val loc: mut store.Loc = store.Loc{pack_index: 0, record_index: 0, kind: 0}+        if store.find_handles(s.handles, objid.id(h.ptr), loc) {+            found = true+            any_known = true+        }+        val bit: mut u64 = 0+        if found {+            bit = 1+        }+        @append(known, bit)+        @append(s.haves, bytes.Bytes.dup(h))+    }+    val enough: mut u8 = 0+    if @len(haves) == 0 || any_known {+        enough = 1+    }+    val body: bytes.Bytes = msg.encode_negotiate_ok(known, enough)+    @listfree(known)+    free_bytes_list(wants)+    free_bytes_list(haves)+    return wire.write_frame(s.s, wire.NEGOTIATE_OK, f.request_id, body)+}++fn handle_fetch(s: mut ref Session, f: wire.Frame) bool = trust {+    if deny(s, f.request_id, false) {+        return true+    }+    val dec = msg.decode_ids(f.payload, 1000000)+    val wants: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    match dec {+        ok v => {+            wants = v+        }+        err _ => {+            wire.write_error(s.s, f.request_id, wire.ERR_BAD_FRAME, bytes.bytes(c"bad wants", 9))+            return true+        }+    }+    if @len(wants) == 0 {+        wire.write_error(s.s, f.request_id, wire.ERR_BAD_FRAME, bytes.bytes(c"empty wants", 11))+        free_bytes_list(wants)+        return true+    }+    val want_ids: mut list[objid.Id] = lists.new[objid.Id]()+    for w in wants {+        @append(want_ids, objid.id(w.ptr))+    }+    val all: list[objid.Id] = graph.collect(s.handles, want_ids)+    val exclude: mut idmap.IdSet = idmap.new(64)+    for h in s.haves {+        val hs: mut list[objid.Id] = lists.new[objid.Id]()+        @append(hs, objid.id(h.ptr))+        val hc = graph.collect(s.handles, hs)+        for x in hc {+            idmap.put(exclude, copy_id_bytes(x))+        }+        graph.free_ids(hc)+        @listfree(hs)+    }+    val ss_hash: ref void = @alloc(b3.hasher_state_size()) as ref void+    b3.hasher_init(ss_hash)+    val ss: mut SendState = SendState{s: s, rid: f.request_id, hash: ss_hash, failed: false}+    val seen: mut idmap.IdSet = idmap.new(256)+    val i: mut usize = 0+    for i < @len(all) {+        val o = @get(all, i)+        if o is some cid {+            if !idmap.contains(exclude, copy_id_bytes(cid)) {+                val lc_opt = graph.load_commit(s.handles, cid)+                if lc_opt is some lc {+                    if !send_record_id(ss, cid, types.COMMIT, lc.body) {+                        ss.failed = true+                    }+                    collect_tree(ss, lc.c.root_tree, seen, true)+                    graph.free_loaded(lc)+                } else {+                    ss.failed = true+                }+            }+        }+        i+++    }+    if !ss.failed {+        send_end(ss)+    }+    @free(ss_hash)+    idmap.free(seen)+    idmap.free(exclude)+    graph.free_ids(all)+    @listfree(want_ids)+    free_bytes_list(wants)+    log_outcome(s, bytes.bytes(c"fetch", 5))+    return !ss.failed+}++fn handle_get_chunks(s: mut ref Session, f: wire.Frame) bool = trust {+    if deny(s, f.request_id, false) {+        return true+    }+    val dec = msg.decode_ids(f.payload, MAX_CHUNKS_PER_REQUEST)+    val ids: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    match dec {+        ok v => {+            ids = v+        }+        err _ => {+            wire.write_error(s.s, f.request_id, wire.ERR_BAD_FRAME, bytes.bytes(c"bad chunk list", 14))+            return true+        }+    }+    val ss_hash: ref void = @alloc(b3.hasher_state_size()) as ref void+    b3.hasher_init(ss_hash)+    val ss: mut SendState = SendState{s: s, rid: f.request_id, hash: ss_hash, failed: false}+    for id in ids {+        val loc: mut store.Loc = store.Loc{pack_index: 0, record_index: 0, kind: 0}+        if !store.find_handles(s.handles, objid.id(id.ptr), loc) || loc.kind != types.CHUNK {+            ss.failed = true+            break+        }+        val body_opt = store.get_handles(s.handles, loc)+        if body_opt is ok body {+            if !send_record_id(ss, objid.id(id.ptr), types.CHUNK, body) {+                ss.failed = true+            }+            files.free_buffer(body)+        } else {+            ss.failed = true+        }+    }+    if ss.failed {+        wire.write_error(s.s, f.request_id, wire.ERR_NOT_FOUND, bytes.bytes(c"chunk not found", 15))+    } else {+        send_end(ss)+    }+    @free(ss_hash)+    free_bytes_list(ids)+    return !ss.failed+}++fn handle_have_query(s: mut ref Session, f: wire.Frame) bool = trust {+    if deny(s, f.request_id, true) {+        return true+    }+    val dec = msg.decode_ids(f.payload, 1000000)+    val ids: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    match dec {+        ok v => {+            ids = v+        }+        err _ => {+            wire.write_error(s.s, f.request_id, wire.ERR_BAD_FRAME, bytes.bytes(c"bad HAVE_QUERY", 14))+            return true+        }+    }+    val bits: mut list[u64] = lists.new[u64]()+    for id in ids {+        val loc: mut store.Loc = store.Loc{pack_index: 0, record_index: 0, kind: 0}+        val bit: mut u64 = 0+        if store.find_handles(s.handles, objid.id(id.ptr), loc) {+            bit = 1+        }+        @append(bits, bit)+    }+    val body: bytes.Bytes = msg.encode_bitmap(bits)+    @listfree(bits)+    free_bytes_list(ids)+    return wire.write_frame(s.s, wire.HAVE_BITMAP, f.request_id, body)+}++type IncomingRecord = {+    id: mut bytes.Bytes+    kind: mut u8+    body: mut bytes.Bytes+}++fn parse_record(data: bytes.Bytes) option[IncomingRecord] = trust {+    if data.len < 35 {+        return none+    }+    val r: mut reader.Reader = reader.new(data.ptr, data.len)+    val idp: ref u8 = reader.Reader.read_id(r)?+    val kind: u8 = reader.Reader.read_u8(r)?+    val comp: u8 = reader.Reader.read_u8(r)?+    val raw_len: u64 = reader.Reader.read_varint(r)?+    val stored_len: u64 = reader.Reader.read_varint(r)?+    if raw_len == 0 || raw_len > 67108864 {+        return none+    }+    val stored: bytes.Bytes = reader.Reader.read_raw(r, stored_len as usize)?+    if !reader.Reader.at_end(r) {+        return none+    }+    val idcopy: ref u8 = @alloc(32) as ref u8+    @memcpy(idcopy as ref void, idp as ref void, 32)+    if comp == 0 {+        if stored.len != raw_len as usize {+            @free(idcopy as ref void)+            return none+        }+        return some IncomingRecord{+            id: bytes.bytes(idcopy, 32),+            kind: kind,+            body: bytes.Bytes.dup(stored)+        }+    }+    val dec = zstd.decompress(stored, raw_len as usize)+    if dec is some d {+        return some IncomingRecord{+            id: bytes.bytes(idcopy, 32),+            kind: kind,+            body: d+        }+    }+    @free(idcopy as ref void)+    return none+}++fn object_exists(handles: list[ref store.Handle], id: objid.Id) bool = trust {+    val loc: mut store.Loc = store.Loc{pack_index: 0, record_index: 0, kind: 0}+    return store.find_handles(handles, id, loc)+}++fn check_closure(handles: list[ref store.Handle], id: objid.Id, kind: u8) bool = trust {+    val body_opt = state.read_body(handles, id, kind)+    val body: mut bytes.Bytes = bytes.empty()+    if body_opt is some b {+        body = b+    } else {+        return false+    }+    val fine: mut bool = true+    if kind == types.COMMIT {+        val dec = commit.decode(body)+        if dec is ok c {+            if !object_exists(handles, c.root_tree) {+                fine = false+            }+            for p in c.parents {+                if !object_exists(handles, p) {+                    fine = false+                }+            }+            commit.free_commit(c)+        } else {+            fine = false+        }+    } elif kind == types.TREE {+        val dec = tree.decode(body)+        if dec is ok t {+            for e in t.entries {+                if e.kind != tree.KIND_SUBMODULE && !object_exists(handles, e.target) {+                    fine = false+                }+            }+            tree.free_tree(t)+        } else {+            fine = false+        }+    } elif kind == types.BLOB {+        val dec = blob.decode(body)+        if dec is ok b {+            for e in b.entries {+                if !object_exists(handles, e.id) {+                    fine = false+                }+            }+            blob.free_blob(b)+        } else {+            fine = false+        }+    } elif kind == types.CONFLICT {+        val dec = conflict.decode(body)+        if dec is ok c {+            for v in c.adds {+                if v.target.ptr != none && !object_exists(handles, v.target) {+                    fine = false+                }+            }+            for v in c.removes {+                if v.target.ptr != none && !object_exists(handles, v.target) {+                    fine = false+                }+            }+            conflict.free_conflict(c)+        } else {+            fine = false+        }+    }+    files.free_buffer(body)+    return fine+}++fn handle_put_records(s: mut ref Session, f: wire.Frame) bool = trust {+    if deny(s, f.request_id, true) {+        return true+    }+    val w_opt = writer.open(s.repo)+    val w: mut ref writer.Writer = none+    match w_opt {+        some x => {+            w = x+        }+        none => {+            wire.write_error(s.s, f.request_id, wire.ERR_INTERNAL, bytes.bytes(c"cannot write", 12))+            return true+        }+    }+    val hash: ref void = @alloc(b3.hasher_state_size()) as ref void+    b3.hasher_init(hash)+    val failed: mut bool = false+    val accepted: mut list[objid.Id] = lists.new[objid.Id]()+    for {+        val nf = wire.read_frame(s.s)+        val fr: mut wire.Frame = wire.Frame{+            kind: 0,+            request_id: 0,+            payload: bytes.empty(),+            base: bytes.empty()+        }+        match nf {+            some x => {+                fr = x+            }+            none => {+                failed = true+                break+            }+        }+        if fr.kind == wire.END {+            val got: bytes.Bytes = fr.payload+            val digest: ref u8 = @alloc(32) as ref u8+            b3.hasher_final(hash, digest)+            if got.len != 32 || !bytes.Bytes.eql(bytes.bytes(digest, 32), got) {+                failed = true+            }+            @free(digest as ref void)+            wire.free_frame(fr)+            break+        }+        if fr.kind != wire.RECORDS {+            wire.free_frame(fr)+            failed = true+            break+        }+        b3.hasher_update(hash, fr.payload.ptr, fr.payload.len)+        val pr = parse_record(fr.payload)+        if pr is some rec {+            val computed: objid.Id = objid.object_id(rec.kind, rec.body)+            if !objid.Id.eql(computed, objid.id(rec.id.ptr)) {+                failed = true+            } else {+                writer.add_known(w, rec.kind, objid.id(rec.id.ptr), rec.body)+                @append(accepted, copy_id(objid.id(rec.id.ptr)))+            }+            bytes.free_ptr(computed.ptr)+            bytes.free_ptr(rec.id.ptr)+        } else {+            failed = true+        }+        wire.free_frame(fr)+        if failed {+            break+        }+    }+    @free(hash as ref void)+    if failed {+        writer.abort(w)+        wire.write_error(s.s, f.request_id, wire.ERR_HASH_MISMATCH, bytes.bytes(c"record rejected", 15))+        return true+    }+    val passed: bool = writer.finish(w)+    if !passed {+        wire.write_error(s.s, f.request_id, wire.ERR_INTERNAL, bytes.bytes(c"pack write failed", 17))+        return true+    }+    open_session_store(s)+    val closure_ok: mut bool = true+    for id in accepted {+        val loc: mut store.Loc = store.Loc{pack_index: 0, record_index: 0, kind: 0}+        if store.find_handles(s.handles, id, loc) {+            if !check_closure(s.handles, id, loc.kind) {+                closure_ok = false+                break+            }+        }+    }+    for id in accepted {+        if id.ptr != none {+            bytes.free_ptr(id.ptr)+        }+    }+    @listfree(accepted)+    if !closure_ok {+        return wire.write_error(s.s, f.request_id, wire.ERR_MISSING_CLOSURE, bytes.bytes(c"missing object closure", 22))+    }+    return wire.write_frame(s.s, wire.END, f.request_id, bytes.empty())+}++fn find_bookmark(v: ref view.View, name: bytes.Bytes) i32 = trust {+    val i: mut usize = 0+    for i < @len(v.bookmarks) {+        val o = @get(v.bookmarks, i)+        if o is some bm {+            if bytes.Bytes.eql(bm.name, name) {+                return i as i32+            }+        }+        i+++    }+    return -1+}++fn find_tag(v: ref view.View, name: bytes.Bytes) i32 = trust {+    val i: mut usize = 0+    for i < @len(v.tags) {+        val o = @get(v.tags, i)+        if o is some t {+            if bytes.Bytes.eql(t.name, name) {+                return i as i32+            }+        }+        i+++    }+    return -1+}++fn first_target(ts: view.TargetSet) option[objid.Id] = trust {+    if @len(ts.adds) > 0 {+        return @get(ts.adds, 0)+    }+    return none+}++fn ref_matches(v: ref view.View, name: bytes.Bytes, expected: bytes.Bytes) bool = trust {+    val bm = find_bookmark(v, name)+    val tg = find_tag(v, name)+    val current: mut option[objid.Id] = none+    if bm >= 0 {+        val o = @get(v.bookmarks, bm as usize)+        if o is some b {+            current = first_target(b.targets)+        }+    } elif tg >= 0 {+        val o2 = @get(v.tags, tg as usize)+        if o2 is some t {+            current = some t.target+        }+    }+    if expected.ptr == none {+        if current is none {+            return true+        }+        return false+    }+    if current is some id {+        return objid.Id.eql(id, objid.id(expected.ptr))+    }+    return false+}++fn apply_ref(v: mut ref view.View, name: bytes.Bytes, target: bytes.Bytes) void = trust {+    val bm = find_bookmark(v, name)+    if target.ptr == none {+        if bm >= 0 {+            val o = @get(v.bookmarks, bm as usize)+            if o is some b {+                @listfree(b.targets.adds)+                @listfree(b.targets.removes)+                if b.name.ptr != none {+                    bytes.free_ptr(b.name.ptr)+                }+                @free(b as ref void)+            }+            @remove(v.bookmarks, bm as usize)+        }+        val tg = find_tag(v, name)+        if tg >= 0 {+            val o2 = @get(v.tags, tg as usize)+            if o2 is some t {+                if t.name.ptr != none {+                    bytes.free_ptr(t.name.ptr)+                }+                @free(t as ref void)+            }+            @remove(v.tags, tg as usize)+        }+        return+    }+    val tid: objid.Id = objid.id(target.ptr)+    if bm >= 0 {+        val o3 = @get(v.bookmarks, bm as usize)+        if o3 is some b3v {+            @listfree(b3v.targets.adds)+            @listfree(b3v.targets.removes)+            b3v.targets = view.empty_target_set()+            @append(b3v.targets.adds, copy_id(tid))+        }+        return+    }+    val tg2 = find_tag(v, name)+    if tg2 >= 0 {+        val o4 = @get(v.tags, tg2 as usize)+        if o4 is some t2 {+            t2.target = copy_id(tid)+        }+        return+    }+    val nb: mut ref view.Bookmark = @alloc(@sizeof(view.Bookmark)) as ref view.Bookmark+    nb.name = bytes.Bytes.dup(name)+    nb.targets = view.empty_target_set()+    @append(nb.targets.adds, copy_id(tid))+    @append(v.bookmarks, nb)+}++fn handle_update_refs(s: mut ref Session, f: wire.Frame) bool = trust {+    if deny(s, f.request_id, true) {+        return true+    }+    val dec = msg.decode_update_refs(f.payload)+    val updates: mut list[msg.UpdateRef] = lists.new[msg.UpdateRef]()+    match dec {+        ok v => {+            updates = v+        }+        err _ => {+            wire.write_error(s.s, f.request_id, wire.ERR_BAD_FRAME, bytes.bytes(c"bad UPDATE_REFS", 15))+            return true+        }+    }+    val tx_opt = txnmod.begin(s.repo)+    val tx: mut ref txnmod.Txn = none+    match tx_opt {+        some t => {+            tx = t+        }+        none => {+            msg.free_updates(updates)+            wire.write_error(s.s, f.request_id, wire.ERR_INTERNAL, bytes.bytes(c"cannot update refs", 18))+            return true+        }+    }+    val conflict: mut bool = false+    for u in updates {+        if !ref_matches(tx.view, u.name, u.expected) {+            conflict = true+            break+        }+    }+    if conflict {+        txnmod.abort(tx)+        msg.free_updates(updates)+        return wire.write_error(s.s, f.request_id, wire.ERR_REF_CONFLICT, bytes.bytes(c"ref changed", 11))+    }+    for u in updates {+        apply_ref(tx.view, u.name, u.target)+    }+    viewops.rebuild_heads(tx.view)+    val status: i32 = txnmod.finish(tx, bytes.bytes(c"remote push", 11))+    msg.free_updates(updates)+    if status != 0 {+        return wire.write_error(s.s, f.request_id, wire.ERR_INTERNAL, bytes.bytes(c"commit failed", 13))+    }+    val fp_text: bytes.Bytes = ed.base32_text(s.fingerprint)+    val line: ref u8 = @fmtalloc(+        "{d} {s} update-refs\n",+        {time.unix_now_millis(), str.view(fp_text.ptr, fp_text.len as i64)}+    )+    log_line(s, bytes.from_cstr(line))+    @free(line as ref void)+    bytes.free_owned(fp_text)+    return wire.write_simple(s.s, wire.UPDATE_REFS_OK, f.request_id)+}++fn dispatch(s: mut ref Session, f: wire.Frame, root: option[layout.Repo]) bool = trust {+    if f.kind == wire.HELLO {+        return handle_hello(s, f, root)+    }+    if f.kind == wire.AUTH {+        return handle_auth(s, f)+    }+    if f.kind == wire.WHOAMI {+        return handle_whoami(s, f)+    }+    if !s.repo_present {+        wire.write_error(s.s, f.request_id, wire.ERR_UNAUTHENTICATED, bytes.bytes(c"authentication required", 23))+        return true+    }+    if f.kind == wire.LIST_REFS {+        return handle_list_refs(s, f)+    }+    if f.kind == wire.NEGOTIATE {+        return handle_negotiate(s, f)+    }+    if f.kind == wire.FETCH_SKELETON {+        return handle_fetch(s, f)+    }+    if f.kind == wire.GET_CHUNKS {+        return handle_get_chunks(s, f)+    }+    if f.kind == wire.HAVE_QUERY {+        return handle_have_query(s, f)+    }+    if f.kind == wire.PUT_RECORDS {+        return handle_put_records(s, f)+    }+    if f.kind == wire.UPDATE_REFS {+        return handle_update_refs(s, f)+    }+    return wire.write_error(s.s, f.request_id, wire.ERR_BAD_FRAME, bytes.bytes(c"unknown request", 15))+}++fn free_session(s: mut ref Session) void = trust {+    if s.store_open {+        store.close_handles(s.handles)+    }+    if s.repo_present {+        access.free(s.access)+        layout.free_repo(s.repo)+    }+    free_bytes_list(s.haves)+    if s.hello_repo.ptr != none {+        bytes.free_ptr(s.hello_repo.ptr)+    }+    if s.server_nonce.ptr != none {+        bytes.free_ptr(s.server_nonce.ptr)+    }+    if s.client_nonce.ptr != none {+        bytes.free_ptr(s.client_nonce.ptr)+    }+    if s.binding.ptr != none {+        bytes.free_ptr(s.binding.ptr)+    }+    if s.public_key.ptr != none {+        bytes.free_ptr(s.public_key.ptr)+    }+    if s.fingerprint.ptr != none {+        bytes.free_ptr(s.fingerprint.ptr)+    }+    @free(s as ref void)+}++/// Serve one connection. `root` is set for `-listen`, `fixed` for `-stdio`.+pub fn session(+    st: stream.Stream,+    fixed: option[layout.Repo],+    root: option[layout.Repo],+    binding: bytes.Bytes+) void = trust {+    val s: mut ref Session = @alloc(@sizeof(Session)) as ref Session+    s.s = st+    s.repo = layout.Repo{root: bytes.empty()}+    s.repo_present = false+    s.handles = lists.new[ref store.Handle]()+    s.store_open = false+    s.access = access.empty()+    s.hello_repo = bytes.empty()+    s.server_nonce = bytes.empty()+    s.client_nonce = bytes.empty()+    s.binding = bytes.Bytes.dup(binding)+    s.version = msg.PROTOCOL_VERSION+    s.authed = false+    s.role = access.ROLE_ANONYMOUS+    s.public_key = bytes.empty()+    s.fingerprint = bytes.empty()+    s.haves = lists.new[bytes.Bytes]()+    s.failed_auth = 0+    s.closing = false+    if fixed is some repo {+        s.repo = repo+        s.repo_present = true+        s.access = access.load(repo)+        if s.access.valid {+            open_session_store(s)+        }+    }+    for !s.closing {+        val f_opt = wire.read_frame(st)+        val f: mut wire.Frame = wire.Frame{+            kind: 0,+            request_id: 0,+            payload: bytes.empty(),+            base: bytes.empty()+        }+        match f_opt {+            some x => {+                f = x+            }+            none => {+                break+            }+        }+        val keep: bool = dispatch(s, f, root)+        wire.free_frame(f)+        if !keep {+            break+        }+    }+    log_outcome(s, bytes.bytes(c"close", 5))+    stream.close(st)+    free_session(s)+}++pub fn serve_stdio(repo: layout.Repo) i32 = trust {+    val st: stream.Stream = stream.stdio_stream()+    session(st, some repo, none, bytes.empty())+    return 0+}++fn parse_port(addr: bytes.Bytes) option[i32] = trust {+    val colon: mut i64 = -1+    val i: mut usize = 0+    for i < addr.len {+        if bytes.Bytes.at(addr, i) == 58 {+            colon = i as i64+        }+        i+++    }+    if colon < 0 || colon as usize + 1 >= addr.len {+        return none+    }+    val port: mut i32 = 0+    val j: mut usize = (colon as usize) + 1+    for j < addr.len {+        val c: u8 = bytes.Bytes.at(addr, j)+        if c < 48 || c > 57 {+            return none+        }+        port = port * 10 + (c - 48) as i32+        j+++    }+    return some port+}++pub fn serve_listen(+    addr: bytes.Bytes,+    root: layout.Repo,+    cert: bytes.Bytes,+    key: bytes.Bytes+) i32 = trust {+    val port_opt = parse_port(addr)+    val port: mut i32 = 0+    match port_opt {+        some p => {+            port = p+        }+        none => {+            cmsg.error_prefix()+            stdio.eprint("invalid listen address\n", {})+            return 1+        }+    }+    val cert_z: ref u8 = bytes.Bytes.to_cstr(cert)+    val key_z: ref u8 = bytes.Bytes.to_cstr(key)+    val ctx: ref void = tls.server_ctx(cert_z, key_z)+    @free(cert_z as ref void)+    @free(key_z as ref void)+    if ctx == none {+        cmsg.error_prefix()+        stdio.eprint("cannot load TLS certificate or key\n", {})+        return 1+    }+    val ac: allocators.HeapAllocator = @zeroed+    val server = net.TcpServer.listen[allocators.HeapAllocator](ac, port)+    if server == none {+        cmsg.error_prefix()+        stdio.eprint("cannot listen on port {d}\n", {port})+        tls.free_ctx(ctx)+        return 1+    }+    cmsg.info_prefix()+    stdio.print("listening on {s}\n", {addr})+    for {+        val fd: i64 = net.TcpServer.accept(server)+        if fd < 0 {+            break+        }+        val ssl: ref void = tls.accept(ctx, fd as i32)+        if ssl == none {+            net.TcpServer.close_client(fd)+            continue+        }+        val binding: ref u8 = @alloc(32) as ref u8+        val exported: bool = tls.exporter(ssl, binding, 32)+        val st: stream.Stream = stream.tls_stream(fd as i32, ssl)+        val bind: mut bytes.Bytes = bytes.empty()+        if exported {+            bind = bytes.bytes(binding, 32)+        }+        val no_repo: option[layout.Repo] = none+        session(st, no_repo, some root, bind)+        @free(binding as ref void)+    }+    net.TcpServer.close[allocators.HeapAllocator](ac, server)+    tls.free_ctx(ctx)+    return 0+}--- a/veins/src/store/state.sx+++ b/veins/src/store/state.sx@@ -61,6 +61,7 @@     val decoded = view.decode(body)     match decoded {         ok v => {+            v.owned = body             return some v         }         err _ => {@@ -87,6 +88,7 @@     val decoded = operation.decode(body)     match decoded {         ok op => {+            op.owned = body             return some op         }         err _ => {@@ -186,6 +188,7 @@ ) option[ref view.View] = trust {     val hs: list[objid.Id] = heads(repo)     if @len(hs) == 0 {+        @listfree(hs)         return none     }     val first = @get(hs, 0)@@ -227,6 +230,7 @@     v.tags = lists.new[ref view.TagRef]()     v.remote_refs = lists.new[ref view.RemoteRef]()     v.working_copies = lists.new[ref view.WorkspaceRef]()+    v.owned = bytes.empty()     return v } --- a/veins/src/store/txn.sx+++ b/veins/src/store/txn.sx@@ -449,6 +449,7 @@     op.username = username     op.description = bytes.Bytes.dup(description)     op.tags = tags+    op.owned = bytes.empty()     val op_body: bytes.Bytes = operation.encode(op)     val op_id: objid.Id = writer.add(tx.writer, types.OPERATION, op_body)     operation.free_operation(op)--- a/veins/src/store/writer.sx+++ b/veins/src/store/writer.sx@@ -175,11 +175,17 @@                 err _ => {                 }             }+            allocators.HeapAllocator.free(ac, t)         }         j++     }-    for job in jobs {-        val _ = job+    val jf: mut usize = 0+    for jf < @len(jobs) {+        val jo = @get(jobs, jf)+        if jo is some jobp {+            @free(jobp as ref void)+        }+        jf++     }     @listfree(jobs)     @listfree(thread_refs)--- a/veins/src/worktree/checkout.sx+++ b/veins/src/worktree/checkout.sx@@ -23,6 +23,7 @@ val state      = use("../store/state.sx") val txn        = use("../store/txn.sx") val viewops    = use("../store/viewops.sx")+val promisor = use("../protocol/promisor.sx") val snapshot   = use("../worktree/snapshot.sx") val files      = use("../io/files.sx") val native     = use("../io/native.sx")@@ -392,7 +393,14 @@     } elif b.form == blob.FORM_LEAF {         for e in b.entries {             val chunk_opt = state.read_body(handles, e.id, types.CHUNK)-            match chunk_opt {+            val chunk2: mut option[bytes.Bytes] = chunk_opt+            if chunk2 is none {+                promisor.ensure(handles)+                if promisor.is_active() {+                    chunk2 = promisor.fetch_chunk(e.id)+                }+            }+            match chunk2 {                 some chunk => {                     if !native.write_fd_all(fd, chunk) {                         success = false@@ -1324,9 +1332,13 @@             git_usable = false         }     }+    promisor.ensure(handles)     val count: usize = cpu_count()     val n: usize = @len(tasks)     val workers: mut usize = count+    if promisor.is_active() {+        workers = 1+    }     if workers < 1 {         workers = 1     }@@ -1338,6 +1350,7 @@     if n == 0 {         workers = 0     }+    val use_threads: bool = !promisor.is_active()     val w: mut usize = 0     for w < workers {         val job: mut ref CheckoutJob = @alloc(@sizeof(CheckoutJob)) as ref CheckoutJob@@ -1352,15 +1365,19 @@         job.git_lock = git_lock         job.has_git = git_usable         @append(jobs, job)-        val tr = thread.Thread.new[allocators.HeapAllocator](ac, checkout_worker, job as ref void)-        match tr {-            ok t => {-                @append(thread_refs, t)-            }-            err _ => {-                job.failed = true-                job.error = bytes.Bytes.dup(bytes.from_cstr(c"cannot start checkout thread"))+        if use_threads {+            val tr = thread.Thread.new[allocators.HeapAllocator](ac, checkout_worker, job as ref void)+            match tr {+                ok t => {+                    @append(thread_refs, t)+                }+                err _ => {+                    job.failed = true+                    job.error = bytes.Bytes.dup(bytes.from_cstr(c"cannot start checkout thread"))+                }             }+        } else {+            checkout_worker(job as ref void)         }         w++     }@@ -1371,13 +1388,15 @@     for j < @len(jobs) {         val job = @get(jobs, j)         if job is some jb {-            val tr = @get(thread_refs, j)-            if tr is some t {-                val joined = thread.Thread.join[allocators.HeapAllocator](ac, t)-                match joined {-                    ok _ => {-                    }-                    err _ => {+            if use_threads {+                val tr = @get(thread_refs, j)+                if tr is some t {+                    val joined = thread.Thread.join[allocators.HeapAllocator](ac, t)+                    match joined {+                        ok _ => {+                        }+                        err _ => {+                        }                     }                 }             }@@ -1614,6 +1633,53 @@     }     if old_root is some or3 {         free_id(or3)+    }+    return status+}++/// Materialize the working-copy commit without snapshotting first. Used after+/// a clone, when the directory is empty and must not become a new commit.+pub fn materialize_working_copy(repo: layout.Repo) i32 = trust {+    val st: store.Store = store.open_all(repo)+    val v_opt = state.current_view(repo, st.handles)+    val v: mut ref view.View = none+    match v_opt {+        some x => {+            v = x+        }+        none => {+            store.close(st)+            return 1+        }+    }+    val wc_opt = viewops.working_copy(v)+    view.free_view(v)+    val wc: mut objid.Id = objid.id_none()+    match wc_opt {+        some id => {+            wc = id+        }+        none => {+            store.close(st)+            return 1+        }+    }+    val root_opt = tree_of_commit(st.handles, wc)+    val root: mut objid.Id = objid.id_none()+    match root_opt {+        some r => {+            root = r+        }+        none => {+            store.close(st)+            free_id(wc)+            return 1+        }     }+    val old_none: option[objid.Id] = none+    val status: i32 = materialize_commit(repo, st.handles, old_none, root)+    store.close(st)+    free_id(wc)+    free_id(root)     return status }