694ae2cf655a

replace per-save file rows with shared per-folder manifests (schema 2), and resolve K3, K19, K26, K27, K30 and K33

time
2026-11-17 00:32 UTC · 1 week ago
machine
Junes-MacBook-Pro.local
agent
deepseek/deepseek-flash
session
review findings
parent
096ef744e76f
28 files shell/koh3.plugin.zsh+1 −1src/apply/apply.v+41 −19src/build/build.v+4 −1src/cli/cmd_doctor.v+11 −5src/cli/cmd_peek.v+4 −1src/cli/cmd_steal.v+6 −5src/cli/doctor_checks.v+9 −4src/exchange/exchange.v+16 −4src/exchange/exchange_test.v+40 −2src/exchange/steal.v+26 −12src/exchange/strip.v+272 −44src/exchange/strip_test.v+69 −0src/history/history.v+18 −11src/history/save.v+72 −29src/release/release_test.v+0 −1src/remote/s3.v+3 −2src/snapshot/diff.v+4 −1src/storage/doctor.v+26 −11src/storage/manifest.v+278 −0src/storage/manifest_test.v+221 −0src/storage/objects.v+63 −16src/storage/storage.v+137 −19src/update/update.v+9 −0src/view/term.v+21 −0src/view/view.v+32 −12tests/cli_test.v+19 −9vendor/shim/koh_term.c+80 −2vendor/shim/koh_term.h+8 −1
shell/koh3.plugin.zsh+1 −1
@@ -167,7 +167,7 @@167167     steal)           _arguments '--yes' '--list' '--mine' '--theirs' '--json' ;;168168     ignore)          _arguments '--global[edit ~/.kohignore for every repo]' '--yes[skip the question]' '--json' '*:path:_files' ;;169169     strip)           _arguments '--yes[skip the yes/no question; paths still typed]' '--save[one save]:save:_koh3_ids' '*:path:_files' ;;170-    doctor)          _arguments '--fast[skip the slow remote audit]' '--json[print the report as JSON]' '--yes[remove old peek folders]' '--backup[copy .koh to]:path:_files' ;;170+    doctor)          _arguments '--fast[skip the remote audit and the object hash sweep]' '--json[print the report as JSON]' '--yes[remove old peek folders]' '--backup[copy .koh to]:path:_files' ;;171171     build)           _arguments '*--platform[target platform]:platform:(macos-aarch64 macos-x86_64 linux-aarch64 linux-x86_64)' '--all' ;;172172     update)          _arguments '--check' '--yes' '--json' ;;173173     migrate)         _arguments '--lane[Koh 2 lane]:lane:(dev main)' '*--with[a lost version, from a backup]:file:_files' '--yes[skip the question]' '--json' ;;

view file

src/apply/apply.v+41 −19
@@ -45,9 +45,9 @@4545 	paths.sort()4646 4747 	mut plan := Plan{48-		files:   current.clone()4948 		applied: []string{}5049 	}50+	mut edits := []Edit{cap: paths.len}5151 	for path in paths {5252 		from := base_map[path] or {5353 			snapshot.FileEntry{@@ -68,8 +68,12 @@6868 			}6969 		}7070 		if same_entry(here, from) {71-			plan.files = set_entry(plan.files, path, to, path in target_map)7271 			plan.applied << path72+			edits << Edit{73+				path:  path74+				entry: to75+				keep:  path in target_map76+			}7377 			continue7478 		}7579 		if same_entry(here, to) {@@ -77,8 +81,10 @@7781 			continue7882 		}7983 		plan.conflict = path84+		plan.files = with_edits(current, edits)8085 		return plan8186 	}87+	plan.files = with_edits(current, edits)8288 	return plan8389 }8490 @@ -113,29 +119,45 @@113119 	return a.hash == b.hash && a.executable == b.executable114120 }115121 116-// set_entry replaces one path in a sorted tree, adding or removing it, and117-// keeps the list ordered by path.118-fn set_entry(files []snapshot.FileEntry, path string, entry snapshot.FileEntry, keep bool) []snapshot.FileEntry {119-	mut out := []snapshot.FileEntry{}120-	mut placed := false121-	for file in files {122-		if file.path == path {123-			if keep {124-				out << entry122+// Edit is one decided path: the entry to place, and whether it stays at all.123+struct Edit {124+	path  string125+	entry snapshot.FileEntry126+	keep  bool127+}128+129+// with_edits applies the decided paths to the tree in one pass, adding,130+// replacing or removing each, and returns the list ordered by path. The input131+// is sorted here because callers have handed it unsorted trees before (a132+// pluck fixture, a hand-built list), and the old one-at-a-time insert did not133+// care.134+fn with_edits(files []snapshot.FileEntry, edits []Edit) []snapshot.FileEntry {135+	mut sorted := files.clone()136+	sorted.sort(a.path < b.path)137+	mut out := []snapshot.FileEntry{cap: sorted.len + edits.len}138+	mut at := 0139+	for file in sorted {140+		// Edits only ever hold paths the decision reached, in path order.141+		for at < edits.len && edits[at].path < file.path {142+			if edits[at].keep {143+				out << edits[at].entry125144 			}126-			placed = true127-			continue145+			at++128146 		}129-		if !placed && file.path > path {130-			if keep {131-				out << entry147+		if at < edits.len && edits[at].path == file.path {148+			if edits[at].keep {149+				out << edits[at].entry132150 			}133-			placed = true151+			at++152+			continue134153 		}135154 		out << file136155 	}137-	if !placed && keep {138-		out << entry156+	for at < edits.len {157+		if edits[at].keep {158+			out << edits[at].entry159+		}160+		at++139161 	}140162 	return out141163 }

view file

src/build/build.v+4 −1
@@ -343,7 +343,10 @@343343 // and hang waiting for a reader that is waiting for it to finish.344344 fn run_build(root string, command string, env map[string]string) !Run {345345 	logs := os.join_path(os.temp_dir(), 'koh-build-${os.getpid()}-${time.now().unix_nano()}')346-	os.mkdir_all(logs, os.MkdirParams{})!346+	os.mkdir_all(logs, os.MkdirParams{ mode: 0o700 })!347+	// Build output can carry paths and secrets; keep the logs off other users'348+	// screens on a shared machine.349+	os.chmod(logs, 0o700)!347350 	defer {348351 		os.rmdir_all(logs) or {}349352 	}

view file

src/cli/cmd_doctor.v+11 −5
@@ -112,9 +112,15 @@112112 		return report113113 	}114114 	report.check('SQLite integrity', store.integrity_check() or { [err.msg()] })115-	report.object_check('object hashes and sizes', store.check_objects() or {116-		[storage.ObjectProblem{'', err.msg()}]117-	})115+	if fast {116+		// Reading and hashing every object is the slow half of Doctor; --fast leaves117+		// it to a full run and says so, as the remote audit does.118+		report.checks << DoctorCheck{'object hashes and sizes', 'skipped', '--fast requested; object bytes not verified', ''}119+	} else {120+		report.object_check('object hashes and sizes', store.check_objects() or {121+			[storage.ObjectProblem{'', err.msg()}]122+		})123+	}118124 	report.object_check('save object references', store.check_save_files() or {119125 		[storage.ObjectProblem{'', err.msg()}]120126 	})@@ -296,7 +302,7 @@296302 	if report.flagged_saves > 0 { saves << '${report.flagged_saves} flagged' }297303 	doctor_row('history', saves.join(' · '))298304 	doctor_row('storage', '${fmt.human_bytes(i64(report.size_bytes))} + ${fmt.human_bytes(i64(report.wal_bytes))} WAL · schema ${report.schema_version}')299-	doctor_row('', fmt.dim('${report.objects} objects · ${fmt.human_bytes(report.object_bytes)} → ${fmt.human_bytes(report.packed_bytes)} compressed · ${report.file_entries} file entries'))305+	doctor_row('', fmt.dim('${report.objects} objects · ${fmt.human_bytes(report.object_bytes)} → ${fmt.human_bytes(report.packed_bytes)} compressed · ${report.manifests} folder manifests'))300306 	changes := report.changes301307 	counts := ['${changes.added.len} added', '${changes.modified.len} modified',302308 		'${changes.removed.len} removed'].filter(!it.starts_with('0 '))@@ -398,7 +404,7 @@398404 	events               int399405 	flagged_saves        int400406 	head_flagged         bool401-	file_entries         i64407+	manifests            i64402408 	size_bytes           u64403409 	wal_bytes            u64404410 	object_bytes         i64

view file

src/cli/cmd_peek.v+4 −1
@@ -30,7 +30,10 @@3030 	if os.exists(path) {3131 		os.rmdir_all(path) or { return refuse(args.json(), err.msg()) }3232 	}33-	os.mkdir_all(path, os.MkdirParams{}) or { return refuse(args.json(), err.msg()) }33+	os.mkdir_all(path, os.MkdirParams{ mode: 0o700 }) or { return refuse(args.json(), err.msg()) }34+	// A peek is a copy of the repo; the root stays private so nothing below it35+	// is readable by other users on a shared machine.36+	os.chmod(path, 0o700) or { return refuse(args.json(), err.msg()) }3437 	snapshot.restore_files(store, path, snapshot.Ignore{}, files, []) or {3538 		return refuse(args.json(), err.msg())3639 	}

view file

src/cli/cmd_steal.v+6 −5
@@ -36,6 +36,11 @@3636 		if args.positional.len > 1 {3737 			return usage_error('steal takes one repo: koh steal myproject, or koh steal kepr.uk/nina')3838 		}39+		// A bare name becomes both a remote key and a folder here, so it obeys the40+		// same rule before anything is asked of a remote.41+		if !name.contains('/') && !exchange.valid_repo_name(name) {42+			return usage_error('"${name}" is not a repo name — a repo name is letters, digits, ., _ and -')43+		}3944 		address := web_address(name) or { return refuse(args.json(), err.msg()) }4045 		if address.len > 0 {4146 			return steal_web(address[0], address[1], args)@@ -415,11 +420,7 @@415420 	}416421 	repo := value.all_after_last('/')417422 	host := value.all_before_last('/')418-	if host == '' || repo in ['', '.', '..'] || !repo.bytes().all(it.is_alnum() || it in [419-		`.`,420-		`_`,421-		`-`,422-	]) {423+	if host == '' || !exchange.valid_repo_name(repo) {423424 		return error('"${value}" is not <host>/<repo> — a repo name is letters, digits, ., _ and -')424425 	}425426 	return [host, repo]

view file

src/cli/doctor_checks.v+9 −4
@@ -65,6 +65,9 @@6565 6666 fn doctor_files(id string, files []snapshot.FileEntry, event_list []events.Event,6767 	mut report DoctorJson) {68+	// Only a valid strip can leave residue. Callers that hold every event (the69+	// remote audit, tests) filter once per save here, never once per file.70+	strips := event_list.filter(events.valid_strip(it))6871 	mut paths := map[string]bool{}6972 	for file in files {7073 		paths[file.path] = true@@ -81,8 +84,8 @@8184 			}8285 			parent = os.dir(parent)8386 		}84-		for event in event_list {85-			if events.valid_strip(event) && (event.save_id == '' || event.save_id == id)87+		for event in strips {88+			if (event.save_id == '' || event.save_id == id)8689 				&& (file.path == event.path || file.path.starts_with('${event.path.trim_right('/')}/')) {8790 				report.problems << 'save ${id} still contains stripped path ${snapshot.escape_path(file.path)}'8891 				report.strip_residue = true@@ -137,7 +140,7 @@137140 	report.saves = int(stats.saves)138141 	report.checkpoints = int(stats.checkpoints)139142 	report.cached_files = int(stats.cached_files)140-	report.file_entries = stats.file_entries143+	report.manifests = stats.manifests141144 	report.object_bytes = stats.object_bytes142145 	report.packed_bytes = stats.packed_bytes143146 	report.unreferenced_objects = stats.unused@@ -171,8 +174,10 @@171174 	event_list := events.all(store)!172175 	before := report.problems.len173176 	doctor_events(event_list, saves, mut report)177+	// Filtered once here, so per-save filtering in doctor_files sees strips only.178+	strips := event_list.filter(events.valid_strip(it))174179 	for save in saves {175-		doctor_files(save.id, history.files_of(store, save.id)!, event_list, mut report)180+		doctor_files(save.id, history.files_of(store, save.id)!, strips, mut report)176181 		if save.replayed_from != '' && save.replayed_from !in known {177182 			report.warnings << 'save ${save.id} was replayed from unavailable save ${save.replayed_from}; nothing to do'178183 		}

view file

src/exchange/exchange.v+16 −4
@@ -72,6 +72,16 @@7272 	store.set_state(repo_state_key, name)!7373 }7474 75+// valid_repo_name is the one name rule: what Kepr serves, what `host/repo` carries and76+// what a key on the remote may be built from. A name with a space, a slash or a colon77+// would make a key nothing else can address, so every way in checks it first.78+pub fn valid_repo_name(name string) bool {79+	if name == '' || name == '.' || name == '..' {80+		return false81+	}82+	return name.bytes().all(it.is_alnum() || it in [`-`, `.`, `_`])83+}84+7585 // repo_name is the folder's name at first offer, lowercased so it makes the same7686 // Kepr URL whatever the folder's case (June, 2026-10-01), and remembered in the7787 // repo so renaming the folder later changes nothing.@@ -88,6 +98,11 @@8898 		return follow_rename(store, mut backend, remembered)!8999 	}90100 	name := os.base(store.root).to_lower()101+	// Before any read: a name Kepr cannot serve would only be refused later, with a102+	// key already built from it.103+	if !valid_repo_name(name) {104+		return error('"${name}" is not a repo name — a repo name is letters, digits, ., _ and -; rename the folder')105+	}91106 	// Before the clash check below: a remote this koh cannot read is a "update92107 	// koh" answer, not a "rename the folder" one.93108 	check_format(mut backend, name)!@@ -115,10 +130,7 @@115130 		}116131 		marker := backend.get('.kepr/renamed/${name}')!117132 		next := marker.body.bytestr().trim_space()118-		if !marker.found || next == '' || next.contains('/') || next.contains('\\') || next in [119-			'.',120-			'..',121-		] {133+		if !marker.found || !valid_repo_name(next) {122134 			break123135 		}124136 		name = next

view file

src/exchange/exchange_test.v+40 −2
@@ -203,6 +203,41 @@203203 	assert offer_now(a, mut backend)!.repo == 'proj'204204 }205205 206+// The rule every name passes: what Kepr serves, so a key on the remote is one207+// another machine can address.208+fn test_only_names_kepr_serves_are_repo_names() {209+	for name in ['proj', 'a', 'Koh.v2', 'a_b-c.d', '-', '_', '...'] {210+		assert valid_repo_name(name), name211+	}212+	for name in ['', '.', '..', 'two words', 'a/b', 'a\\b', 'nina\n', 'é', 'a:b', '%41'] {213+		assert !valid_repo_name(name), name214+	}215+}216+217+// The folder's name is the remote key at first offer, so one Kepr cannot serve218+// is refused before any request, with the fix in the message.219+fn test_a_folder_name_that_is_not_a_repo_name_is_refused() {220+	base := scratch('spacey')!221+	defer {222+		os.rmdir_all(base) or {}223+	}224+	dir := os.join_path(base, 'two words')225+	os.mkdir_all(dir, os.MkdirParams{})!226+	mut a := open_repo(dir)!227+	defer {228+		a.close()229+	}230+	put(a.root, 'a.txt', 'one\n')!231+	make_save(a, 'first')!232+	mut backend := remote.new_folder(os.join_path(base, 'remote'))!233+	if _ := offer_now(a, mut backend) {234+		assert false, 'a folder name with a space must not become a remote repo'235+	} else {236+		assert err.msg().contains('rename the folder'), err.msg()237+	}238+	assert a.state('remote_repo') == none239+}240+206241 fn test_steal_fast_forwards_a_machine_that_has_nothing_of_its_own() {207242 	base := scratch('forward')!208243 	defer {@@ -2435,8 +2470,11 @@24352470 	put(store.root, 'secret', 'secret')!24362471 	put(store.root, 'keep', 'keep')!24372472 	save := make_save(store, 'initial')!2438-	store.db.exec("CREATE TRIGGER block_secret BEFORE DELETE ON save_files2439-		WHEN OLD.path = 'secret' BEGIN SELECT RAISE(ABORT, 'blocked'); END")!2473+	secret_hash := storage.hash_hex('secret'.bytes())2474+	store.db.exec("CREATE TRIGGER block_secret BEFORE UPDATE OF manifest ON saves2475+		WHEN NOT EXISTS (SELECT 1 FROM manifests2476+			WHERE hash = NEW.manifest AND body LIKE '%${secret_hash}%')2477+		BEGIN SELECT RAISE(ABORT, 'blocked'); END")!24402478 	if _ := strip_local_batch(store, ['private', 'secret'], '') {24412479 		assert false, 'batch succeeded despite the second path failing'24422480 	}

view file

src/exchange/steal.v+26 −12
@@ -408,6 +408,9 @@408408 	remote_head := fetched.saves.last()409409 	mut clashes := find_clashes(after_strips(base_files, fetched.base, strips), after_strips(history.files_of(store,410410 		head.id)!, head.id, strips), after_strips(to_files(remote_head), remote_head.id, strips))411+	// One cache for the whole clash pass: each save's file list is read once,412+	// not once per clash on either side.413+	mut trees := map[string]map[string]snapshot.FileEntry{}411414 	for mut clash in clashes {412415 		base := fetched_bytes(store, fetched, clash.base)!413416 		mine := fetched_bytes(store, fetched, clash.mine)!@@ -418,8 +421,8 @@418421 		clash.theirs_stat = delta_stat(theirs_delta, clash.theirs.size)419422 		clash.mine_patch = mine_delta.patch420423 		clash.theirs_patch = theirs_delta.patch421-		clash.mine_save = last_touch(store, local_only, clash.path)!422-		clash.theirs_save = last_touch(store, fetched.saves.map(to_save(it)), clash.path)!424+		clash.mine_save = last_touch(store, local_only, clash.path, mut trees)!425+		clash.theirs_save = last_touch(store, fetched.saves.map(to_save(it)), clash.path, mut trees)!423426 	}424427 	return clashes425428 }@@ -431,24 +434,35 @@431434 	return '+${delta.added} -${delta.removed}'432435 }433436 434-fn last_touch(store &storage.Store, saves []history.Save, path string) !history.Save {437+// last_touch is the newest save that changed `path`, walking back from the end.438+// `trees` is the caller's cache, so each save's list is indexed once per steal439+// rather than once per clash.440+fn last_touch(store &storage.Store, saves []history.Save, path string, mut trees map[string]map[string]snapshot.FileEntry) !history.Save {435441 	for index := saves.len - 1; index >= 0; index-- {436442 		save := saves[index]437-		current := snapshot.index_files(history.files_of(store, save.id)!)[path] or {438-			snapshot.FileEntry{}443+		here := save_tree(store, mut trees, save.id)!444+		current := here[path] or { snapshot.FileEntry{} }445+		mut parent := snapshot.FileEntry{}446+		if save.parent != '' {447+			was := save_tree(store, mut trees, save.parent)!448+			parent = was[path] or { snapshot.FileEntry{} }439449 		}440-		parent := if save.parent != '' {441-			snapshot.index_files(history.files_of(store, save.parent)!)[path] or {442-				snapshot.FileEntry{}443-			}444-		} else {445-			snapshot.FileEntry{}446-		}447450 		if !same(current, parent) {448451 			return save449452 		}450453 	}451454 	return saves.last()455+}456+457+// save_tree is a save's files indexed by path, read once and kept for the rest458+// of the steal.459+fn save_tree(store &storage.Store, mut trees map[string]map[string]snapshot.FileEntry, save_id string) !map[string]snapshot.FileEntry {460+	if index := trees[save_id] {461+		return index462+	}463+	index := snapshot.index_files(history.files_of(store, save_id)!)464+	trees[save_id] = index465+	return index452466 }453467 454468 // combine_preview counts what a combine would do to the paths either side changed since `base`:

view file

src/exchange/strip.v+272 −44
@@ -81,20 +81,14 @@8181 	return file == path || file.starts_with('${path.trim_right('/')}/')8282 }8383 84-// strip_scope counts the rows strip_rows will delete, using the same match. `objects` is the distinct85-// content they hold; content another path still uses is kept, so fewer may be deleted.84+// strip_scope counts what strip_rows will remove, using the same trie walk. `objects` is the85+// distinct content they hold; content another path still uses is kept, so fewer may be deleted.8686 pub fn strip_scope(store &storage.Store, path string, only_save string) !Scope {87-	mut stmt := store.db.prepare('SELECT COUNT(*), COUNT(DISTINCT save_id), COUNT(DISTINCT hash)88-		FROM save_files WHERE ${match_clause(only_save)}')!89-	defer {90-		stmt.finalize()91-	}92-	bind_match(stmt, path, only_save)!93-	stmt.step()!87+	covered := covered_by(store, path.trim_right('/'), only_save)!9488 	return Scope{95-		files:   int(stmt.int(0))96-		saves:   int(stmt.int(1))97-		objects: int(stmt.int(2))89+		files:   covered.files90+		saves:   covered.saves91+		objects: covered.hashes.len9892 	}9993 }10094 @@ -130,19 +124,21 @@130124 // strip_rows is the body of strip_local's transaction. Its event has no save id for a whole-history131125 // strip (spec §10.2), and that empty id is what bans the path from every later walk.132126 fn strip_rows(store &storage.Store, path string, only_save string) !LocalStrip {133-	hashes := stripped_hashes(store, path, only_save)!134-	if hashes.len == 0 {127+	target := path.trim_right('/')128+	covered := covered_by(store, target, only_save)!129+	if covered.hashes.len == 0 {135130 		// Already stripped: keep the pending note an unfinished remote needs.136131 		return LocalStrip{}137132 	}138-	removed := remove_path(store, path, only_save)!139-	dropped := store.drop_unused(hashes)!133+	rewrite_saves(store, target, only_save)!134+	store.drop_unreachable_manifests()!135+	dropped := store.drop_unused(covered.hashes)!140136 	events.strip(store, only_save, path)!141137 	// An earlier strip of the same path may not have finished on the remote,142138 	// so the note grows rather than resets.143-	queue_strip(store, path, [only_save], hashes)!139+	queue_strip(store, path, [only_save], covered.hashes)!144140 	return LocalStrip{145-		files_removed:   removed141+		files_removed:   covered.files146142 		objects_dropped: dropped147143 	}148144 }@@ -277,44 +273,276 @@277273 	}278274 }279275 280-// stripped_hashes is the content of the rows remove_path will delete.281-fn stripped_hashes(store &storage.Store, path string, only_save string) ![]string {282-	mut stmt :=283-		store.db.prepare('SELECT DISTINCT hash FROM save_files WHERE ${match_clause(only_save)}')!276+struct Covered {277+	files  int278+	saves  int279+	hashes []string280+}281+282+// Subtree is one folder's files, counted once and reused.283+struct Subtree {284+	files  int285+	hashes []string286+}287+288+struct SaveTree {289+	id       string290+	manifest string291+}292+293+fn save_trees(store &storage.Store, only_save string) ![]SaveTree {294+	mut stmt := store.db.prepare('SELECT id, manifest FROM saves ORDER BY id')!284295 	defer {285296 		stmt.finalize()286297 	}287-	bind_match(stmt, path, only_save)!288-	mut hashes := []string{}298+	mut trees := []SaveTree{}289299 	for stmt.step()! {290-		hashes << stmt.text(0)300+		id := stmt.text(0)301+		if only_save != '' && id != only_save {302+			continue303+		}304+		trees << SaveTree{305+			id:       id306+			manifest: stmt.text(1)307+		}291308 	}292-	return hashes309+	return trees293310 }294311 295-// remove_path deletes the rows and counts them; the objects go afterwards, once nothing references them.312+struct FoundEntry {313+	ok    bool314+	entry storage.ManifestEntry315+}316+317+// find_entry follows `path`'s segments from the root. A folder where a file318+// was expected is no match, and a folder entry named exactly the remaining319+// path covers its whole subtree.320+fn find_entry(store &storage.Store, root string, path string) !FoundEntry {321+	mut hash := root322+	mut rest := path323+	for {324+		entries := store.manifest_entries(hash)!325+		for entry in entries {326+			if entry.name == rest {327+				return FoundEntry{328+					ok:    true329+					entry: entry330+				}331+			}332+		}333+		slash := rest.index('/') or { return FoundEntry{} }334+		segment := rest[..slash]335+		mut child := ''336+		for entry in entries {337+			if entry.name == segment && entry.kind == storage.folder_kind {338+				child = entry.manifest339+				break340+			}341+		}342+		if child == '' {343+			return FoundEntry{}344+		}345+		hash = child346+		rest = rest[slash + 1..]347+	}348+	return FoundEntry{}349+}350+351+// subtree counts one folder's files, memoized by manifest hash so a tree two352+// saves share is walked once.353+fn subtree(store &storage.Store, hash string, mut memo map[string]Subtree, mut busy map[string]bool) !Subtree {354+	if hash in memo {355+		return memo[hash]356+	}357+	if busy[hash] {358+		return error('manifest ${hash} refers to itself')359+	}360+	busy[hash] = true361+	mut files := 0362+	mut hashes := map[string]bool{}363+	entries := store.manifest_entries(hash)!364+	for entry in entries {365+		if entry.kind == storage.file_kind {366+			files++367+			hashes[entry.hash] = true368+		} else {369+			child := subtree(store, entry.manifest, mut memo, mut busy)!370+			files += child.files371+			for h in child.hashes {372+				hashes[h] = true373+			}374+		}375+	}376+	busy.delete(hash)377+	summary := Subtree{378+		files:  files379+		hashes: hashes.keys()380+	}381+	memo[hash] = summary382+	return summary383+}384+385+// stripped_hashes is the content a strip of `path` would free.386+fn stripped_hashes(store &storage.Store, path string, only_save string) ![]string {387+	return covered_by(store, path.trim_right('/'), only_save)!.hashes388+}389+390+// remove_path rewrites every save that holds the path and returns the files it391+// removed; callers drop the freed objects once nothing references them.296392 fn remove_path(store &storage.Store, path string, only_save string) !int {297-	mut stmt := store.db.prepare('DELETE FROM save_files WHERE ${match_clause(only_save)}')!298-	defer {299-		stmt.finalize()393+	target := path.trim_right('/')394+	covered := covered_by(store, target, only_save)!395+	rewrite_saves(store, target, only_save)!396+	store.drop_unreachable_manifests()!397+	return covered.files398+}399+400+// covered_by counts the files `path` reaches, the saves that hold them and the401+// distinct content they carry.402+fn covered_by(store &storage.Store, path string, only_save string) !Covered {403+	mut files := 0404+	mut saves := 0405+	mut hashes := map[string]bool{}406+	mut memo := map[string]Subtree{}407+	mut busy := map[string]bool{}408+	for tree in save_trees(store, only_save)! {409+		found := find_entry(store, tree.manifest, path)!410+		if found.ok {411+			entry := found.entry412+			mut here := 0413+			if entry.kind == storage.file_kind {414+				here = 1415+				hashes[entry.hash] = true416+			} else {417+				summary := subtree(store, entry.manifest, mut memo, mut busy)!418+				here = summary.files419+				for hash in summary.hashes {420+					hashes[hash] = true421+				}422+			}423+			if here > 0 {424+				files += here425+				saves++426+			}427+		}300428 	}301-	bind_match(stmt, path, only_save)!302-	stmt.step()!303-	return store.db.changes()429+	mut distinct := hashes.keys()430+	distinct.sort()431+	return Covered{432+		files:  files433+		saves:  saves434+		hashes: distinct435+	}304436 }305437 306-// match_clause is `covers` in SQL. LIKE would ignore ASCII case and treat `_`307-// and `%` as wildcards; a strip destroys, so the prefix is compared exactly.308-fn match_clause(only_save string) string {309-	scope := if only_save == '' { '' } else { ' AND save_id = ?3' }310-	return '(path = ?1 OR substr(path, 1, length(?2)) = ?2)${scope}'438+// Rewriter rebuilds the folders on one path without mutating a row. The memo439+// keeps old folder hash to new, so identical subtrees are rewritten once.440+struct Rewriter {441+mut:442+	memo map[string]string443+	busy map[string]bool311444 }312445 313-// bind_match fills what match_clause names: ?1 the path, ?2 its folder prefix, ?3 the save.314-fn bind_match(stmt &storage.Stmt, path string, only_save string) ! {315-	stmt.bind_text(1, path)!316-	stmt.bind_text(2, '${path.trim_right('/')}/')!317-	if only_save != '' {318-		stmt.bind_text(3, only_save)!446+struct Rewritten {447+	changed bool448+	hash    string449+}450+451+// rewrite returns `hash` with `path` removed, or unchanged when the tree does452+// not hold it.453+fn (mut r Rewriter) rewrite(store &storage.Store, hash string, path string) !Rewritten {454+	key := '${hash}\x00${path}'455+	if key in r.memo {456+		found := r.memo[key]457+		if found == '' {458+			return Rewritten{}459+		}460+		return Rewritten{461+			changed: true462+			hash:    found463+		}464+	}465+	if r.busy[key] {466+		return error('manifest ${hash} refers to itself')467+	}468+	r.busy[key] = true469+	entries := store.manifest_entries(hash)!470+	mut kept := []storage.ManifestEntry{}471+	mut exact := false472+	for entry in entries {473+		if entry.name == path {474+			exact = true475+		}476+	}477+	if exact {478+		for entry in entries {479+			if entry.name != path {480+				kept << entry481+			}482+		}483+	} else {484+		slash := path.index('/') or { -1 }485+		if slash < 0 {486+			r.miss(key)487+			return Rewritten{}488+		}489+		segment := path[..slash]490+		mut at := -1491+		for i, entry in entries {492+			if entry.name == segment && entry.kind == storage.folder_kind {493+				at = i494+				break495+			}496+		}497+		if at < 0 {498+			r.miss(key)499+			return Rewritten{}500+		}501+		child := r.rewrite(store, entries[at].manifest, path[slash + 1..])!502+		if child.changed {503+			kept = entries.clone()504+			kept[at] = storage.ManifestEntry{505+				name:     entries[at].name506+				kind:     storage.folder_kind507+				manifest: child.hash508+			}509+		} else {510+			r.miss(key)511+			return Rewritten{}512+		}513+	}514+	new_hash := store.put_manifest(json2.encode(storage.Manifest{515+		entries: kept516+	}))!517+	r.busy.delete(key)518+	r.memo[key] = new_hash519+	return Rewritten{520+		changed: true521+		hash:    new_hash522+	}523+}524+525+// miss remembers that this folder does not hold the path.526+fn (mut r Rewriter) miss(key string) {527+	r.busy.delete(key)528+	r.memo[key] = ''529+}530+531+// rewrite_saves points every save that holds `path` at its rewritten root.532+// A save whose tree does not hold the path is not touched.533+fn rewrite_saves(store &storage.Store, path string, only_save string) ! {534+	mut rewriter := Rewriter{}535+	mut update := store.db.prepare('UPDATE saves SET manifest = ? WHERE id = ?')!536+	defer {537+		update.finalize()538+	}539+	for tree in save_trees(store, only_save)! {540+		rewritten := rewriter.rewrite(store, tree.manifest, path)!541+		if rewritten.changed {542+			update.bind_text(1, rewritten.hash)!543+			update.bind_text(2, tree.id)!544+			update.step()!545+			update.reset()546+		}319547 	}320548 }

view file

src/exchange/strip_test.v+69 −0
@@ -0,0 +1,69 @@1+//! Stripping one save must not disturb another save that shares manifests.2+3+module exchange4+5+import os6+import src.history7+import src.snapshot8+import src.storage9+10+fn strip_test_repo(name string) !storage.Store {11+	dir := os.join_path(os.temp_dir(), 'koh3_strip_${os.getpid()}_${name}')12+	os.rmdir_all(dir) or {}13+	os.mkdir_all(dir)!14+	mut store := storage.create(dir)!15+	os.write_file(os.join_path(dir, '.kohignore'), '*.log\n')!16+	return store17+}18+19+fn strip_test_put(root string, rel string, text string) ! {20+	full := os.join_path(root, rel)21+	os.mkdir_all(os.dir(full))!22+	os.write_file(full, text)!23+}24+25+fn strip_test_save(store &storage.Store, message string) !history.Save {26+	return history.save_worktree(store, store.root, snapshot.load(store.root), history.SaveInput{27+		message: message28+	})!29+}30+31+fn strip_test_folder(store &storage.Store, root string, name string) !string {32+	for entry in store.manifest_entries(root)! {33+		if entry.name == name && entry.kind == storage.folder_kind {34+			return entry.manifest35+		}36+	}37+	return error('no folder ${name}')38+}39+40+fn test_stripping_one_save_leaves_a_sharing_save_untouched() {41+	mut store := strip_test_repo('isolation')!42+	defer {43+		store.close()44+		os.rmdir_all(store.root) or {}45+	}46+	strip_test_put(store.root, 'a/keep', 'keep')!47+	strip_test_put(store.root, 'a/secret', 'secret')!48+	strip_test_put(store.root, 'b/x', 'x')!49+	first := strip_test_save(store, 'first')!50+	strip_test_put(store.root, 'a/secret', 'secret two')!51+	second := strip_test_save(store, 'second')!52+	first_saved := history.by_id(store, first.id) or { panic('first save is missing') }53+	second_saved := history.by_id(store, second.id) or { panic('second save is missing') }54+	first_root := first_saved.manifest55+	second_root := second_saved.manifest56+	assert first_root != second_root57+	shared_b := strip_test_folder(store, second_root, 'b')!58+	first_b := strip_test_folder(store, first_root, 'b')!59+	assert first_b == shared_b60+	strip_local(store, 'a/secret', first.id)!61+	first_paths := history.files_of(store, first.id)!62+	assert first_paths.map(it.path) == ['.kohignore', 'a/keep', 'b/x']63+	second_paths := history.files_of(store, second.id)!64+	assert second_paths.map(it.path) == ['.kohignore', 'a/keep', 'a/secret', 'b/x']65+	assert store.manifest_body(second_root)!.contains('"name":"b"')66+	assert store.manifest_body(shared_b)!.contains('"name":"x"')67+	gone := store.has_object(storage.hash_hex('secret'.bytes()))!68+	assert !gone69+}

view file

src/history/history.v+18 −11
@@ -10,6 +10,7 @@1010 pub mut:1111 	id            string1212 	parent        string13+	manifest      string1314 	message       string1415 	created_at    i641516 	machine       string@@ -22,7 +23,7 @@2223 }2324 2425 const select_save = 'SELECT id, parent, message, created_at, machine, is_checkpoint, size_bytes,25-	agent, session, restores, replayed_from FROM saves'26+	agent, session, restores, replayed_from, manifest FROM saves'2627 2728 fn read_save(stmt &storage.Stmt) Save {2829 	return Save{@@ -37,6 +38,7 @@3738 		session:       stmt.text_or_none(8) or { '' }3839 		restores:      stmt.text_or_none(9) or { '' }3940 		replayed_from: stmt.text_or_none(10) or { '' }41+		manifest:      stmt.text(11)4042 	}4143 }4244 @@ -202,22 +204,27 @@202204 	return none203205 }204206 205-// files_of lists a save's files sorted by path, each with its object's size.207+// files_of lists a save's files sorted by path, read from its manifest tree.206208 pub fn files_of(store &storage.Store, save_id string) ![]snapshot.FileEntry {207-	mut stmt :=208-		store.db.prepare('SELECT path, hash, executable FROM save_files WHERE save_id = ? ORDER BY path')!209+	mut stmt := store.db.prepare('SELECT manifest FROM saves WHERE id = ?')!209210 	defer {210211 		stmt.finalize()211212 	}212213 	stmt.bind_text(1, save_id)!213-	mut files := []snapshot.FileEntry{}214-	for stmt.step()! {215-		hash := stmt.text(1)214+	if !stmt.step()! {215+		return error('save ${save_id} is missing')216+	}217+	root := stmt.text(0)218+	entries := store.manifest_files(root) or {219+		return error('save ${save_id}: ${err.msg()}')220+	}221+	mut files := []snapshot.FileEntry{cap: entries.len}222+	for entry in entries {216223 		files << snapshot.FileEntry{217-			path:       stmt.text(0)218-			hash:       hash219-			size:       store.object_size(hash) or { 0 }220-			executable: stmt.int(2) != 0224+			path:       entry.path225+			hash:       entry.hash226+			size:       entry.size227+			executable: entry.executable221228 		}222229 	}223230 	return files

view file

src/history/save.v+72 −29
@@ -110,7 +110,7 @@110110 		created_at:    created_at111111 		machine:       if input.machine != '' { input.machine } else { machine.name() }112112 		is_checkpoint: input.is_checkpoint113-		size_bytes:    tree_size(store, files)113+		size_bytes:    tree_size(files)114114 		agent:         input.agent115115 		session:       input.session116116 		restores:      input.restores@@ -132,9 +132,33 @@132132 133133 // import_save records a save exactly as another machine made it: same ID, same134134 // parent, same time, same files. `steal` and `migrate` use it; a save made here135-// goes through write_save instead, which mints the ID.135+// goes through write_save instead, which mints the ID. A record carries no136+// sizes, so a file whose size is not known yet takes it from its object — the137+// manifest stores it and every later read avoids asking.136138 pub fn import_save(store &storage.Store, save Save, files []snapshot.FileEntry) ! {137-	insert_save(store, save, files)!139+	mut sized := files.clone()140+	if sized.any(it.size == 0) {141+		mut stmt := store.db.prepare('SELECT size FROM objects WHERE hash = ?')!142+		defer {143+			stmt.finalize()144+		}145+		for index in 0 .. sized.len {146+			if sized[index].size != 0 {147+				continue148+			}149+			stmt.bind_text(1, sized[index].hash)!150+			if stmt.step()! {151+				sized[index] = snapshot.FileEntry{152+					path:       sized[index].path153+					hash:       sized[index].hash154+					size:       stmt.int(0)155+					executable: sized[index].executable156+				}157+			}158+			stmt.reset()159+		}160+	}161+	insert_save(store, save, sized)!138162 }139163 140164 // set_head moves the line's head without creating a save. Only fetching another@@ -144,43 +168,62 @@144168 	store.set_state(storage.head_key, id)!145169 }146170 147-// insert_save writes the save row, then one row per file. Its callers hold the transaction.171+// insert_save writes the save row, naming the root manifest built from its172+// files. Every object the tree names must already be here: the manifest has no173+// foreign key to `objects`, so this is the check that a half-written save174+// cannot exist. Its callers hold the transaction.148175 fn insert_save(store &storage.Store, save Save, files []snapshot.FileEntry) ! {149-	mut stmt := store.db.prepare('INSERT INTO saves (id, parent, message, created_at, machine,176+	manifest := store.manifest_tree(manifest_files(files))!177+	mut seen := map[string]bool{}178+	mut lookup := store.db.prepare('SELECT 1 FROM objects WHERE hash = ?')!179+	defer {180+		lookup.finalize()181+	}182+	for file in files {183+		if file.hash in seen {184+			continue185+		}186+		seen[file.hash] = true187+		lookup.bind_text(1, file.hash)!188+		if !lookup.step()! {189+			return error('save ${save.id} needs missing object ${file.hash}')190+		}191+		lookup.reset()192+	}193+	mut stmt := store.db.prepare('INSERT INTO saves (id, parent, manifest, message, created_at, machine,150194 		is_checkpoint, size_bytes, agent, session, restores, replayed_from)151-		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')!195+		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')!152196 	stmt.bind_text(1, save.id)!153197 	if save.parent == '' {154198 		stmt.bind_null(2)!155199 	} else {156200 		stmt.bind_text(2, save.parent)!157201 	}158-	stmt.bind_text(3, save.message)!159-	stmt.bind_int(4, save.created_at)!160-	stmt.bind_text(5, save.machine)!161-	stmt.bind_int(6, if save.is_checkpoint { 1 } else { 0 })!162-	stmt.bind_int(7, save.size_bytes)!163-	bind_optional(stmt, 8, save.agent)!164-	bind_optional(stmt, 9, save.session)!165-	bind_optional(stmt, 10, save.restores)!166-	bind_optional(stmt, 11, save.replayed_from)!202+	stmt.bind_text(3, manifest)!203+	stmt.bind_text(4, save.message)!204+	stmt.bind_int(5, save.created_at)!205+	stmt.bind_text(6, save.machine)!206+	stmt.bind_int(7, if save.is_checkpoint { 1 } else { 0 })!207+	stmt.bind_int(8, save.size_bytes)!208+	bind_optional(stmt, 9, save.agent)!209+	bind_optional(stmt, 10, save.session)!210+	bind_optional(stmt, 11, save.restores)!211+	bind_optional(stmt, 12, save.replayed_from)!167212 	stmt.step()!168213 	stmt.finalize()214+}169215 170-	mut files_stmt :=171-		store.db.prepare('INSERT INTO save_files (save_id, path, hash, executable) VALUES (?, ?, ?, ?)')!172-	defer {173-		files_stmt.finalize()174-	}216+fn manifest_files(files []snapshot.FileEntry) []storage.ManifestFile {217+	mut out := []storage.ManifestFile{cap: files.len}175218 	for file in files {176-		files_stmt.bind_text(1, save.id)!177-		files_stmt.bind_text(2, file.path)!178-		files_stmt.bind_text(3, file.hash)!179-		files_stmt.bind_int(4, if file.executable { 1 } else { 0 })!180-		files_stmt.step()!181-		// A statement that has returned DONE must be reset before rebinding.182-		files_stmt.reset()219+		out << storage.ManifestFile{220+			path:       file.path221+			hash:       file.hash222+			size:       file.size223+			executable: file.executable224+		}183225 	}226+	return out184227 }185228 186229 fn bind_optional(stmt &storage.Stmt, index int, value string) ! {@@ -224,10 +267,10 @@224267 	sb.write_string('\n')225268 }226269 227-fn tree_size(store &storage.Store, files []snapshot.FileEntry) i64 {270+fn tree_size(files []snapshot.FileEntry) i64 {228271 	mut total := i64(0)229272 	for file in files {230-		total += store.object_size(file.hash) or { 0 }273+		total += file.size231274 	}232275 	return total233276 }

view file

src/release/release_test.v+0 −1
@@ -5,7 +5,6 @@55 66 import json277 import os8-import time98 import src.build109 import src.history1110 import src.machine

view file

src/remote/s3.v+3 −2
@@ -146,7 +146,8 @@146146 }147147 148148 // send signs one request and retries the failures worth retrying: a network149-// error, or a 5xx. A 412 is an answer, not a fault, and is never retried.149+// error, a 5xx, or a 429 (a rate limit is transient, like a 5xx).150+// A 412 is an answer, not a fault, and is never retried.150151 fn (mut s S3) send(method string, key string, query string, headers map[string]string, body []u8) !http.Response {151152 	url := s.url_for(key, query)152153 	mut last := ''@@ -172,7 +173,7 @@172173 			time.sleep(backoff(attempt))173174 			continue174175 		}175-		if response.status_code >= 500 {176+		if response.status_code >= 500 || response.status_code == 429 {176177 			last = '${response.status_code}'177178 			time.sleep(backoff(attempt))178179 			continue

view file

src/snapshot/diff.v+4 −1
@@ -164,7 +164,10 @@164164 165165 fn temp_workspace() !string {166166 	dir := os.join_path(os.temp_dir(), 'koh-diff-${os.getpid()}-${time.now().unix_nano()}')167-	os.mkdir_all(dir, os.MkdirParams{})!167+	os.mkdir_all(dir, os.MkdirParams{ mode: 0o700 })!168+	// The umask can widen nothing but can narrow mkdir's mode; chmod makes the169+	// workspace private even on a shared machine.170+	os.chmod(dir, 0o700)!168171 	return dir169172 }170173 

view file

src/storage/doctor.v+26 −11
@@ -8,7 +8,7 @@88 	saves        i6499 	checkpoints  i641010 	cached_files i6411-	file_entries i6411+	manifests    i641212 	object_bytes i641313 	packed_bytes i641414 	unused       i64@@ -32,26 +32,28 @@3232 		(SELECT COUNT(*) FROM saves),3333 		(SELECT COUNT(*) FROM saves WHERE is_checkpoint = 1),3434 		(SELECT COUNT(*) FROM file_cache),35-		(SELECT COUNT(*) FROM save_files),36-		(SELECT COUNT(*) FROM objects WHERE hash NOT IN (SELECT hash FROM save_files))')!35+		(SELECT COUNT(*) FROM manifests)')!3736 	defer { counts.finalize() }3837 	if counts.step()! {3938 		out.saves = counts.int(0)4039 		out.checkpoints = counts.int(1)4140 		out.cached_files = counts.int(2)42-		out.file_entries = counts.int(3)43-		out.unused = counts.int(4)41+		out.manifests = counts.int(3)4442 	}43+	used := s.manifest_object_hashes()!44+	mut objects := s.db.prepare('SELECT hash FROM objects')!45+	defer { objects.finalize() }46+	for objects.step()! {47+		if objects.text(0) !in used {48+			out.unused++49+		}50+	}4551 	mut foreign := s.db.prepare('PRAGMA foreign_key_check')!4652 	defer { foreign.finalize() }4753 	for foreign.step()! {4854 		out.problems << 'broken reference in ${foreign.text(0)} row ${foreign.int(1)} to ${foreign.text(2)}'4955 	}50-	mut invalid := s.db.prepare("SELECT save_id, path FROM save_files51-		WHERE executable NOT IN (0, 1)52-		OR typeof(executable) != 'integer'53-		UNION ALL54-		SELECT id, 'invalid save metadata' FROM saves56+	mut invalid := s.db.prepare("SELECT id FROM saves5557 		WHERE is_checkpoint NOT IN (0, 1)5658 		OR typeof(is_checkpoint) != 'integer'5759 		OR id = ''@@ -61,7 +63,20 @@6163 		OR size_bytes < 0")!6264 	defer { invalid.finalize() }6365 	for invalid.step()! {64-		out.problems << 'invalid metadata in save ${invalid.text(0)}: ${invalid.text(1)}'66+		out.problems << 'invalid metadata in save ${invalid.text(0)}'67+	}68+	mut manifests := s.db.prepare('SELECT hash, body FROM manifests')!69+	defer { manifests.finalize() }70+	for manifests.step()! {71+		hash := manifests.text(0)72+		body := manifests.text(1)73+		if hash_hex(body.bytes()) != hash {74+			out.problems << 'invalid metadata in manifest ${hash}: its hash does not match its body'75+			continue76+		}77+		decode_manifest(body) or {78+			out.problems << 'invalid metadata in manifest ${hash}: ${err.msg()}'79+		}6580 	}6681 	mut state := s.db.prepare('SELECT key, value FROM state')!6782 	defer { state.finalize() }

view file

src/storage/manifest.v+278 −0
@@ -0,0 +1,278 @@1+//! Manifests: one folder's immediate entries, content-addressed.2+//!3+//! A save names its root manifest. Each folder is one row whose hash is the4+//! Blake3 of its canonical body, so a folder two saves share is stored once,5+//! and changing one file only writes the folders on its path.6+7+module storage8+9+import json210+11+pub const file_kind = 'file'12+pub const folder_kind = 'folder'13+14+// One immediate entry: a file names its object, a folder names its manifest.15+pub struct ManifestEntry {16+pub:17+	name       string18+	kind       string19+	hash       string20+	size       i6421+	executable bool22+	manifest   string23+}24+25+// The canonical body. Field order is the encoding, so it is the schema.26+pub struct Manifest {27+pub:28+	entries []ManifestEntry29+}30+31+// One file in a flattened tree, with its repo-relative path.32+pub struct ManifestFile {33+pub:34+	path       string35+	hash       string36+	size       i6437+	executable bool38+}39+40+// put_manifest stores a body and returns its hash. An identical body is41+// already there, so writing it again is a no-op.42+pub fn (s &Store) put_manifest(body string) !string {43+	hash := hash_hex(body.bytes())44+	mut stmt := s.db.prepare('INSERT OR IGNORE INTO manifests (hash, body) VALUES (?, ?)')!45+	defer {46+		stmt.finalize()47+	}48+	stmt.bind_text(1, hash)!49+	stmt.bind_text(2, body)!50+	stmt.step()!51+	return hash52+}53+54+pub fn (s &Store) manifest_body(hash string) !string {55+	mut stmt := s.db.prepare('SELECT body FROM manifests WHERE hash = ?')!56+	defer {57+		stmt.finalize()58+	}59+	stmt.bind_text(1, hash)!60+	if !stmt.step()! {61+		return error('manifest ${hash} is missing')62+	}63+	return stmt.text(0)64+}65+66+// decode_manifest checks the shape every reader depends on: a known kind, and67+// the field that kind requires. Names are not checked — a damaged tree keeps68+// its odd names so a strip can still name and remove one.69+fn decode_manifest(body string) ![]ManifestEntry {70+	decoded := json2.decode[Manifest](body) or {71+		return error('its body is not readable: ${err.msg()}')72+	}73+	for entry in decoded.entries {74+		if entry.name == '' {75+			return error('it has an entry with no name')76+		}77+		if entry.kind == file_kind {78+			if !valid_hash(entry.hash) {79+				return error('its entry ${entry.name} has an invalid object hash ${entry.hash}')80+			}81+			if entry.size < 0 {82+				return error('its entry ${entry.name} has a negative size')83+			}84+		} else if entry.kind == folder_kind {85+			if !valid_hash(entry.manifest) {86+				return error('its entry ${entry.name} has an invalid manifest hash ${entry.manifest}')87+			}88+		} else {89+			return error('its entry ${entry.name} has unknown kind "${entry.kind}"')90+		}91+	}92+	return decoded.entries93+}94+95+pub fn (s &Store) manifest_entries(hash string) ![]ManifestEntry {96+	body := s.manifest_body(hash)!97+	return decode_manifest(body) or { return error('manifest ${hash} is invalid: ${err.msg()}') }98+}99+100+// manifest_tree builds and stores the folders of `files` (repo-relative,101+// `/`-separated) and returns the root hash.102+pub fn (s &Store) manifest_tree(files []ManifestFile) !string {103+	mut sorted := files.clone()104+	sorted.sort(a.path < b.path)105+	return s.manifest_level('', sorted)106+}107+108+fn (s &Store) manifest_level(prefix string, files []ManifestFile) !string {109+	mut entries := []ManifestEntry{}110+	mut i := 0111+	for i < files.len {112+		rest := files[i].path[prefix.len..]113+		slash := rest.index('/') or { -1 }114+		if slash < 0 {115+			entries << ManifestEntry{116+				name:       rest117+				kind:       file_kind118+				hash:       files[i].hash119+				size:       files[i].size120+				executable: files[i].executable121+			}122+			i++123+			continue124+		}125+		name := rest[..slash]126+		start := i127+		for i < files.len && segment_at(files[i].path, prefix) == name {128+			i++129+		}130+		child := s.manifest_level('${prefix}${name}/', files[start..i])!131+		entries << ManifestEntry{132+			name:     name133+			kind:     folder_kind134+			manifest: child135+		}136+	}137+	entries.sort_with_compare(fn (a &ManifestEntry, b &ManifestEntry) int {138+		if a.name != b.name {139+			return if a.name < b.name { -1 } else { 1 }140+		}141+		return kind_rank(a.kind) - kind_rank(b.kind)142+	})143+	return s.put_manifest(json2.encode(Manifest{144+		entries: entries145+	}))!146+}147+148+fn segment_at(path string, prefix string) string {149+	rest := path[prefix.len..]150+	slash := rest.index('/') or { -1 }151+	return if slash < 0 { rest } else { rest[..slash] }152+}153+154+fn kind_rank(kind string) int {155+	return if kind == file_kind { 0 } else { 1 }156+}157+158+// manifest_files flattens a tree back to sorted repo-relative paths.159+pub fn (s &Store) manifest_files(root string) ![]ManifestFile {160+	mut files := []ManifestFile{}161+	s.manifest_flatten(root, '', mut files, []string{})!162+	files.sort(a.path < b.path)163+	return files164+}165+166+fn (s &Store) manifest_flatten(hash string, prefix string, mut out []ManifestFile, ancestors []string) ! {167+	if hash in ancestors {168+		return error('manifest ${hash} refers to itself')169+	}170+	mut deeper := ancestors.clone()171+	deeper << hash172+	entries := s.manifest_entries(hash)!173+	for entry in entries {174+		if entry.kind == file_kind {175+			out << ManifestFile{176+				path:       prefix + entry.name177+				hash:       entry.hash178+				size:       entry.size179+				executable: entry.executable180+			}181+		} else {182+			s.manifest_flatten(entry.manifest, '${prefix}${entry.name}/', mut out, deeper)!183+		}184+	}185+}186+187+pub fn (s &Store) manifest_count() !i64 {188+	mut stmt := s.db.prepare('SELECT COUNT(*) FROM manifests')!189+	defer {190+		stmt.finalize()191+	}192+	if !stmt.step()! {193+		return 0194+	}195+	return stmt.int(0)196+}197+198+// manifest_bodies lists every stored body in hash order, for Doctor.199+pub fn (s &Store) manifest_bodies() ![]string {200+	mut stmt := s.db.prepare('SELECT body FROM manifests ORDER BY hash')!201+	defer {202+		stmt.finalize()203+	}204+	mut bodies := []string{}205+	for stmt.step()! {206+		bodies << stmt.text(0)207+	}208+	return bodies209+}210+211+// manifest_object_hashes is every object any stored manifest names, in one pass.212+// A damaged manifest is an error: with the reference set unknown, nothing may213+// conclude an object is unused.214+fn (s &Store) manifest_object_hashes() !map[string]bool {215+	mut used := map[string]bool{}216+	mut stmt := s.db.prepare('SELECT hash, body FROM manifests')!217+	defer {218+		stmt.finalize()219+	}220+	for stmt.step()! {221+		hash := stmt.text(0)222+		entries := decode_manifest(stmt.text(1)) or {223+			return error('manifest ${hash} is invalid: ${err.msg()}')224+		}225+		for entry in entries {226+			if entry.kind == file_kind {227+				used[entry.hash] = true228+			}229+		}230+	}231+	return used232+}233+234+// drop_unreachable_manifests removes folder rows no save's tree reaches. A235+// rewrite replaces the folders on one path and never mutates a row, so the236+// old ones would otherwise keep naming objects nothing uses.237+pub fn (s &Store) drop_unreachable_manifests() !i64 {238+	mut reachable := map[string]bool{}239+	mut roots := s.db.prepare('SELECT DISTINCT manifest FROM saves')!240+	for roots.step()! {241+		s.mark_manifest(roots.text(0), mut reachable)!242+	}243+	roots.finalize()244+	mut hashes := s.db.prepare('SELECT hash FROM manifests')!245+	mut stale := []string{}246+	for hashes.step()! {247+		hash := hashes.text(0)248+		if hash !in reachable {249+			stale << hash250+		}251+	}252+	hashes.finalize()253+	mut delete := s.db.prepare('DELETE FROM manifests WHERE hash = ?')!254+	defer {255+		delete.finalize()256+	}257+	mut dropped := i64(0)258+	for hash in stale {259+		delete.bind_text(1, hash)!260+		delete.step()!261+		delete.reset()262+		dropped += s.db.changes()263+	}264+	return dropped265+}266+267+fn (s &Store) mark_manifest(hash string, mut reachable map[string]bool) ! {268+	if hash in reachable {269+		return270+	}271+	reachable[hash] = true272+	entries := s.manifest_entries(hash)!273+	for entry in entries {274+		if entry.kind == folder_kind {275+			s.mark_manifest(entry.manifest, mut reachable)!276+		}277+	}278+}

view file

src/storage/manifest_test.v+221 −0
@@ -0,0 +1,221 @@1+//! Manifests: canonical bodies, folder sharing and the version-1 upgrade.2+3+module storage4+5+import os6+7+fn manifest_store(name string) !Store {8+	dir := os.join_path(os.temp_dir(), 'koh3_manifest_${os.getpid()}_${name}')9+	os.rmdir_all(dir) or {}10+	os.mkdir_all(dir)!11+	return create(dir)!12+}13+14+fn hex(letter string) string {15+	return letter.repeat(64)16+}17+18+fn file(path string, hash string, size i64, executable bool) ManifestFile {19+	return ManifestFile{20+		path:       path21+		hash:       hash22+		size:       size23+		executable: executable24+	}25+}26+27+fn test_a_nested_tree_round_trips_sorted() {28+	mut store := manifest_store('round_trip')!29+	defer {30+		store.close()31+		os.rmdir_all(store.root) or {}32+	}33+	tree := [34+		file('a.txt', hex('a'), 3, false),35+		file('bin/tool', hex('b'), 5, true),36+		file('src/lib/x.v', hex('c'), 7, false),37+		file('src/main.v', hex('d'), 11, false),38+	]39+	root := store.manifest_tree(tree)!40+	flat := store.manifest_files(root)!41+	assert flat.map(it.path) == tree.map(it.path)42+	assert flat.map(it.hash) == tree.map(it.hash)43+	assert flat.map(it.size) == tree.map(it.size)44+	assert flat.map(it.executable) == tree.map(it.executable)45+	assert store.manifest_count()! == 446+	empty := store.manifest_tree([]ManifestFile{})!47+	assert store.manifest_body(empty)! == '{"entries":[]}'48+	assert store.manifest_files(empty)!.len == 049+}50+51+fn test_two_trees_share_every_unaffected_folder() {52+	mut store := manifest_store('sharing')!53+	defer {54+		store.close()55+		os.rmdir_all(store.root) or {}56+	}57+	first := [58+		file('a/one.txt', hex('a'), 1, false),59+		file('a/two.txt', hex('b'), 2, false),60+		file('b/deep/x.txt', hex('c'), 3, false),61+		file('b/deep/y.txt', hex('d'), 4, false),62+	]63+	assert store.manifest_tree(first)!.len == 6464+	assert store.manifest_count()! == 465+	second := [66+		file('a/one.txt', hex('a'), 1, false),67+		file('a/two.txt', hex('b'), 2, false),68+		file('b/deep/x.txt', hex('e'), 5, false),69+		file('b/deep/y.txt', hex('d'), 4, false),70+	]71+	store.manifest_tree(second)!72+	// Only b/deep, b and the root are new; a is shared.73+	assert store.manifest_count()! == 774+}75+76+fn test_the_canonical_body_locks_field_order_and_hash() {77+	mut store := manifest_store('golden')!78+	defer {79+		store.close()80+		os.rmdir_all(store.root) or {}81+	}82+	tree := [83+		file('a.txt', hex('a'), 3, false),84+		file('src/x', hex('b'), 5, false),85+	]86+	root := store.manifest_tree(tree)!87+	src_body := '{"entries":[{"name":"x","kind":"file","hash":"${hex('b')}",' +88+		'"size":5,"executable":false,"manifest":""}]}'89+	src_hash := hash_hex(src_body.bytes())90+	want := '{"entries":[{"name":"a.txt","kind":"file","hash":"${hex('a')}",' +91+		'"size":3,"executable":false,"manifest":""},' +92+		'{"name":"src","kind":"folder","hash":"","size":0,"executable":false,' +93+		'"manifest":"${src_hash}"}]}'94+	assert store.manifest_body(root)! == want95+	assert root == hash_hex(want.bytes())96+	assert store.manifest_body(src_hash)! == src_body97+}98+99+fn test_a_version_one_file_upgrades_on_open() {100+	dir := os.join_path(os.temp_dir(), 'koh3_manifest_${os.getpid()}_upgrade')101+	os.rmdir_all(dir) or {}102+	os.mkdir_all(dir)!103+	defer {104+		os.rmdir_all(dir) or {}105+	}106+	path := os.join_path(dir, '.koh')107+	db := connect(path, busy_timeout_ms)!108+	db.exec_v1_for_test()!109+	db.close()110+	mut store := open_at(path, dir)!111+	defer {112+		store.close()113+	}114+	version := store.db.user_version()!115+	assert version == 2116+	mut stmt := store.db.prepare('SELECT manifest, message, parent, agent, size_bytes FROM saves')!117+	assert stmt.step()!118+	root := stmt.text(0)119+	assert stmt.text(1) == 'migrated'120+	assert stmt.text_or_none(2) or { '' } == ''121+	assert stmt.text_or_none(3) or { '' } == 'agent-one'122+	assert stmt.int(4) == 11123+	stmt.finalize()124+	flat := store.manifest_files(root)!125+	assert flat.map(it.path) == ['a.txt', 'src/x.v']126+	assert flat.map(it.hash) == [hex('a'), hex('b')]127+	assert flat.map(it.size) == [i64(3), i64(9)]128+	assert flat.map(it.executable) == [false, true]129+	mut tables := store.db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")!130+	mut names := []string{}131+	for tables.step()! {132+		names << tables.text(0)133+	}134+	tables.finalize()135+	assert 'manifests' in names136+	assert 'save_files' !in names137+}138+139+fn (db &Db) exec_v1_for_test() ! {140+	db.exec('141+CREATE TABLE objects (142+	hash TEXT PRIMARY KEY, size INTEGER NOT NULL, data BLOB NOT NULL143+);144+CREATE TABLE saves (145+	id TEXT PRIMARY KEY,146+	parent TEXT REFERENCES saves(id),147+	message TEXT NOT NULL,148+	created_at INTEGER NOT NULL,149+	machine TEXT NOT NULL,150+	is_checkpoint INTEGER NOT NULL DEFAULT 0,151+	size_bytes INTEGER NOT NULL DEFAULT 0,152+	agent TEXT, session TEXT, restores TEXT, replayed_from TEXT153+);154+CREATE TABLE save_files (155+	save_id TEXT NOT NULL REFERENCES saves(id),156+	path TEXT NOT NULL,157+	hash TEXT NOT NULL REFERENCES objects(hash),158+	executable INTEGER NOT NULL DEFAULT 0,159+	PRIMARY KEY (save_id, path)160+);161+CREATE TABLE events (162+	id TEXT PRIMARY KEY, kind TEXT NOT NULL, save_id TEXT, path TEXT,163+	reason TEXT, created_at INTEGER NOT NULL, machine TEXT NOT NULL164+);165+CREATE TABLE state (key TEXT PRIMARY KEY, value TEXT NOT NULL);166+CREATE TABLE file_cache (167+	path TEXT PRIMARY KEY, size INTEGER NOT NULL, mtime_ns INTEGER NOT NULL,168+	ctime_ns INTEGER NOT NULL, hash TEXT NOT NULL169+);170+CREATE INDEX saves_parent ON saves(parent);171+CREATE INDEX save_files_hash ON save_files(hash);172+PRAGMA user_version = 1;173+')!174+	mut object := db.prepare('INSERT INTO objects (hash, size, data) VALUES (?, ?, ?)')!175+	for hash, size in {176+		hex('a'): i64(3)177+		hex('b'): i64(9)178+	} {179+		object.bind_text(1, hash)!180+		object.bind_int(2, size)!181+		object.bind_blob(3, [u8(0)])!182+		object.step()!183+		object.reset()184+	}185+	object.finalize()186+	mut save := db.prepare('INSERT INTO saves (id, parent, message, created_at, machine,187+		size_bytes, agent) VALUES (?, NULL, ?, ?, ?, ?, ?)')!188+	save.bind_text(1, 'aaaaaaaaaaaa')!189+	save.bind_text(2, 'migrated')!190+	save.bind_int(3, 1700000000)!191+	save.bind_text(4, 'machine')!192+	save.bind_int(5, 11)!193+	save.bind_text(6, 'agent-one')!194+	save.step()!195+	save.finalize()196+	mut rows := db.prepare('INSERT INTO save_files (save_id, path, hash, executable)197+		VALUES (?, ?, ?, ?)')!198+	rows.bind_text(1, 'aaaaaaaaaaaa')!199+	rows.bind_text(2, 'src/x.v')!200+	rows.bind_text(3, hex('b'))!201+	rows.bind_int(4, 1)!202+	rows.step()!203+	rows.reset()204+	rows.bind_text(1, 'aaaaaaaaaaaa')!205+	rows.bind_text(2, 'a.txt')!206+	rows.bind_text(3, hex('a'))!207+	rows.bind_int(4, 0)!208+	rows.step()!209+	rows.finalize()210+}211+212+fn (db &Db) user_version() !i64 {213+	mut stmt := db.prepare('PRAGMA user_version')!214+	defer {215+		stmt.finalize()216+	}217+	if !stmt.step()! {218+		return 0219+	}220+	return stmt.int(0)221+}

view file

src/storage/objects.v+63 −16
@@ -157,15 +157,31 @@157157 	return stmt.int(0)158158 }159159 160-// drop_unreferenced_objects removes objects no save points at any more. Only160+// drop_unreferenced_objects removes objects no manifest names any more. Only161161 // `strip` leaves objects behind, so this is what makes a strip permanent.162162 pub fn (s &Store) drop_unreferenced_objects() !i64 {163163 	before := s.object_count()!164-	mut stmt := s.db.prepare('DELETE FROM objects WHERE hash NOT IN (SELECT hash FROM save_files)')!164+	used := s.manifest_object_hashes()!165+	mut stmt := s.db.prepare('DELETE FROM objects WHERE hash = ?')!165166 	defer {166167 		stmt.finalize()167168 	}168-	stmt.step()!169+	mut hashes := s.db.prepare('SELECT hash FROM objects')!170+	defer {171+		hashes.finalize()172+	}173+	mut stale := []string{}174+	for hashes.step()! {175+		hash := hashes.text(0)176+		if hash !in used {177+			stale << hash178+		}179+	}180+	for hash in stale {181+		stmt.bind_text(1, hash)!182+		stmt.step()!183+		stmt.reset()184+	}169185 	after := s.object_count()!170186 	return before - after171187 }@@ -176,21 +192,24 @@176192 	return hash.len == 64 && hash.bytes().all((it >= `0` && it <= `9`) || (it >= `a` && it <= `f`))177193 }178194 179-// drop_unused removes those of `hashes` no save points at any more. Other195+// drop_unused removes those of `hashes` no stored manifest names any more. Other180196 // unused objects stay: with damaged rows one may be the only copy of saved181197 // content, and Doctor offers their removal separately.182198 pub fn (s &Store) drop_unused(hashes []string) !i64 {183-	mut stmt := s.db.prepare('DELETE FROM objects WHERE hash = ?1184-		AND NOT EXISTS (SELECT 1 FROM save_files WHERE hash = ?1)')!199+	used := s.manifest_object_hashes()!200+	mut stmt := s.db.prepare('DELETE FROM objects WHERE hash = ?')!185201 	defer {186202 		stmt.finalize()187203 	}188204 	mut dropped := i64(0)189205 	for hash in hashes {190-		stmt.reset()206+		if hash in used {207+			continue208+		}191209 		stmt.bind_text(1, hash)!192210 		stmt.step()!193211 		dropped += s.db.changes()212+		stmt.reset()194213 	}195214 	return dropped196215 }@@ -225,16 +244,31 @@225244 	return problems226245 }227246 228-/// Find missing objects, including damage from writes with foreign keys disabled.247+/// Find missing objects, walking every distinct manifest. Damage from writes248+/// with foreign keys disabled names the manifest that refers to the gap.229249 pub fn (s &Store) check_save_files() ![]ObjectProblem {230250 	mut problems := []ObjectProblem{}231-	mut stmt := s.db.prepare('SELECT DISTINCT f.save_id, f.hash FROM save_files f232-		LEFT JOIN objects o ON o.hash = f.hash WHERE o.hash IS NULL')!251+	mut stmt := s.db.prepare('SELECT hash, body FROM manifests ORDER BY hash')!233252 	defer {234253 		stmt.finalize()235254 	}255+	mut seen := map[string]bool{}236256 	for stmt.step()! {237-		problems << ObjectProblem{stmt.text(1), 'save ${stmt.text(0)} needs missing object ${stmt.text(1)}'}257+		manifest := stmt.text(0)258+		entries := decode_manifest(stmt.text(1)) or { continue }259+		for entry in entries {260+			if entry.kind != file_kind {261+				continue262+			}263+			key := '${manifest} ${entry.hash}'264+			if key in seen {265+				continue266+			}267+			seen[key] = true268+			if !s.has_object(entry.hash)! {269+				problems << ObjectProblem{entry.hash, 'manifest ${manifest} needs missing object ${entry.hash}'}270+			}271+		}238272 	}239273 	return problems240274 }@@ -259,14 +293,27 @@259293 260294 /// Saved paths whose content is `hash`, where a working copy may still exist.261295 pub fn (s &Store) paths_of_object(hash string) ![]string {262-	mut stmt := s.db.prepare('SELECT DISTINCT path FROM save_files WHERE hash = ?')!296+	mut stmt := s.db.prepare('SELECT DISTINCT manifest FROM saves')!263297 	defer {264298 		stmt.finalize()265299 	}266-	stmt.bind_text(1, hash)!267-	mut paths := []string{}300+	mut roots := []string{}268301 	for stmt.step()! {269-		paths << stmt.text(0)302+		roots << stmt.text(0)270303 	}271-	return paths304+	mut memo := map[string][]ManifestFile{}305+	mut paths := map[string]bool{}306+	for root in roots {307+		if root !in memo {308+			memo[root] = s.manifest_files(root)!309+		}310+		for file in memo[root] {311+			if file.hash == hash {312+				paths[file.path] = true313+			}314+		}315+	}316+	mut out := paths.keys()317+	out.sort()318+	return out272319 }

view file

src/storage/storage.v+137 −19
@@ -8,22 +8,24 @@88 99 import os1010 11-pub const schema_version = 111+pub const schema_version = 21212 pub const file_name = '.koh'1313 pub const busy_timeout_ms = 50001414 15-// Every fact Koh knows lives in these six tables. `state` and `file_cache` are16-// machine-local: they are never synced and may be dropped at any time.17-const schema = '18-CREATE TABLE objects (19-	hash       TEXT PRIMARY KEY,20-	size       INTEGER NOT NULL,21-	data       BLOB NOT NULL22-);15+// One save's file list is a tree of folder manifests, each named by the hash16+// of its canonical body, so identical folders are stored and shared once.17+const manifests_table = '18+CREATE TABLE manifests (19+	hash TEXT PRIMARY KEY,20+	body TEXT NOT NULL21+) WITHOUT ROWID;22+'2323 24+const saves_table = '2425 CREATE TABLE saves (2526 	id            TEXT PRIMARY KEY,2627 	parent        TEXT REFERENCES saves(id),28+	manifest      TEXT NOT NULL REFERENCES manifests(hash),2729 	message       TEXT NOT NULL,2830 	created_at    INTEGER NOT NULL,2931 	machine       TEXT NOT NULL,@@ -34,15 +36,17 @@3436 	restores      TEXT,3537 	replayed_from TEXT3638 );39+'3740 38-CREATE TABLE save_files (39-	save_id    TEXT NOT NULL REFERENCES saves(id),40-	path       TEXT NOT NULL,41-	hash       TEXT NOT NULL REFERENCES objects(hash),42-	executable INTEGER NOT NULL DEFAULT 0,43-	PRIMARY KEY (save_id, path)41+// Every fact Koh knows lives in these six tables. `state` and `file_cache` are42+// machine-local: they are never synced and may be dropped at any time.43+const schema = '44+CREATE TABLE objects (45+	hash       TEXT PRIMARY KEY,46+	size       INTEGER NOT NULL,47+	data       BLOB NOT NULL4448 );45-49+' + manifests_table + saves_table + '4650 CREATE TABLE events (4751 	id         TEXT PRIMARY KEY,4852 	kind       TEXT NOT NULL,@@ -67,7 +71,6 @@6771 );6872 6973 CREATE INDEX saves_parent ON saves(parent);70-CREATE INDEX save_files_hash ON save_files(hash);7174 '7275 7376 pub const head_key = 'head'@@ -157,8 +160,123 @@157160 	if version > schema_version {158161 		return error('this .koh was written by a newer koh (schema ${version}, this build knows ${schema_version})')159162 	}160-	if version < schema_version {161-		return error('this .koh needs an upgrade koh does not know how to do (schema ${version})')163+	if version == schema_version {164+		return165+	}166+	if version == 1 {167+		return upgrade_1_to_2(db)168+	}169+	return error('this .koh needs an upgrade koh does not know how to do (schema ${version})')170+}171+172+// upgrade_1_to_2 turns `save_files` into per-folder manifests. Foreign keys173+// cannot change inside a transaction, so they are off around it; a failure174+// rolls back and leaves the version-1 file as it was.175+fn upgrade_1_to_2(db &Db) ! {176+	db.exec('PRAGMA foreign_keys=OFF')!177+	db.exec('BEGIN IMMEDIATE')!178+	upgrade_steps(db) or {179+		db.exec('ROLLBACK') or {}180+		db.exec('PRAGMA foreign_keys=ON') or {}181+		return err182+	}183+	db.exec('COMMIT')!184+	db.exec('PRAGMA foreign_keys=ON')!185+}186+187+struct V1Save {188+	id            string189+	parent        string190+	message       string191+	created_at    i64192+	machine       string193+	is_checkpoint bool194+	size_bytes    i64195+	agent         string196+	session       string197+	restores      string198+	replayed_from string199+}200+201+fn upgrade_steps(db &Db) ! {202+	store := Store{203+		db: db204+	}205+	db.exec(manifests_table)!206+	db.exec('ALTER TABLE saves RENAME TO saves_v1')!207+	db.exec('DROP INDEX IF EXISTS saves_parent')!208+	db.exec(saves_table)!209+	db.exec('CREATE INDEX saves_parent ON saves(parent)')!210+	mut saves := []V1Save{}211+	mut old := db.prepare('SELECT id, parent, message, created_at, machine, is_checkpoint, size_bytes,212+		agent, session, restores, replayed_from FROM saves_v1 ORDER BY id')!213+	for old.step()! {214+		saves << V1Save{215+			id:            old.text(0)216+			parent:        old.text_or_none(1) or { '' }217+			message:       old.text(2)218+			created_at:    old.int(3)219+			machine:       old.text(4)220+			is_checkpoint: old.int(5) != 0221+			size_bytes:    old.int(6)222+			agent:         old.text_or_none(7) or { '' }223+			session:       old.text_or_none(8) or { '' }224+			restores:      old.text_or_none(9) or { '' }225+			replayed_from: old.text_or_none(10) or { '' }226+		}227+	}228+	old.finalize()229+	mut files := db.prepare('SELECT path, hash, executable,230+		COALESCE((SELECT size FROM objects WHERE objects.hash = save_files.hash), 0)231+		FROM save_files WHERE save_id = ? ORDER BY path')!232+	defer {233+		files.finalize()234+	}235+	mut insert := db.prepare('INSERT INTO saves (id, parent, manifest, message, created_at, machine,236+		is_checkpoint, size_bytes, agent, session, restores, replayed_from)237+		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')!238+	defer {239+		insert.finalize()240+	}241+	for save in saves {242+		mut rows := []ManifestFile{}243+		files.bind_text(1, save.id)!244+		for files.step()! {245+			rows << ManifestFile{246+				path:       files.text(0)247+				hash:       files.text(1)248+				size:       files.int(3)249+				executable: files.int(2) != 0250+			}251+		}252+		files.reset()253+		root := store.manifest_tree(rows)!254+		insert.bind_text(1, save.id)!255+		bind_optional(insert, 2, save.parent)!256+		insert.bind_text(3, root)!257+		insert.bind_text(4, save.message)!258+		insert.bind_int(5, save.created_at)!259+		insert.bind_text(6, save.machine)!260+		insert.bind_int(7, if save.is_checkpoint { 1 } else { 0 })!261+		insert.bind_int(8, save.size_bytes)!262+		bind_optional(insert, 9, save.agent)!263+		bind_optional(insert, 10, save.session)!264+		bind_optional(insert, 11, save.restores)!265+		bind_optional(insert, 12, save.replayed_from)!266+		insert.step()!267+		insert.reset()268+	}269+	db.exec('DROP TABLE save_files')!270+	db.exec('DROP TABLE saves_v1')!271+	db.exec('PRAGMA user_version = ${schema_version}')!272+}273+274+// bind_optional writes NULL for an absent text, as the save columns expect.275+fn bind_optional(stmt &Stmt, index int, value string) ! {276+	if value == '' {277+		stmt.bind_null(index)!278+	} else {279+		stmt.bind_text(index, value)!162280 	}163281 }164282 

view file

src/update/update.v+9 −0
@@ -10,6 +10,7 @@1010 import crypto.blake31111 import json21212 import net.http13+import net.urllib1314 import os1415 import src.remote1516 @@ -64,6 +65,14 @@6465 // do" is not one of them, so it is a field, not a failed call.6566 pub fn check(now string, platform string) !Checked {6667 	url := source()68+	// The document supplies both the download address and its hash, so a plain-http source would69+	// let anyone on the path replace both. Localhost is the one exception, for a mirror on this machine.70+	parsed := urllib.parse(url) or { return error('${url} is not an address') }71+	if parsed.scheme != 'https'72+		&& !(parsed.scheme == 'http' && parsed.hostname().to_lower() in ['127.0.0.1', 'localhost',73+			'::1']) {74+		return error('koh update needs https — plain http is only for a source on this machine')75+	}6776 	response := http.fetch(6877 		url:          url6978 		validate:     true

view file

src/view/term.v+21 −0
@@ -18,6 +18,8 @@1818 1919 fn C.koh_read_key(buf &char, cap int) int2020 21+fn C.koh_wait_key(buf &char, cap int, milliseconds int) int22+2123 pub enum KeyKind {2224 	rune2325 	up@@ -71,6 +73,25 @@7173 		}7274 	}7375 	return decode(buf[..n])76+}77+78+// read_key_timeout waits up to `milliseconds` for a keystroke. `timed_out` is79+// true when nothing arrived, which is the view's cue to check whether the80+// window changed size; a key decodes exactly as read_key decodes it.81+pub fn read_key_timeout(milliseconds int) (Key, bool) {82+	mut buf := []u8{len: 16}83+	n := C.koh_wait_key(unsafe { &char(buf.data) }, buf.len, milliseconds)84+	if n == 0 {85+		return Key{86+			kind: .unknown87+		}, true88+	}89+	if n < 0 {90+		return Key{91+			kind: .eof92+		}, false93+	}94+	return decode(buf[..n]), false7495 }7596 7697 // decode is a key table: one case per byte or escape sequence, nothing carried between reads.

view file

src/view/view.v+32 −12
@@ -105,6 +105,10 @@105105 		}106106 		stale:  true107107 	}108+	// A resize arrives as no key at all, so the loop waits for one only so109+	// long and then looks at the window size instead of blocking on stdin.110+	wait_ms := 250111+	mut dirty := true108112 	for {109113 		if session.stale {110114 			// A load appends a save and a flag changes a mark: read both again.@@ -115,26 +119,42 @@115119 			session.screen.counts = count_tabs(every, session.screen.on_line)116120 			session.detail_for = ''117121 			session.stale = false122+			dirty = true118123 		}119-		session.screen.rows, session.screen.cols = terminal_size()120-		session.screen.items = filter_saves(every, session.screen.tab, session.screen.on_line,121-			session.screen.query)122-		session.screen.selected = move_selection(session.screen.selected, 0, session.screen.items.len)123-		if session.mode in [.detail, .reason, .confirm] && session.detail_for != session.target.id {124-			session.detail = detail_lines(session.target, session.screen.head, diff_of(store,125-				session.target), session.screen.flags[session.target.id] or { events.Flag{} })126-			session.detail_for = session.target.id124+		if dirty {125+			session.screen.rows, session.screen.cols = terminal_size()126+			session.screen.items = filter_saves(every, session.screen.tab, session.screen.on_line,127+				session.screen.query)128+			session.screen.selected = move_selection(session.screen.selected, 0,129+				session.screen.items.len)130+			if session.mode in [.detail, .reason, .confirm]131+				&& session.detail_for != session.target.id {132+				session.detail = detail_lines(session.target, session.screen.head, diff_of(store,133+					session.target), session.screen.flags[session.target.id] or { events.Flag{} })134+				session.detail_for = session.target.id135+			}136+			paint(render(frame_lines(session)))137+			// A status message is shown for one frame, as in Koh 2.138+			session.screen.status = ''139+			dirty = false127140 		}128-		paint(render(frame_lines(session)))129-		// A status message is shown for one frame, as in Koh 2.130-		session.screen.status = ''131-		key := read_key()141+		key, timed_out := read_key_timeout(wait_ms)142+		if timed_out {143+			// Repaint only when the size moved: an idle view must not redraw144+			// four times a second for nothing.145+			rows, cols := terminal_size()146+			if rows != session.screen.rows || cols != session.screen.cols {147+				dirty = true148+			}149+			continue150+		}132151 		if key.kind in [.interrupt, .eof] {133152 			return134153 		}135154 		if handle_key(mut session, store, key, act) {136155 			return137156 		}157+		dirty = true138158 	}139159 }140160 

view file

tests/cli_test.v+19 −9
@@ -5,6 +5,7 @@55 import os66 import time77 import src.exchange8+import src.history89 import src.storage910 1011 const root = @VMODROOT@@ -116,6 +117,17 @@116117 	os.write_file(full, text) or { panic(err) }117118 }118119 120+// count_saved_path counts the saves whose manifest tree still holds `path`.121+fn count_saved_path(store &storage.Store, path string) !int {122+	mut found := 0123+	for save in history.all_saves(store)! {124+		if history.files_of(store, save.id)!.any(it.path == path) {125+			found++126+		}127+	}128+	return found129+}130+119131 fn read_json_has(text string, key string) {120132 	if !text.contains(key) {121133 		panic('missing JSON key ${key}: ${text}')@@ -1995,7 +2007,11 @@19952007 	write(repo, 'secret', 'secret')19962008 	assert run_home(repo, home, 'save', 'legacy').code == 019972009 	store := storage.open(repo)!1998-	store.db.exec("UPDATE save_files SET path = '../unsafe' WHERE path = 'secret'")!2010+	unsafe_hash := storage.hash_hex('secret'.bytes())2011+	body := '{"entries":[{"name":"../unsafe","kind":"file","hash":"${unsafe_hash}","size":6,"executable":false,"manifest":""}]}'2012+	manifest := storage.hash_hex(body.bytes())2013+	store.db.exec("INSERT INTO manifests (hash, body) VALUES ('${manifest}', '${body}')")!2014+	store.db.exec("UPDATE saves SET manifest = '${manifest}'")!19992015 	store.close()20002016 	legacy := run_pty_home(repo, home, ['y', '../unsafe'], 'strip', '../unsafe')20012017 	assert legacy.code == 0, legacy.out@@ -2095,17 +2111,11 @@20952111 	assert run_pty_home(b, home, [''], 'steal').code == 120962112 	assert run_home(b, home, 'view', '--json').out == before20972113 	store := storage.open(b)!2098-	held := store.db.prepare("SELECT COUNT(*) FROM save_files WHERE path = 'secret.txt'")!2099-	assert held.step()!2100-	assert held.int(0) > 02101-	held.finalize()2114+	assert count_saved_path(store, 'secret.txt')! > 021022115 	store.close()21032116 	assert run_home(b, home, 'steal', '--yes').code == 021042117 	checked := storage.open(b)!2105-	removed := checked.db.prepare("SELECT COUNT(*) FROM save_files WHERE path = 'secret.txt'")!2106-	assert removed.step()!2107-	assert removed.int(0) == 02108-	removed.finalize()2118+	assert count_saved_path(checked, 'secret.txt')! == 021092119 	checked.close()21102120 }21112121 

view file

vendor/shim/koh_term.c+80 −2
@@ -1,6 +1,8 @@11 #include "koh_term.h"22 3+#include <errno.h>34 #include <poll.h>5+#include <signal.h>46 #include <stdio.h>57 #include <sys/ioctl.h>68 #include <termios.h>@@ -9,6 +11,48 @@911 static struct termios koh_saved;1012 static int koh_have_saved = 0;1113 14+/* A kill cannot run the caller's cleanup, so raw mode installs its own exit:15+ * restore the terminal, leave the alternate screen, and die with the signal16+ * encoded in the status the shell expects. The previous handlers go back when17+ * raw mode ends so the rest of the process sees the default disposition. */18+static const int koh_fatal_signals[] = { SIGTERM, SIGHUP, SIGQUIT };19+#define KOH_FATAL_COUNT 320+21+static struct sigaction koh_prev_handlers[KOH_FATAL_COUNT];22+static int koh_handler_count = 0;23+24+static void koh_leave_on_signal(int sig) {25+	if (koh_have_saved) {26+		tcsetattr(STDIN_FILENO, TCSAFLUSH, &koh_saved);27+	}28+	static const char leave[] = "\x1b[?25h\x1b[?1049l";29+	ssize_t ignored = write(STDOUT_FILENO, leave, sizeof(leave) - 1);30+	(void)ignored;31+	_exit(128 + sig);32+}33+34+static void koh_install_handlers(void) {35+	if (koh_handler_count > 0) {36+		return;37+	}38+	struct sigaction action = { .sa_handler = koh_leave_on_signal };39+	sigemptyset(&action.sa_mask);40+	action.sa_flags = 0;41+	for (int i = 0; i < KOH_FATAL_COUNT; i++) {42+		if (sigaction(koh_fatal_signals[i], &action, &koh_prev_handlers[i]) != 0) {43+			break;44+		}45+		koh_handler_count = i + 1;46+	}47+}48+49+static void koh_restore_handlers(void) {50+	for (int i = 0; i < koh_handler_count; i++) {51+		sigaction(koh_fatal_signals[i], &koh_prev_handlers[i], NULL);52+	}53+	koh_handler_count = 0;54+}55+1256 int koh_term_raw(int enable) {1357 	if (enable) {1458 		if (!isatty(STDIN_FILENO)) {@@ -25,12 +69,18 @@2569 		raw.c_iflag &= (tcflag_t) ~(IXON | ICRNL | BRKINT | INPCK | ISTRIP);2670 		raw.c_cc[VMIN] = 1;2771 		raw.c_cc[VTIME] = 0;28-		return tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == 0;72+		if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) != 0) {73+			koh_have_saved = 0;74+			return 0;75+		}76+		koh_install_handlers();77+		return 1;2978 	}3079 	if (koh_have_saved) {3180 		tcsetattr(STDIN_FILENO, TCSAFLUSH, &koh_saved);3281 		koh_have_saved = 0;3382 	}83+	koh_restore_handlers();3484 	return 1;3585 }3686 @@ -54,7 +104,9 @@54104 	return poll(&p, 1, milliseconds) > 0;55105 }56106 57-int koh_read_key(char *buf, int cap) {107+/* One keystroke, blocking if there is none yet. Both koh_read_key and108+ * koh_wait_key go through here so a key means the same thing either way. */109+static int koh_read_one(char *buf, int cap) {58110 	if (cap <= 0) {59111 		return 0;60112 	}@@ -99,4 +151,30 @@99151 		remaining--;100152 	}101153 	return total;154+}155+156+int koh_read_key(char *buf, int cap) {157+	return koh_read_one(buf, cap);158+}159+160+int koh_wait_key(char *buf, int cap, int milliseconds) {161+	if (cap <= 0) {162+		return 0;163+	}164+	struct pollfd p;165+	p.fd = STDIN_FILENO;166+	p.events = POLLIN;167+	p.revents = 0;168+	int ready;169+	do {170+		ready = poll(&p, 1, milliseconds);171+	} while (ready < 0 && errno == EINTR);172+	if (ready <= 0) {173+		return 0;174+	}175+	int n = koh_read_one(buf, cap);176+	/* A key reader that returns nothing after poll said readable means the177+	 * input is gone, not quiet: report it apart so the caller quits instead178+	 * of waiting forever on a dead stdin. */179+	return n == 0 ? -1 : n;102180 }

view file

vendor/shim/koh_term.h+8 −1
@@ -12,7 +12,9 @@1212 1313 /* Switches stdin to raw mode (enable = 1) or back (enable = 0). Returns 1 on1414  * success. Ctrl-C is delivered as a key rather than a signal, so the caller15- * can restore the terminal before quitting. */15+ * can restore the terminal before quitting. While raw mode is on, SIGTERM,16+ * SIGHUP and SIGQUIT restore the terminal and exit; turning raw mode off puts17+ * the previous handlers back. */1618 int koh_term_raw(int enable);1719 1820 /* Fills rows and columns; falls back to 24x80 when the size is unavailable. */@@ -21,5 +23,10 @@2123 /* Reads one keystroke into buf, gathering the rest of an escape sequence when2224  * the first byte is ESC. Returns the byte count, or 0 at end of input. */2325 int koh_read_key(char *buf, int cap);26+27+/* Waits up to milliseconds for a keystroke, then reads it exactly as28+ * koh_read_key does. Returns the byte count, 0 when no key arrived in time, or29+ * -1 when input ended. */30+int koh_wait_key(char *buf, int cap, int milliseconds);2431 2532 #endif

view file