//! `twigpine model` — open-weight model publishing (KTD14). //! //! `twigpine model publish` runs inside a local clone of a fully public //! Twigpine repo: it classifies files by the chunking threshold, packs the //! large ones into content blocks with cross-release dedup, uploads the new //! blocks under an upload session (resuming from a `.git` state file after an //! interruption), commits the signed manifest, pushes, claims the release, //! and polls until the node's verification publishes or rejects it. If the //! release is still verifying when the poll budget expires, the command //! exits non-zero with the status URL to check later. use anyhow::{bail, Context, Result}; use clap::{Args, Subcommand}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::collections::{HashMap, HashSet}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use std::process::Output; use std::time::{Duration, Instant}; use twigpine_core::cid::sha256_hex; use twigpine_core::model::manifest::{ self, detect_format, Manifest, ManifestFile, ParentRef, ReconstructionRef, StorageKind, MANIFEST_SCHEMA_V1, }; use twigpine_core::model::reconstruction::{ pack_file_with, BlockEntry, DedupIndex, Reconstruction, }; use crate::http::{json_or_denial, read_body_capped_bytes, read_json, NodeClient}; use crate::identity::load_keypair_from_dir; const DEFAULT_CHUNK_THRESHOLD: u64 = 10 * 1024 * 1024; const SESSION_HEADER: &str = "x-twigpine-model-session"; const STATE_FILE_NAME: &str = "twigpine-model-publish.json"; const GITIGNORE_BEGIN: &str = "# >>> twigpine-model-publish >>>"; const GITIGNORE_END: &str = "# <<< twigpine-model-publish <<<"; /// huggingface_hub 2.x refuses plain downloads of a single file past this. const SINGLE_FILE_WARN_BYTES: u64 = 50 << 30; /// Bound on a fetched prior reconstruction object: big models name thousands /// of blocks but the object is small JSON; a runaway body is not one. const RECONSTRUCTION_FETCH_CAP: usize = 64 * 1024 * 1024; const POLL_INTERVAL: Duration = Duration::from_secs(3); const POLL_BUDGET: Duration = Duration::from_secs(300); #[derive(Subcommand)] pub enum ModelCmd { /// Publish the working tree as a signed model release; polls until the /// release publishes or is rejected, exiting non-zero when it is still /// verifying after the poll budget Publish(PublishArgs), } #[derive(Args)] pub struct PublishArgs { /// Node base URL (or set TWIGPINE_NODE) #[arg( long, default_value = "https://node.twigpine.com", env = "TWIGPINE_NODE" )] pub node: String, /// Skip the permanence confirmation (for scripts) #[arg(long)] pub yes: bool, /// Declare a parent release: /@ #[arg(long)] pub parent: Option, /// License identifier recorded in the manifest #[arg(long, default_value = "")] pub license: String, /// Branch to push the release commit to (default: current branch) #[arg(long)] pub branch: Option, /// Chunking threshold in bytes; files at or above it are stored as /// content blocks instead of git blobs #[arg(long, hide = true, default_value_t = DEFAULT_CHUNK_THRESHOLD)] pub chunk_threshold_bytes: u64, /// Identity directory override #[arg(long)] pub dir: Option, } pub async fn run(cmd: ModelCmd) -> Result<()> { match cmd { ModelCmd::Publish(a) => cmd_publish(a).await, } } // ── git helpers ───────────────────────────────────────────────────────────── fn git(root: &Path, args: &[&str]) -> Result { // allow-unbounded-git: short-lived CLI process; there is no request // permit to hold or client disconnect to outlive. let out = std::process::Command::new("git") .args(args) .current_dir(root) .output() .context("failed to run git")?; if !out.status.success() { bail!( "git {} failed: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim() ); } Ok(out) } fn git_lines(root: &Path, args: &[&str]) -> Result> { let out = git(root, args)?; let text = String::from_utf8(out.stdout).context("git output was not utf-8")?; Ok(text .lines() .map(str::trim) .filter(|l| !l.is_empty()) .map(str::to_string) .collect()) } /// `git` with `GIT_INDEX_FILE` pointed at a dedicated index, so the release /// commit is built from an index the user's own staging never touches. fn git_index(root: &Path, index: &Path, args: &[&str]) -> Result { let out = std::process::Command::new("git") .args(args) .current_dir(root) .env("GIT_INDEX_FILE", index) .output() .context("failed to run git")?; if !out.status.success() { bail!( "git {} failed: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim() ); } Ok(out) } fn git_nul(root: &Path, args: &[&str]) -> Result> { let out = git(root, args)?; let text = String::from_utf8(out.stdout).context("git output was not utf-8")?; Ok(text .split('\0') .filter(|s| !s.is_empty()) .map(str::to_string) .collect()) } /// `git log` for the release-marker path, newest first; an unborn HEAD just /// has none. Capped: each commit costs one reconstruction fetch for dedup. fn release_commits(root: &Path) -> Vec { git_lines( root, &[ "log", "--format=%H", "-n", "8", "--", ".twigpine/model-release.json", ], ) .unwrap_or_default() } fn repo_root() -> Result { // allow-unbounded-git: short-lived CLI process; there is no request // permit to hold or client disconnect to outlive. let out = std::process::Command::new("git") .args(["rev-parse", "--show-toplevel"]) .output() .context("failed to run git")?; if !out.status.success() { bail!("not inside a git repository"); } let text = String::from_utf8(out.stdout).context("git output was not utf-8")?; Ok(PathBuf::from(text.trim())) } fn git_dir(root: &Path) -> Result { let lines = git_lines(root, &["rev-parse", "--git-dir"])?; let dir = PathBuf::from(lines.first().context("no git dir")?); Ok(if dir.is_absolute() { dir } else { root.join(dir) }) } /// Parse a `twigpine:///` (or `gitlawb://`) remote URL. fn parse_remote_url(url: &str) -> Option<(String, String)> { let rest = twigpine_core::url_scheme::strip_scheme(url.trim())?; let slash = rest.rfind('/')?; let did = rest[..slash].to_string(); let repo = twigpine_core::ucan::push::canonical_repo_name(&rest[slash + 1..]).to_string(); if did.is_empty() || repo.is_empty() { return None; } Some((did, repo)) } /// The remote name plus (owner did, repo) of the first remote carrying a /// twigpine URL: origin first, then twigpine/gitlawb, then any other. fn detect_remote(root: &Path) -> Result<(String, String, String)> { let names = git_lines(root, &["remote"])?; let preferred = ["origin", "twigpine", "gitlawb"]; let ordered = preferred .iter() .filter(|p| names.iter().any(|n| n == *p)) .map(|p| p.to_string()) .chain( names .iter() .filter(|n| !preferred.contains(&n.as_str())) .cloned(), ); for name in ordered { for extra in [&["--all"][..], &["--push", "--all"][..]] { let mut args = vec!["remote", "get-url"]; args.extend_from_slice(extra); args.push(&name); let Ok(urls) = git_lines(root, &args) else { continue; }; if let Some((did, repo)) = urls.iter().find_map(|u| parse_remote_url(u)) { // The push must land on the repo the session and claim calls // use: a push URL naming a different twigpine repo is an // ambiguous destination, not a slow failure after upload. let push_urls = git_lines(root, &["remote", "get-url", "--push", "--all", &name]) .unwrap_or_default(); for u in &push_urls { if let Some((pdid, prepo)) = parse_remote_url(u) { if pdid != did || prepo != repo { bail!( "remote {name} pushes to {pdid}/{prepo} but fetches from \ {did}/{repo}; fix the remote's push URL and retry" ); } } } return Ok((name, did, repo)); } } } bail!("no twigpine:// (or gitlawb://) remote found; run inside a clone of the repo") } // ── file classification ───────────────────────────────────────────────────── #[derive(Debug, PartialEq, Eq)] enum Class { /// Listed in the manifest with `storage: "git"` and committed. Git, /// Listed with `storage: "chunked"`, packed into blocks, gitignored. Chunked, /// At or over the threshold but git-tracked: refused (weights live /// outside git). LargeTracked, /// Untracked and ignored, so not part of the publishable set. Ignored, } /// The publishable set is git's own view of the tree: tracked files plus /// untracked files that are not ignored. An ignored file only comes back in /// at threshold size and only while it sits inside the managed .gitignore /// block, which is how previously published chunked paths stay findable on /// re-publish without sweeping ignored junk (a `target/` dir) into a release. fn classify(size: u64, tracked: bool, ignored: bool, managed: bool, threshold: u64) -> Class { if size >= threshold { if tracked { Class::LargeTracked } else if ignored && !managed { Class::Ignored } else { Class::Chunked } } else if ignored { Class::Ignored } else { Class::Git } } struct Scan { /// Repo-relative paths committed as git blobs. git_files: Vec, /// Repo-relative paths packed as content blocks. chunked_files: Vec, /// Tracked files at or over the threshold: the refusal list. refused: Vec, /// Ignored files at or over the threshold that are not managed: warned /// and skipped (see [`classify`]). skipped_ignored: Vec, /// Tracked paths gone from the worktree but not staged for deletion: /// staged into the release commit without entering the manifest. deleted: Vec, } /// Tracked paths from `git ls-files -s`, minus submodule gitlinks (mode /// 160000): a gitlink has no blob to hash and is not a manifest file. fn tracked_paths(root: &Path) -> Result> { let entries = git_nul(root, &["ls-files", "-s", "-z"])?; let mut out = HashSet::new(); for e in entries { let Some((meta, name)) = e.split_once('\t') else { continue; }; if meta.starts_with("160000 ") { continue; } out.insert(name.to_string()); } Ok(out) } /// Paths listed inside the managed .gitignore block (empty when there is no /// block): previously published chunked files. /// One repo-relative path as a gitignore pattern line: anchored at the repo /// root so it matches only this path, with pattern metacharacters and a /// trailing space backslash-escaped. fn escape_gitignore_path(p: &str) -> String { let mut out = String::from("/"); let mut chars = p.chars().peekable(); while let Some(c) = chars.next() { if matches!(c, '\\' | '!' | '#' | '[' | ']' | '*' | '?') { out.push('\\'); } if c == ' ' && chars.peek().is_none() { out.push('\\'); } out.push(c); } out } fn unescape_gitignore_path(line: &str) -> String { // Generated patterns are root-anchored; older unanchored blocks decode // unchanged either way. let line = line.strip_prefix('/').unwrap_or(line); let mut out = String::new(); let mut escaped = false; for c in line.chars() { if escaped { out.push(c); escaped = false; } else if c == '\\' { escaped = true; } else { out.push(c); } } out } fn managed_block_paths(gitignore: &str) -> Vec { let mut inside = false; let mut out = Vec::new(); for line in gitignore.lines() { let t = line.trim_end(); if t == GITIGNORE_BEGIN { inside = true; continue; } if t == GITIGNORE_END { break; } if inside && !t.is_empty() { out.push(unescape_gitignore_path(t)); } } out } fn scan_files(root: &Path, gitignore: &str, threshold: u64) -> Result { let tracked = tracked_paths(root)?; let others = git_nul(root, &["ls-files", "--others", "-z"])?; let unignored: HashSet = git_nul(root, &["ls-files", "--others", "--exclude-standard", "-z"])? .into_iter() .collect(); let managed: HashSet = managed_block_paths(gitignore).into_iter().collect(); let mut scan = Scan { git_files: Vec::new(), chunked_files: Vec::new(), refused: Vec::new(), skipped_ignored: Vec::new(), deleted: Vec::new(), }; let mut consider = |path: &str, is_tracked: bool| { if path.starts_with(".twigpine/") { return; // release metadata is never a manifest file } // A path that vanished between listing and stat is not publishable; // a tracked one records an unstaged deletion the commit must carry // so the released tree drops the file too. let meta = match std::fs::symlink_metadata(root.join(path)) { Ok(m) => m, Err(_) => { if is_tracked { scan.deleted.push(path.to_string()); } return; } }; if !meta.is_file() && !meta.file_type().is_symlink() { return; } let ignored = !is_tracked && !unignored.contains(path); match classify( meta.len(), is_tracked, ignored, managed.contains(path), threshold, ) { Class::Git => scan.git_files.push(path.to_string()), Class::Chunked => scan.chunked_files.push(path.to_string()), Class::LargeTracked => scan.refused.push(path.to_string()), Class::Ignored => { if meta.len() >= threshold { scan.skipped_ignored.push(path.to_string()); } } } }; for p in &tracked { consider(p, true); } for p in &others { if tracked.contains(p) { continue; } consider(p, false); } scan.git_files.sort(); scan.chunked_files.sort(); scan.refused.sort(); scan.skipped_ignored.sort(); scan.deleted.sort(); Ok(scan) } // ── .gitignore managed block ──────────────────────────────────────────────── /// Insert or replace the managed block so it lists exactly `paths`; an empty /// list removes the block. Idempotent: rewriting the same list yields the /// same file content. fn upsert_managed_block(existing: &str, paths: &[String]) -> String { let mut out: Vec = existing.lines().map(str::to_string).collect(); if let Some(b) = out.iter().position(|l| l.trim_end() == GITIGNORE_BEGIN) { let end = out[b + 1..] .iter() .position(|l| l.trim_end() == GITIGNORE_END) .map(|e| b + 1 + e) .unwrap_or(out.len() - 1); out.drain(b..=end); // The blank line we insert before the block goes with it. if b > 0 && out.get(b - 1).is_some_and(|l| l.is_empty()) { out.remove(b - 1); } } if !paths.is_empty() { if !out.is_empty() && !out.last().is_some_and(|l| l.is_empty()) { out.push(String::new()); } out.push(GITIGNORE_BEGIN.to_string()); out.extend(paths.iter().map(|p| escape_gitignore_path(p))); out.push(GITIGNORE_END.to_string()); } let mut s = out.join("\n"); if !s.is_empty() { s.push('\n'); } s } // ── resume state ──────────────────────────────────────────────────────────── #[derive(Debug, Default, Serialize, Deserialize, PartialEq)] struct PublishState { session_id: String, uploaded: Vec, } fn load_state(path: &Path) -> PublishState { let Ok(text) = std::fs::read_to_string(path) else { return PublishState::default(); }; serde_json::from_str(&text).unwrap_or_default() } /// Rewrite the state file after each uploaded block: the file carries the /// resume set, so it is written and fsync'd rather than left in page cache. fn save_state(path: &Path, state: &PublishState) -> Result<()> { let bytes = serde_json::to_vec(state)?; // The file holds the session bearer, so it goes through the owner-only // writer, then is fsync'd (the helper does not sync). crate::secret_file::write(path, &bytes).with_context(|| format!("write {}", path.display()))?; std::fs::OpenOptions::new() .write(true) .open(path)? .sync_all()?; Ok(()) } // ── misc ──────────────────────────────────────────────────────────────────── /// `/@<40-hex commit>` -> ((owner, name), commit). fn parse_parent(spec: &str) -> Result<((String, String), String)> { let (repo, commit) = spec .rsplit_once('@') .context("parent must be /@")?; let (owner, name) = repo .split_once('/') .context("parent must be /@")?; if owner.is_empty() || name.is_empty() || name.contains('/') { bail!("parent must be /@"); } if commit.len() != 40 || !commit.chars().all(|c| c.is_ascii_hexdigit()) { bail!("parent commit must be a 40-hex sha"); } Ok(((owner.to_string(), name.to_string()), commit.to_string())) } fn read_head(path: &Path, n: u64) -> Result> { let f = std::fs::File::open(path).with_context(|| format!("open {}", path.display()))?; let mut buf = Vec::new(); f.take(n).read_to_end(&mut buf)?; Ok(buf) } /// Point the real index's entries for the released paths back at HEAD. The /// release commit is built under a dedicated index, so without this the /// user's index still holds the old HEAD tree and every released path shows /// as a staged reversion the next plain commit would apply. Entries for /// paths not listed are untouched. fn sync_index_to_head(root: &Path, git_dir: &Path, paths: &[String]) -> Result<()> { if paths.is_empty() { return Ok(()); } let spec_path = git_dir.join("twigpine-model-reset-pathspec"); { let mut spec = Vec::new(); for p in paths { spec.extend_from_slice(p.as_bytes()); spec.push(0); } std::fs::write(&spec_path, spec)?; } let res = git( root, &[ "--literal-pathspecs", "reset", "-q", "HEAD", &format!("--pathspec-from-file={}", spec_path.display()), "--pathspec-file-nul", ], ); let _ = std::fs::remove_file(&spec_path); res.map(|_| ()) } /// Bytes of the blob staged for `path` in the dedicated release index: /// exactly what the release commit will store, filters and symlink handling /// included. fn staged_blob(root: &Path, index: &Path, path: &str) -> Result> { // Resolve the blob sha through the index rather than `:{path}` revspec // syntax: a path that opens with magic characters is parsed as revspec // there, not as a filename. Literal pathspecs keep a path that LOOKS // like magic from resolving to a different entry. let out = git_index( root, index, &["--literal-pathspecs", "ls-files", "-s", "-z", "--", path], )?; let stdout = String::from_utf8(out.stdout).context("ls-files output was not utf-8")?; // ` \t`: require the returned entry to name the // exact path asked for, so a resolution surprise fails loudly. let (meta, name) = stdout .trim_end_matches('\0') .split_once('\t') .with_context(|| format!("{path} is not staged in the index"))?; if name != path { bail!("{path} resolved to a different index path: {name}"); } let sha = meta .split(' ') .nth(1) .filter(|s| !s.is_empty()) .with_context(|| format!("{path} is not staged in the index"))?; Ok(git(root, &["cat-file", "blob", sha])?.stdout) } /// Fetch a prior release's reconstruction object for dedup. A 404 means the /// commit never became a published release (or its repo stopped serving); /// any other non-2xx surfaces the node's own body. async fn fetch_reconstruction( client: &NodeClient, owner: &str, name: &str, commit: &str, ) -> Result> { let path = format!("/api/v1/repos/{owner}/{name}/models/releases/{commit}/reconstruction"); let resp = client .get_signed(&path) .await .context("reconstruction fetch failed")?; let status = resp.status(); if status == reqwest::StatusCode::NOT_FOUND { return Ok(None); } if !status.is_success() { let capped = read_body_capped_bytes(resp, 8 * 1024).await; bail!( "reconstruction fetch for {commit} failed ({status}): {}", crate::http::sanitize_node_msg(&String::from_utf8_lossy(&capped.bytes)) ); } let capped = read_body_capped_bytes(resp, RECONSTRUCTION_FETCH_CAP).await; if capped.truncated || capped.read_failed { bail!("reconstruction object for {commit} was oversized or truncated"); } let rec = Reconstruction::parse(&capped.bytes) .map_err(|e| anyhow::anyhow!("reconstruction object for {commit} is invalid: {e}"))?; Ok(Some(rec)) } /// Send one content block to the session. Unsigned by protocol: the session /// id is the bearer credential. A non-2xx body is surfaced through /// `read_json`'s denial path. async fn upload_block( client: &NodeClient, base: &str, session_id: &str, sha: &str, data: Vec, ) -> Result<()> { let resp = client .put_unsigned( &format!("{base}/models/blocks/{sha}"), data, &[(SESSION_HEADER, session_id)], ) .await?; let _: Value = read_json(resp, "block upload").await?; Ok(()) } /// The failure `cmd_publish` returns when the release is still `verifying` /// at the poll budget: a non-zero exit that keeps the status URL visible. fn still_verifying_error(release_id: i64, budget_secs: u64, release_path: &str) -> anyhow::Error { anyhow::anyhow!( "release {release_id} is still verifying after {budget_secs}s; its status is at\n \ GET {release_path}" ) } /// Without `--yes`, publishing requires an explicit "yes" on stdin. Any /// other answer, including EOF on a pipe, declines. fn confirm_publish() -> Result { eprint!("type 'yes' to publish: "); let _ = std::io::stderr().flush(); let mut line = String::new(); std::io::stdin().read_line(&mut line)?; Ok(line.trim().eq_ignore_ascii_case("yes")) } // ── publish ───────────────────────────────────────────────────────────────── async fn cmd_publish(args: PublishArgs) -> Result<()> { let kp = load_keypair_from_dir(args.dir.as_deref())?; let root = repo_root()?; let git_dir = git_dir(&root)?; let (remote_name, owner, name) = detect_remote(&root)?; let branch = match &args.branch { Some(b) => b.clone(), None => { // allow-unbounded-git: short-lived CLI process; there is no // request permit to hold or client disconnect to outlive. let out = std::process::Command::new("git") .args(["symbolic-ref", "--short", "-q", "HEAD"]) .current_dir(&root) .output() .context("failed to run git")?; if !out.status.success() { bail!("detached HEAD: pass --branch to name the release branch"); } String::from_utf8(out.stdout) .context("branch name was not utf-8")? .trim() .to_string() } }; // 1. Scan and refuse tracked large files before anything else happens. let gitignore_path = root.join(".gitignore"); let existing_gitignore = std::fs::read_to_string(&gitignore_path).unwrap_or_default(); let scan = scan_files(&root, &existing_gitignore, args.chunk_threshold_bytes)?; if !scan.refused.is_empty() { bail!( "these files are {} bytes or larger but tracked in git; weights must live \ outside git. Remove them from the index first (git rm --cached):\n {}", args.chunk_threshold_bytes, scan.refused.join("\n ") ); } for p in &scan.skipped_ignored { eprintln!( "warning: {p} is at or over the chunk threshold but gitignored; \ unignore it to publish" ); } // 2. Warn + confirm: publishing is permanent. println!("Publishing {owner}/{name} as a model release on branch {branch}:"); println!( " {} git files, {} chunked files", scan.git_files.len(), scan.chunked_files.len() ); for p in &scan.chunked_files { let size = std::fs::symlink_metadata(root.join(p)) .map(|m| m.len()) .unwrap_or(0); if size > SINGLE_FILE_WARN_BYTES { eprintln!( "warning: {p} is over 50 GiB; huggingface_hub refuses plain downloads that large" ); } } eprintln!( "publishing stores the blocks in this node's configured block store and commits a \ signed release manifest to git: the bytes stay available only while this node \ keeps them and the repo stays readable, and nothing is pinned to IPFS or \ anchored to Arweave" ); if !args.yes && !confirm_publish()? { println!("aborted"); return Ok(()); } let client = NodeClient::new(&args.node, Some(kp.clone())); let base = format!("/api/v1/repos/{owner}/{name}"); // 3. Dedup: reconstructions of prior releases in this clone, plus the // declared parent's when given. let mut priors: Vec = Vec::new(); let mut parent_ref: Option = None; let prior_commits = release_commits(&root); for commit in &prior_commits { if let Some(rec) = fetch_reconstruction(&client, &owner, &name, commit).await? { priors.push(rec); } } if let Some(spec) = &args.parent { let ((powner, pname), pcommit) = parse_parent(spec)?; let rec = fetch_reconstruction(&client, &powner, &pname, &pcommit) .await? .context("declared parent has no published reconstruction on this node")?; // There is no manifest-serving route, so the parent manifest sha256 // is the sha of the manifest bytes in the local clone when the parent // commit is here, and the sha of the parent's reconstruction object // (the only parent artifact the node serves) otherwise. The node // records the field without checking it (R9: a signed claim, not a // verified link). let manifest_sha = git( &root, &["show", &format!("{pcommit}:.twigpine/model-release.json")], ) .map(|out| sha256_hex(&out.stdout)) .unwrap_or_else(|_| sha256_hex(&rec.to_bytes().unwrap_or_default())); parent_ref = Some(ParentRef { repo: format!("{powner}/{pname}"), commit: pcommit, manifest_sha256: manifest_sha, }); priors.push(rec); } let prior_refs: Vec<&Reconstruction> = priors.iter().collect(); let mut dedup = DedupIndex::from_reconstructions(&prior_refs); let mut all_entries: HashMap = HashMap::new(); for rec in &priors { for b in &rec.blocks { all_entries.insert(b.sha256.clone(), b.clone()); } } // 4. Open (or resume) the upload session before packing, so each new // block streams out as it seals instead of buffering the whole // model in memory. let state_path = git_dir.join(STATE_FILE_NAME); let mut state = load_state(&state_path); if !state.session_id.is_empty() { let resp = client .get_signed(&format!("{base}/models/sessions/{}", state.session_id)) .await .context("session status request failed")?; if resp.status() == reqwest::StatusCode::NOT_FOUND { state = PublishState::default(); } else { let v: Value = read_json(resp, "session status").await?; if v["state"].as_str() != Some("open") { state = PublishState::default(); } } } if state.session_id.is_empty() { let body = serde_json::to_vec(&json!({}))?; let resp = client .post(&format!("{base}/models/sessions"), &body) .await?; let v: Value = json_or_denial("open model session", resp).await?; state.session_id = v["session_id"] .as_str() .context("session response had no session_id")? .to_string(); state.uploaded.clear(); save_state(&state_path, &state)?; } let mut uploaded: HashSet = state.uploaded.iter().cloned().collect(); let session_id = state.session_id.clone(); // 5. Pack every chunked file; shared chunks become terms into prior // blocks, the rest seal into new blocks uploaded as they seal. let mut rec = Reconstruction::new(); let mut files: Vec = Vec::new(); for path in &scan.chunked_files { // Pack on a blocking thread and upload each block as it seals: a // bounded channel keeps resident memory to a couple of blocks // rather than the whole file. The dedup index moves to the thread // through an Arc and comes back when it finishes. let shared_dedup = std::sync::Arc::new(std::mem::take(&mut dedup)); let task_dedup = shared_dedup.clone(); let (block_tx, mut block_rx) = tokio::sync::mpsc::channel::(2); let pack_path = path.clone(); let pack_root = root.clone(); let pack_task = tokio::task::spawn_blocking(move || { let file = std::fs::File::open(pack_root.join(&pack_path)) .map_err(|e| std::io::Error::new(e.kind(), format!("open {pack_path}: {e}")))?; pack_file_with(&pack_path, file, &task_dedup, move |block| { block_tx .blocking_send(block) .map_err(|_| std::io::Error::other("block upload channel closed")) }) }); while let Some(block) = block_rx.recv().await { let sha = block.sha256; if uploaded.contains(&sha) { continue; } upload_block(&client, &base, &session_id, &sha, block.data).await?; state.uploaded.push(sha.clone()); uploaded.insert(sha.clone()); save_state(&state_path, &state)?; println!("uploaded block {}", &sha[..16]); } let (file_entry, block_entries) = pack_task .await .context("pack task failed")? .with_context(|| format!("pack {path}"))?; dedup = std::sync::Arc::try_unwrap(shared_dedup).unwrap_or_else(|a| (*a).clone()); // Make this file's fresh chunks visible to the next file's dedup. dedup.add_block_entries(&block_entries); let head = read_head(&root.join(path), 64)?; files.push(ManifestFile { path: path.clone(), size: file_entry.size, sha256: file_entry.sha256.clone(), format: detect_format(&head, path), storage: StorageKind::Chunked, }); rec.files.push(file_entry); for e in block_entries { all_entries.insert(e.sha256.clone(), e.clone()); rec.blocks.push(e); } } // Terms into earlier blocks need those entries in this object: a reader // resolves term.block against rec.blocks only. // Sorted so the appended block rows (and therefore the serialized // reconstruction object and its sha) are identical across processes on // a retried publish. let mut needed: Vec = rec .files .iter() .flat_map(|f| f.terms.iter().map(|t| t.block.clone())) .collect::>() .into_iter() .collect(); needed.sort(); let mut present: HashSet = rec.blocks.iter().map(|b| b.sha256.clone()).collect(); for sha in needed { if present.contains(&sha) { continue; } let entry = all_entries .get(&sha) .with_context(|| format!("term references unknown block {sha}"))?; present.insert(entry.sha256.clone()); rec.blocks.push(entry.clone()); } // A release with no chunked files has no chunked bytes to reconstruct: // no reconstruction object, no reconstruction block. let rec_bytes = if scan.chunked_files.is_empty() { Vec::new() } else { rec.validate() .map_err(|e| anyhow::anyhow!("reconstruction object invalid: {e}"))?; rec.to_bytes() .map_err(|e| anyhow::anyhow!("reconstruction serialize failed: {e}"))? }; let rec_sha = sha256_hex(&rec_bytes); // 6. The reconstruction object goes up as one more content block. let has_rec = !rec_bytes.is_empty(); let rec_size = rec_bytes.len() as u64; if has_rec && !uploaded.contains(&rec_sha) { upload_block(&client, &base, &session_id, &rec_sha, rec_bytes).await?; state.uploaded.push(rec_sha.clone()); save_state(&state_path, &state)?; println!("uploaded reconstruction object"); } // 7. Managed .gitignore block. A symlink target outside the checkout is // never written through, and edits made while blocks uploaded are // caught against the scan snapshot rather than silently lost. if let Ok(meta) = std::fs::symlink_metadata(&gitignore_path) { if meta.file_type().is_symlink() { bail!(".gitignore is a symlink; refusing to write through it"); } } let new_gitignore = upsert_managed_block(&existing_gitignore, &scan.chunked_files); if new_gitignore != existing_gitignore { let current = std::fs::read_to_string(&gitignore_path).unwrap_or_default(); if current != existing_gitignore { bail!( ".gitignore changed while blocks uploaded; re-run to publish \ from a fresh scan" ); } std::fs::write(&gitignore_path, &new_gitignore)?; } // 8. Stage into a dedicated index seeded from HEAD: the release commit // holds exactly the scanned set, the user's real index and anything // already staged in it are never read or rewritten, and the hashed // blobs below are the same index state the commit records. Only // paths that exist go in the first stage; the release metadata // follows after it is written below. let index_path = git_dir.join("twigpine-model-index"); let _ = std::fs::remove_file(&index_path); if git(&root, &["rev-parse", "--verify", "-q", "HEAD"]).is_ok() { git_index(&root, &index_path, &["read-tree", "HEAD"])?; } else { git_index(&root, &index_path, &["read-tree", "--empty"])?; } let pathspec_path = git_dir.join("twigpine-model-pathspec"); { let mut spec = Vec::new(); for p in scan.git_files.iter().chain(&scan.deleted) { spec.extend_from_slice(p.as_bytes()); spec.push(0); } if gitignore_path.is_file() { spec.extend_from_slice(b".gitignore"); spec.push(0); } if spec.is_empty() { let _ = std::fs::remove_file(&pathspec_path); } else { std::fs::write(&pathspec_path, spec)?; } } if pathspec_path.exists() { let staged = git_index( &root, &index_path, &[ "--literal-pathspecs", "add", "-A", "--pathspec-file-nul", &format!("--pathspec-from-file={}", pathspec_path.display()), ], ); let _ = std::fs::remove_file(&pathspec_path); staged?; } // 9. Hash the git-stored files from the release index (the exact bytes // the commit stores), then write and stage the manifest. for path in &scan.git_files { let bytes = staged_blob(&root, &index_path, path)?; files.push(ManifestFile { path: path.clone(), size: bytes.len() as u64, sha256: sha256_hex(&bytes), format: detect_format(&bytes[..bytes.len().min(64)], path), storage: StorageKind::Git, }); } files.sort_by(|a, b| a.path.cmp(&b.path)); let manifest = Manifest { schema: MANIFEST_SCHEMA_V1.to_string(), repo: format!("{owner}/{name}"), publisher_did: kp.did().to_string(), license: args.license.clone(), parent: parent_ref, files, reconstruction: if !has_rec { None } else { Some(ReconstructionRef { sha256: rec_sha, size: rec_size, }) }, }; let manifest_bytes = manifest .to_bytes() .map_err(|e| anyhow::anyhow!("manifest serialize failed: {e}"))?; let twigpine_dir = root.join(".twigpine"); std::fs::create_dir_all(&twigpine_dir)?; std::fs::write(twigpine_dir.join("model-release.json"), &manifest_bytes)?; std::fs::write( twigpine_dir.join("model-release.sig"), format!( "{}\n", manifest::sign( &ed25519_dalek::SigningKey::from_bytes(&kp.to_seed()), &manifest_bytes, ) ), )?; git_index( &root, &index_path, &[ "--literal-pathspecs", "add", ".twigpine/model-release.json", ".twigpine/model-release.sig", ], )?; // 10. Commit when the release index differs, push, and claim HEAD. let has_changes = git_index(&root, &index_path, &["diff", "--cached", "--quiet"]).is_err(); if has_changes { let n = prior_commits.len() + 1; git_index( &root, &index_path, &["commit", "-m", &format!("model release {n}")], )?; } else { // Nothing staged: a re-publish of identical content lands here, and // HEAD must already be a release commit to claim. if git( &root, &["cat-file", "-e", "HEAD:.twigpine/model-release.json"], ) .is_err() { bail!("nothing to publish and HEAD carries no release manifest"); } println!("no changes to commit; claiming the existing release commit"); } let _ = std::fs::remove_file(&index_path); // The dedicated index left the real index holding the old HEAD tree: // every released path would look staged for reversion, and the next // plain `git commit` would undo the release. Sync exactly the released // paths back to HEAD; unrelated staged entries keep their state. let mut released: Vec = scan.git_files.clone(); released.extend(scan.deleted.iter().cloned()); if gitignore_path.is_file() || git(&root, &["cat-file", "-e", "HEAD:.gitignore"]).is_ok() { released.push(".gitignore".to_string()); } released.push(".twigpine/model-release.json".to_string()); released.push(".twigpine/model-release.sig".to_string()); sync_index_to_head(&root, &git_dir, &released)?; let commit = git_lines(&root, &["rev-parse", "HEAD"])? .into_iter() .next() .context("no HEAD commit")?; // allow-unbounded-git: short-lived CLI process; there is no request // permit to hold or client disconnect to outlive. let push = std::process::Command::new("git") .args(["push", &remote_name, &format!("HEAD:{branch}")]) .current_dir(&root) .env("TWIGPINE_NODE", &args.node) // The helper on PATH may be a build from before the rename. .env("GITLAWB_NODE", &args.node) .output() .context("failed to run git push")?; if !push.status.success() { bail!( "git push failed:\n{}", String::from_utf8_lossy(&push.stderr).trim() ); } println!("pushed {commit} to {remote_name}/{branch}"); let claim_body = serde_json::to_vec(&json!({ "commit": commit, "branch": branch, }))?; let resp = client .post(&format!("{base}/models/claims"), &claim_body) .await?; let claim: Value = json_or_denial("claim release", resp).await?; let release_id = claim["release_id"].as_i64().unwrap_or_default(); println!("release {release_id} claimed; verifying"); // 10. Poll until the verification worker settles the release. let release_path = format!("{base}/models/releases/{commit}"); let deadline = Instant::now() + POLL_BUDGET; loop { // One transport hiccup should not abort the publish; the signed // status read is idempotent, so retry it a few times. let resp = 'poll: { let mut last = None; for _ in 0..3 { match client.get_signed(&release_path).await { Ok(r) => break 'poll r, Err(e) => { last = Some(e); tokio::time::sleep(Duration::from_secs(2)).await; } } } return Err(last .expect("three attempts ran") .context("release status request failed")); }; let v: Value = read_json(resp, "release status").await?; match v["state"].as_str() { Some("published") => { println!("published release {release_id}"); println!(" commit: {}", v["commit"].as_str().unwrap_or(&commit)); println!( " manifest: {}", v["manifest_sha256"].as_str().unwrap_or("?") ); let _ = std::fs::remove_file(&state_path); return Ok(()); } Some("rejected") => { bail!( "release {release_id} rejected: {}", v["failure_reason"].as_str().unwrap_or("unknown reason") ); } _ => { if Instant::now() >= deadline { return Err(still_verifying_error( release_id, POLL_BUDGET.as_secs(), &release_path, )); } tokio::time::sleep(POLL_INTERVAL).await; } } } } #[cfg(test)] mod tests { use super::*; const THR: u64 = 1024; #[test] fn classify_by_threshold_tracking_and_ignore() { // Below threshold: tracked or unignored-untracked are git files. assert_eq!(classify(THR - 1, true, false, false, THR), Class::Git); assert_eq!(classify(THR - 1, false, false, false, THR), Class::Git); assert_eq!(classify(THR - 1, false, true, false, THR), Class::Ignored); assert_eq!(classify(THR - 1, false, true, true, THR), Class::Ignored); // At/above threshold: tracked refuses; untracked chunks unless // ignored outside the managed block. assert_eq!(classify(THR, true, false, false, THR), Class::LargeTracked); assert_eq!( classify(THR + 1, true, true, false, THR), Class::LargeTracked ); assert_eq!(classify(THR, false, false, false, THR), Class::Chunked); assert_eq!(classify(THR, false, true, true, THR), Class::Chunked); assert_eq!(classify(THR, false, true, false, THR), Class::Ignored); } #[test] fn managed_block_upsert_insert_replace_idempotent_remove() { let base = "*.tmp\n".to_string(); let paths = vec!["weights/a.bin".to_string(), "b.bin".to_string()]; let once = upsert_managed_block(&base, &paths); assert!(once.contains("*.tmp\n")); assert!(once.contains(GITIGNORE_BEGIN)); assert!(once.contains("/weights/a.bin\n/b.bin\n")); assert!(once.contains(GITIGNORE_END)); assert_eq!(once, upsert_managed_block(&once, &paths), "idempotent"); let replaced = upsert_managed_block(&once, &["c.bin".to_string()]); assert!(replaced.contains("c.bin")); assert!(!replaced.contains("a.bin")); let removed = upsert_managed_block(&replaced, &[]); assert!(!removed.contains(GITIGNORE_BEGIN)); assert_eq!(removed, "*.tmp\n"); let empty = upsert_managed_block("", &paths); assert_eq!(managed_block_paths(&empty), paths); } #[test] fn a_verifying_release_past_the_budget_is_an_error() { // The poll loop needs a live node, so the budget decision is kept // in this pure helper: the arm it feeds must exit non-zero with the // release id, the budget, and the status path. let e = still_verifying_error(7, 300, "/api/v1/repos/o/r/models/releases/cc"); let msg = e.to_string(); assert!(msg.contains("7"), "{msg}"); assert!(msg.contains("300"), "{msg}"); assert!( msg.contains("/api/v1/repos/o/r/models/releases/cc"), "{msg}" ); } #[test] fn managed_block_paths_reads_only_the_block() { let text = format!("a\n{GITIGNORE_BEGIN}\nx.bin\ny.bin\n{GITIGNORE_END}\nz\n"); assert_eq!(managed_block_paths(&text), vec!["x.bin", "y.bin"]); assert!(managed_block_paths("nothing here\n").is_empty()); } #[cfg(unix)] #[test] fn save_state_is_owner_only_even_over_a_loose_file() { use std::os::unix::fs::PermissionsExt; let dir = tempfile::tempdir().unwrap(); let path = dir.path().join(STATE_FILE_NAME); let state = PublishState { session_id: "bearer".to_string(), uploaded: vec![], }; save_state(&path, &state).unwrap(); let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777; assert_eq!(mode(&path), 0o600); // A resume file left loose by an earlier run is tightened on rewrite. std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); save_state(&path, &state).unwrap(); assert_eq!(mode(&path), 0o600); assert_eq!(load_state(&path), state); } #[test] fn publish_state_round_trips() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join(STATE_FILE_NAME); let state = PublishState { session_id: "abc".to_string(), uploaded: vec!["aa".into(), "bb".into()], }; save_state(&path, &state).unwrap(); assert_eq!(load_state(&path), state); assert_eq!( load_state(&dir.path().join("missing.json")), PublishState::default() ); std::fs::write(&path, "not json").unwrap(); assert_eq!(load_state(&path), PublishState::default()); } #[test] fn parse_parent_shapes() { let commit = "a".repeat(40); let ((owner, name), c) = parse_parent(&format!("alice/weights@{commit}")).unwrap(); assert_eq!( (owner.as_str(), name.as_str(), c.as_str()), ("alice", "weights", commit.as_str()) ); // A did:key owner carries colons; the split is on the LAST '@'. let did_owner = "did:key:z6MkAbc"; let ((owner, name), _) = parse_parent(&format!("{did_owner}/weights@{commit}")).unwrap(); assert_eq!((owner.as_str(), name.as_str()), (did_owner, "weights")); for bad in [ "noslash", "a/b@", "a/b@cafe", &format!("a/b/c@{commit}"), &format!("a/b@{commit}x"), &format!("a/b@{}", "g".repeat(40)), ] { assert!(parse_parent(bad).is_err(), "{bad}"); } } #[test] fn manifest_assembly_round_trips_storage_kinds() { // The manifest the command writes: schema v1, repo as owner/name, // git and chunked entries sorted by path, reconstruction ref present. let kp = twigpine_core::identity::Keypair::from_seed(&[3u8; 32]).unwrap(); let mut files = vec![ ManifestFile { path: "weights.bin".to_string(), size: 11, sha256: "b".repeat(64), format: twigpine_core::model::manifest::FileFormat::Other, storage: StorageKind::Chunked, }, ManifestFile { path: "README.md".to_string(), size: 5, sha256: "a".repeat(64), format: twigpine_core::model::manifest::FileFormat::Text, storage: StorageKind::Git, }, ]; files.sort_by(|a, b| a.path.cmp(&b.path)); let m = Manifest { schema: MANIFEST_SCHEMA_V1.to_string(), repo: "did:key:z6MkA/w".to_string(), publisher_did: kp.did().to_string(), license: "apache-2.0".to_string(), parent: None, files, reconstruction: Some(ReconstructionRef { sha256: "c".repeat(64), size: 42, }), }; let bytes = m.to_bytes().unwrap(); let v: Value = serde_json::from_slice(&bytes).unwrap(); assert_eq!(v["schema"].as_str(), Some(MANIFEST_SCHEMA_V1)); assert_eq!(v["repo"].as_str(), Some("did:key:z6MkA/w")); assert_eq!(v["license"].as_str(), Some("apache-2.0")); let paths: Vec<&str> = v["files"] .as_array() .unwrap() .iter() .filter_map(|f| f["path"].as_str()) .collect(); assert_eq!(paths, ["README.md", "weights.bin"]); let storages: Vec<&str> = v["files"] .as_array() .unwrap() .iter() .filter_map(|f| f["storage"].as_str()) .collect(); assert_eq!(storages, ["git", "chunked"]); let rec_sha = "c".repeat(64); assert_eq!( v["reconstruction"]["sha256"].as_str(), Some(rec_sha.as_str()) ); } #[test] fn remote_url_parses_both_schemes() { assert_eq!( parse_remote_url("twigpine://did:key:z6MkA/repo.git"), Some(("did:key:z6MkA".to_string(), "repo".to_string())) ); assert_eq!( parse_remote_url("gitlawb://did:key:z6MkA/repo"), Some(("did:key:z6MkA".to_string(), "repo".to_string())) ); assert_eq!(parse_remote_url("https://x/y"), None); } fn tgit(dir: &Path, args: &[&str]) -> String { let out = std::process::Command::new("git") .args(args) .current_dir(dir) .output() .expect("git runs"); assert!( out.status.success(), "git {args:?} failed: {}", String::from_utf8_lossy(&out.stderr) ); String::from_utf8_lossy(&out.stdout).trim().to_string() } fn trepo() -> tempfile::TempDir { let dir = tempfile::tempdir().unwrap(); tgit(dir.path(), &["init", "-q", "-b", "main"]); dir } #[test] fn a_push_url_naming_a_different_repo_is_rejected() { let dir = trepo(); tgit( dir.path(), &["remote", "add", "origin", "twigpine://did:key:z6MkA/aaa"], ); tgit( dir.path(), &[ "remote", "set-url", "--push", "origin", "twigpine://did:key:z6MkB/bbb", ], ); let e = detect_remote(dir.path()).unwrap_err(); assert!(e.to_string().contains("pushes to"), "{e}"); } #[test] fn a_matching_push_url_is_accepted() { let dir = trepo(); tgit( dir.path(), &["remote", "add", "origin", "twigpine://did:key:z6MkA/aaa"], ); tgit( dir.path(), &[ "remote", "set-url", "--push", "origin", "twigpine://did:key:z6MkA/aaa", ], ); assert_eq!( detect_remote(dir.path()).unwrap(), ( "origin".to_string(), "did:key:z6MkA".to_string(), "aaa".to_string() ) ); } #[test] fn managed_patterns_anchor_at_root_and_escape_wildcards() { assert_eq!(escape_gitignore_path("a*b?.bin"), "/a\\*b\\?.bin"); assert_eq!(escape_gitignore_path("weights.bin"), "/weights.bin"); let text = format!("{GITIGNORE_BEGIN}\n/weights.bin\n/experiments/weights.bin\n{GITIGNORE_END}\n"); assert_eq!( managed_block_paths(&text), vec!["weights.bin", "experiments/weights.bin"] ); } #[test] fn a_literal_pathspec_filename_resolves_its_own_blob() { let dir = trepo(); std::fs::write(dir.path().join(":(glob)weights*.txt"), b"magic").unwrap(); std::fs::write(dir.path().join("weights-a.txt"), b"plain").unwrap(); tgit( dir.path(), &[ "--literal-pathspecs", "add", "--", ":(glob)weights*.txt", "weights-a.txt", ], ); let index = dir.path().join(".git/index"); assert_eq!( staged_blob(dir.path(), &index, ":(glob)weights*.txt").unwrap(), b"magic" ); assert_eq!( staged_blob(dir.path(), &index, "weights-a.txt").unwrap(), b"plain" ); } fn tcommit(dir: &Path, index: &Path, msg: &str) { git_index( dir, index, &[ "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", msg, ], ) .unwrap(); } /// After the release commit and the index sync, status must show only /// what the user staged: no released path may linger as a staged /// reversion the next plain commit would apply. fn assert_only_unrelated_staged(dir: &Path) { let status = tgit(dir, &["status", "--porcelain"]); assert_eq!(status, "A unrelated.bin", "status"); let staged = tgit(dir, &["diff", "--cached", "--name-status"]); assert_eq!(staged, "A\tunrelated.bin", "diff --cached"); } #[test] fn the_release_index_leaves_user_staging_alone() { let dir = trepo(); std::fs::write(dir.path().join("a.txt"), b"a").unwrap(); tgit(dir.path(), &["add", "a.txt"]); tgit( dir.path(), &[ "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "init", ], ); // An unrelated file staged in the real index must not ride into the // release commit, and must still be staged afterwards. std::fs::write(dir.path().join("unrelated.bin"), b"u").unwrap(); tgit(dir.path(), &["add", "unrelated.bin"]); let index = dir.path().join(".git").join("tmp-index"); git_index(dir.path(), &index, &["read-tree", "HEAD"]).unwrap(); std::fs::write(dir.path().join("b.txt"), b"b").unwrap(); git_index(dir.path(), &index, &["add", "b.txt"]).unwrap(); tcommit(dir.path(), &index, "rel"); let tree = tgit(dir.path(), &["ls-tree", "--name-only", "HEAD"]); assert!(!tree.contains("unrelated.bin"), "{tree}"); assert!(tree.contains("b.txt"), "{tree}"); sync_index_to_head(dir.path(), &dir.path().join(".git"), &["b.txt".to_string()]).unwrap(); assert_only_unrelated_staged(dir.path()); } #[test] fn the_index_sync_handles_a_deleted_tracked_path() { let dir = trepo(); std::fs::write(dir.path().join("gone.txt"), b"x").unwrap(); std::fs::write(dir.path().join("kept.txt"), b"y").unwrap(); tgit(dir.path(), &["add", "gone.txt", "kept.txt"]); tgit( dir.path(), &[ "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "init", ], ); std::fs::write(dir.path().join("unrelated.bin"), b"u").unwrap(); tgit(dir.path(), &["add", "unrelated.bin"]); std::fs::remove_file(dir.path().join("gone.txt")).unwrap(); let index = dir.path().join(".git").join("tmp-index"); git_index(dir.path(), &index, &["read-tree", "HEAD"]).unwrap(); git_index(dir.path(), &index, &["add", "-A", "gone.txt"]).unwrap(); tcommit(dir.path(), &index, "rel"); let tree = tgit(dir.path(), &["ls-tree", "--name-only", "HEAD"]); assert!(!tree.contains("gone.txt"), "{tree}"); sync_index_to_head( dir.path(), &dir.path().join(".git"), &["gone.txt".to_string()], ) .unwrap(); assert_only_unrelated_staged(dir.path()); } #[test] fn the_index_sync_works_on_a_repos_first_commit() { let dir = trepo(); std::fs::write(dir.path().join("unrelated.bin"), b"u").unwrap(); tgit(dir.path(), &["add", "unrelated.bin"]); let index = dir.path().join(".git").join("tmp-index"); git_index(dir.path(), &index, &["read-tree", "--empty"]).unwrap(); std::fs::write(dir.path().join("rel.txt"), b"r").unwrap(); git_index(dir.path(), &index, &["add", "rel.txt"]).unwrap(); tcommit(dir.path(), &index, "first release"); sync_index_to_head( dir.path(), &dir.path().join(".git"), &["rel.txt".to_string()], ) .unwrap(); assert_only_unrelated_staged(dir.path()); } #[test] fn an_unstaged_tracked_deletion_is_recorded_for_staging() { let dir = trepo(); std::fs::write(dir.path().join("gone.txt"), b"x").unwrap(); std::fs::write(dir.path().join("kept.txt"), b"y").unwrap(); tgit(dir.path(), &["add", "gone.txt", "kept.txt"]); tgit( dir.path(), &[ "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "init", ], ); std::fs::remove_file(dir.path().join("gone.txt")).unwrap(); let scan = scan_files(dir.path(), "", 1024).unwrap(); assert_eq!(scan.deleted, vec!["gone.txt"]); assert!(scan.git_files.contains(&"kept.txt".to_string())); assert!(!scan.git_files.contains(&"gone.txt".to_string())); } }