cli_test.v

36.5 KB · raw

1module tests23import os4import time56const root = @VMODROOT7const binary = os.join_path(root, 'build', 'koh3')89struct Result {10mut:11	code int12	out  string13	err  string14}1516fn testsuite_begin() {17	os.mkdir_all(os.join_path(root, 'build')) or { panic(err) }18	build := os.execute('v -o ${q(binary)} ${q(os.join_path(root, 'src', 'koh3.v'))}')19	if build.exit_code != 0 {20		panic('could not build koh3: ${build.output}')21	}22}2324fn q(s string) string {25	return "'${s.replace("'", "'\\''")}'"26}2728fn temp_repo(name string) string {29	dir := os.join_path(os.temp_dir(), 'koh3-cli-${name}-${time.now().unix_nano()}')30	os.mkdir_all(dir) or { panic(err) }31	return dir32}3334fn run(repo string, args ...string) Result {35	home := temp_repo('home')36	defer { os.rmdir_all(home) or {} }37	return run_home(repo, home, ...args)38}3940fn run_home(repo string, home string, args ...string) Result {41	stamp := '${os.getpid()}-${time.now().unix_nano()}'42	base := os.join_path(os.temp_dir(), 'koh3-cli-${stamp}')43	out_path := '${base}.out'44	err_path := '${base}.err'45	code_path := '${base}.code'46	mut command := 'HOME=${q(home)} ${q(binary)}'47	for arg in args {48		command += ' ${q(arg)}'49	}50	shell := 'cd ${q(repo)} && ${command} </dev/null >${q(out_path)} 2>${q(err_path)}; printf "%s" $? >${q(code_path)}'51	result := os.execute(shell)52	if result.exit_code != 0 {53		panic('could not run test command: ${result.output}')54	}55	code := os.read_file(code_path) or { panic(err) }56	out := os.read_file(out_path) or { '' }57	err := os.read_file(err_path) or { '' }58	os.rm(out_path) or {}59	os.rm(err_path) or {}60	os.rm(code_path) or {}61	return Result{62		code: code.int()63		out:  out64		err:  err65	}66}6768fn init_repo(repo string) {69	r := run(repo, 'init')70	assert r.code == 071	assert os.exists(os.join_path(repo, '.koh'))72	assert os.exists(os.join_path(repo, '.kohignore'))73}7475fn write(repo string, path string, text string) {76	full := os.join_path(repo, path)77	os.mkdir_all(os.dir(full)) or { panic(err) }78	os.write_file(full, text) or { panic(err) }79}8081fn read_json_has(text string, key string) {82	if !text.contains(key) {83		panic('missing JSON key ${key}: ${text}')84	}85}8687fn test_init_and_usage() {88	dir := temp_repo('init')89	defer { os.rmdir_all(dir) or {} }90	r := run(dir, 'init', '--json')91	assert r.code == 092	read_json_has(r.out, 'repo')93	read_json_has(r.out, 'ignore_created')94	assert run(dir, 'init').code == 195	assert run(dir, 'unknown-command').code == 296	assert run(dir, 'unknown-command').err.contains('unknown command')97	// An agent asking for JSON gets JSON for a usage mistake too, exit 2.98	for args in [['unknown-command', '--json'], ['save', '--json'],99		['save', 'x', '--nope', '--json']] {100		r2 := run(dir, ...args)101		assert r2.code == 2102		assert r2.out == ''103		assert r2.err.starts_with('{"error":'), r2.err104	}105}106107fn test_save_checkpoint_and_status() {108	dir := temp_repo('save')109	defer { os.rmdir_all(dir) or {} }110	init_repo(dir)111	write(dir, 'tracked.txt', 'one\n')112	r := run(dir, 'save', 'first message', '--agent', 'agent-7', '--session', 'session-a', '--json')113	assert r.code == 0114	for key in ['id', 'parent', 'message', 'created_at', 'machine', 'is_checkpoint', 'agent',115		'session', 'files', 'size_bytes'] {116		read_json_has(r.out, key)117	}118	assert r.out.contains('"message":"first message"')119	assert r.out.contains('"agent":"agent-7"')120	assert r.out.contains('"session":"session-a"')121	assert r.out.contains('"is_checkpoint":false')122	assert run(dir, 'save', 'again').code == 1123	assert run(dir, 'save', 'again').err.contains('nothing has changed since the last save')124	assert run(dir, 'save').code == 2125	assert run(dir, 'save', 'x', '--bogus').code == 2126	cp := run(dir, 'checkpoint', 'still first', '--json')127	assert cp.code == 0128	assert cp.out.contains('"is_checkpoint":true')129	assert cp.out.contains('"parent":')130	clean := run(dir, 'status')131	assert clean.code == 0132	assert clean.out.contains('no changes')133	write(dir, 'tracked.txt', 'two\n')134	write(dir, 'new.txt', 'new\n')135	os.rm(os.join_path(dir, 'tracked.txt')) or { panic(err) }136	write(dir, '.kohignore', '*.log\n')137	status := run(dir, 'status')138	assert status.code == 0139	assert status.out.contains('+')140	assert status.out.contains('~') || status.out.contains('-')141	assert status.out.contains('added')142	js := run(dir, 'status', '--json')143	assert js.code == 0144	for key in ['head_id', 'head_msg', 'dirty', 'modified', 'added', 'deleted', 'ignore_changed'] {145		read_json_has(js.out, key)146	}147	assert js.out.contains('"ignore_changed":true')148}149150fn test_status_requires_repo_and_ignore_rules() {151	dir := temp_repo('status')152	defer { os.rmdir_all(dir) or {} }153	assert run(dir, 'status').code == 1154	init_repo(dir)155	write(dir, '.kohignore', '*.log\nbuild/\n')156	write(dir, 'keep.txt', 'keep\n')157	write(dir, 'ignored.log', 'ignore\n')158	write(dir, 'build/output.txt', 'ignore\n')159	assert run(dir, 'save', 'keep').code == 0160	assert run(dir, 'status').out.contains('no changes')161	assert !run(dir, 'status').out.contains('ignored.log')162	assert !run(dir, 'status').out.contains('build/output.txt')163	assert !run(dir, 'status').out.contains('LOG.md')164}165166// LOG.md is a convenience written after the save commits. If it cannot be167// written, the save still happened, and an agent that retried on a failure168// would only be told nothing had changed.169fn test_a_save_succeeds_when_log_md_cannot_be_written() {170	dir := temp_repo('logmd')171	defer { os.rmdir_all(dir) or {} }172	init_repo(dir)173	os.mkdir_all(os.join_path(dir, 'LOG.md')) or { panic(err) }174	write(dir, 'a.txt', 'one\n')175	r := run(dir, 'save', 'first', '--json')176	assert r.code == 0177	assert r.out.starts_with('{')178	assert r.err.contains('LOG.md')179	assert run(dir, 'log', '--json').out.contains('"message":"first"')180}181182// A folder of ignored files can sit where a restored file should go. Koh183// never touches ignored files, so the restore must stop and say so, not drop184// the file inside the folder under a temporary name.185fn test_a_restore_refuses_a_folder_of_ignored_files_in_the_way() {186	dir := temp_repo('dir-in-way')187	defer { os.rmdir_all(dir) or {} }188	init_repo(dir)189	write(dir, 'out', 'a file\n')190	first := run(dir, 'save', 'out is a file', '--json').out.all_after('"id":"')[..12]191	os.rm(os.join_path(dir, 'out')) or { panic(err) }192	write(dir, 'out/build.log', 'ignored\n')193	assert run(dir, 'save', 'out is gone').code == 0194	r := run(dir, 'load', first, '--yes')195	assert r.code == 1196	assert r.err.contains('out')197	assert os.ls(os.join_path(dir, 'out'))! == ['build.log']198}199200// Koh never follows a symlink, so a folder replaced by a link to somewhere201// else is not the repo's to write into: restoring through it would overwrite202// files outside the repo. The refusal comes before anything is recorded.203fn test_a_restore_never_writes_through_a_symlinked_folder() {204	dir := temp_repo('link-in-way')205	outside := temp_repo('link-target')206	defer {207		os.rmdir_all(dir) or {}208		os.rmdir_all(outside) or {}209	}210	init_repo(dir)211	write(dir, 'docs/a.md', 'saved\n')212	first := run(dir, 'save', 'docs', '--json').out.all_after('"id":"')[..12]213	os.rmdir_all(os.join_path(dir, 'docs')) or { panic(err) }214	write(outside, 'a.md', 'precious\n')215	os.symlink(outside, os.join_path(dir, 'docs')) or { panic(err) }216	assert run(dir, 'save', 'docs is a link now').code == 0217	head := run(dir, 'status', '--json').out218	r := run(dir, 'load', first, '--yes')219	assert r.code == 1220	assert r.err.contains('docs')221	assert os.read_file(os.join_path(outside, 'a.md'))! == 'precious\n'222	assert run(dir, 'status', '--json').out == head223}224225// A restore records its save first, then writes files. When the writing stops226// part way, the half-written tree is not somebody's work: saving it would227// record (and offer) a tree that undoes changes nobody asked to undo. Every228// command that would build on it points at revert, which finishes the job.229fn test_a_restore_cut_short_points_at_revert() {230	dir := temp_repo('cut-short')231	defer {232		os.chmod(os.join_path(dir, 'zz'), 0o755) or {}233		os.rmdir_all(dir) or {}234	}235	init_repo(dir)236	write(dir, 'zero', '0\n')237	assert run(dir, 'save', 'zero').code == 0238	write(dir, 'a.txt', 'v1\n')239	write(dir, 'zz/f', 'v1\n')240	assert run(dir, 'save', 'first').code == 0241	write(dir, 'a.txt', 'v2\n')242	write(dir, 'zz/f', 'v2\n')243	assert run(dir, 'save', 'second').code == 0244	// a.txt is written, then the read-only folder stops the restore: the245	// tree is genuinely half one save and half the other.246	os.chmod(os.join_path(dir, 'zz'), 0o555)!247	stopped := run(dir, 'undo', '--yes')248	assert stopped.code == 1249	assert stopped.err.contains('koh revert')250	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'v1\n'251	assert os.read_file(os.join_path(dir, 'zz/f'))! == 'v2\n'252	// Even a status that cannot read the tree says what happened.253	os.chmod(os.join_path(dir, 'zz'), 0o000)!254	assert run(dir, 'status').err.contains('koh revert')255	os.chmod(os.join_path(dir, 'zz'), 0o755)!256257	assert run(dir, 'status', '--json').out.contains('"restore_unfinished":true')258	for args in [['save', 'half'], ['checkpoint', 'half'], ['undo', '--yes']] {259		r := run(dir, ...args)260		assert r.code == 1261		assert r.err.contains('koh revert')262	}263	assert run(dir, 'revert', '--yes').code == 0264	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'v1\n'265	assert os.read_file(os.join_path(dir, 'zz/f'))! == 'v1\n'266	assert run(dir, 'status', '--json').out.contains('"restore_unfinished":false')267	write(dir, 'a.txt', 'v3\n')268	assert run(dir, 'save', 'carry on').code == 0269}270271// Doctor clears peek folders left from earlier days, never one somebody may272// be reading right now.273fn test_doctor_sweeps_only_old_peek_folders() {274	dir := temp_repo('peek-sweep')275	// V's temp_dir is /tmp on macOS whatever TMPDIR says, so these live in276	// the real temp directory under names no save could have.277	fresh := os.join_path(os.temp_dir(), 'koh-peek-fresh${os.getpid()}')278	old := os.join_path(os.temp_dir(), 'koh-peek-old${os.getpid()}')279	defer {280		os.rmdir_all(dir) or {}281		os.rmdir_all(fresh) or {}282		os.rmdir_all(old) or {}283	}284	init_repo(dir)285	write(dir, 'a.txt', 'one\n')286	assert run(dir, 'save', 'one').code == 0287	os.mkdir_all(fresh) or { panic(err) }288	os.mkdir_all(old) or { panic(err) }289	two_days_ago := time.now().unix() - 2 * 86400290	os.utime(old, two_days_ago, two_days_ago) or { panic(err) }291	assert run(dir, 'doctor', '--json').code == 0292	assert os.exists(fresh)293	assert !os.exists(old)294}295296// A file saved long ago and ignored since holds work no save has. Loading the297// old save must not write over it; the document says a restore never touches298// ignored files.299fn test_a_restore_never_overwrites_an_ignored_file() {300	dir := temp_repo('ignored-restore')301	defer { os.rmdir_all(dir) or {} }302	init_repo(dir)303	write(dir, '.env', 'KEY=saved long ago\n')304	first := run(dir, 'save', 'with env', '--json').out.all_after('"id":"')[..12]305	write(dir, '.kohignore', '.env\n')306	assert run(dir, 'save', 'ignore env').code == 0307	write(dir, '.env', 'KEY=never saved\n')308	assert run(dir, 'load', first, '--yes').code == 0309	assert os.read_file(os.join_path(dir, '.env'))! == 'KEY=never saved\n'310311	// Where the ignored file is missing, the restore still brings it back.312	other := temp_repo('ignored-restore-missing')313	defer { os.rmdir_all(other) or {} }314	init_repo(other)315	write(other, '.env', 'KEY=saved long ago\n')316	again := run(other, 'save', 'with env', '--json').out.all_after('"id":"')[..12]317	write(other, '.kohignore', '.env\n')318	assert run(other, 'save', 'ignore env').code == 0319	os.rm(os.join_path(other, '.env')) or { panic(err) }320	assert run(other, 'load', again, '--yes').code == 0321	assert os.read_file(os.join_path(other, '.env'))! == 'KEY=saved long ago\n'322}323324// A going-back preview lists paths only. Running diff(1) per file to draw it325// cost 27 s for 5,000 changed files, so it must not run diff at all.326fn test_a_going_back_preview_does_not_run_diff() {327	dir := temp_repo('preview-nodiff')328	home := temp_repo('preview-nodiff-home')329	defer {330		os.rmdir_all(dir) or {}331		os.rmdir_all(home) or {}332	}333	init_repo(dir)334	write(dir, 'a.txt', 'one\n')335	assert run_home(dir, home, 'save', 'one').code == 0336	write(dir, 'a.txt', 'two\n')337	assert run_home(dir, home, 'save', 'two').code == 0338	fake := os.join_path(home, 'bin')339	os.mkdir_all(fake) or { panic(err) }340	marker := os.join_path(home, 'diff-ran')341	os.write_file(os.join_path(fake, 'diff'), '#!/bin/sh\ntouch ${q(marker)}\nexit 2\n') or {342		panic(err)343	}344	os.chmod(os.join_path(fake, 'diff'), 0o755) or { panic(err) }345	assert run_home_with_path(dir, home, fake, 'undo', '--yes').code == 0346	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'347	assert !os.exists(marker)348}349350// A restore rewrites only what differs. Rewriting every file resets every351// mtime, so the next status has to hash the whole tree again.352fn test_a_restore_leaves_unchanged_files_alone() {353	dir := temp_repo('restore-skip')354	defer { os.rmdir_all(dir) or {} }355	init_repo(dir)356	write(dir, 'a.txt', 'one\n')357	write(dir, 'same.txt', 'never changes\n')358	assert run(dir, 'save', 'one').code == 0359	write(dir, 'a.txt', 'two\n')360	assert run(dir, 'save', 'two').code == 0361	long_ago := i64(1700000000)362	os.utime(os.join_path(dir, 'same.txt'), long_ago, long_ago) or { panic(err) }363	assert run(dir, 'undo', '--yes').code == 0364	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'365	assert os.file_last_mod_unix(os.join_path(dir, 'same.txt')) == long_ago366}367368// `save` records the executable bit, so `status` has to see it too, or a369// chmod would be invisible until it turned up in a save.370fn test_status_sees_an_executable_bit_change() {371	dir := temp_repo('chmod')372	defer { os.rmdir_all(dir) or {} }373	init_repo(dir)374	write(dir, 'run.sh', 'echo hi\n')375	assert run(dir, 'save', 'script').code == 0376	os.chmod(os.join_path(dir, 'run.sh'), 0o755) or { panic(err) }377	status := run(dir, 'status', '--json')378	assert status.out.contains('"dirty":true')379	assert status.out.contains('"modified":["run.sh"]')380}381382fn test_log_and_diff() {383	dir := temp_repo('history')384	defer { os.rmdir_all(dir) or {} }385	init_repo(dir)386	write(dir, 'a.txt', 'one\n')387	first := run(dir, 'save', 'one', '--session', 'alpha', '--json')388	id1 := first.out.all_after('"id":"')[..12]389	write(dir, 'a.txt', 'two\n')390	second := run(dir, 'save', 'two', '--session', 'beta', '--json')391	id2 := second.out.all_after('"id":"')[..12]392	cp := run(dir, 'checkpoint', 'checkpoint', '--json')393	assert cp.code == 0394	log := run(dir, 'log')395	assert log.code == 0396	assert log.out.contains('▸')397	assert log.out.contains('◐')398	lj := run(dir, 'log', '--json')399	assert lj.code == 0400	assert lj.out.contains('"head_id"')401	assert lj.out.contains('"saves"')402	assert run(dir, 'log', '--since', 'today').out.contains('two')403	session := run(dir, 'log', '--session', 'alpha')404	assert session.out.contains('one')405	assert !session.out.contains('two')406	write(dir, 'a.txt', 'three\n')407	d := run(dir, 'diff')408	assert d.code == 0409	assert d.out.contains('--- a/')410	assert d.out.contains('+++ b/')411	assert run(dir, 'diff', id1).code == 0412	assert run(dir, 'diff', id1, id2).code == 0413	dj := run(dir, 'diff', '--json')414	assert dj.code == 0415	assert dj.out.contains('"from"')416	assert dj.out.contains('"to"')417	assert dj.out.contains('"files"')418	assert dj.out.contains('"change":"modified"')419	assert run(dir, 'diff', 'not-a-real-id').code == 1420	assert run(dir, 'diff', id1, id2, 'third').code == 1421	write(dir, 'blob.bin', '\x00\x01\x02')422	diff_binary := run(dir, 'diff', '--json')423	assert diff_binary.out.contains('"binary":true')424	assert diff_binary.out.contains('Binary files differ')425}426427fn test_undo_revert_and_load() {428	dir := temp_repo('restore')429	defer { os.rmdir_all(dir) or {} }430	init_repo(dir)431	write(dir, 'a.txt', 'one\n')432	one := run(dir, 'save', 'one', '--json').out433	id1 := one.all_after('"id":"')[..12]434	write(dir, 'a.txt', 'two\n')435	write(dir, 'gone.txt', 'gone\n')436	second := run(dir, 'save', 'two', '--json').out437	id2 := second.all_after('"id":"')[..12]438	write(dir, 'a.txt', 'three\n')439	third := run(dir, 'save', 'three', '--json').out440	id3 := third.all_after('"id":"')[..12]441	// Unsaved work — here a file never saved — blocks every going-back but442	// revert, as in Koh 2: a restore must never overwrite what only the disk has.443	write(dir, 'never.txt', 'keep me\n')444	log_before := run(dir, 'log').out445	for args in [['undo', '--yes'], ['load', id1, '--yes'], ['pluck', id2, '--yes']] {446		blocked := run(dir, ...args)447		assert blocked.code == 1448		assert blocked.err.contains('unsaved changes')449	}450	assert run(dir, 'log').out == log_before451	os.rm(os.join_path(dir, 'never.txt')) or { panic(err) }452	write(dir, 'a.txt', 'edited, never saved\n')453	assert run(dir, 'undo', '--yes').err.contains('unsaved changes')454	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'edited, never saved\n'455	write(dir, 'a.txt', 'three\n')456	os.rm(os.join_path(dir, 'gone.txt')) or { panic(err) }457	assert run(dir, 'load', id1, '--yes').err.contains('unsaved changes')458	write(dir, 'gone.txt', 'gone\n')459	undo := run(dir, 'undo', '--yes', '--json')460	assert undo.code == 0461	if !undo.out.contains(id2) {462		panic('undo JSON did not name ${id2}: ${undo.out}')463	}464	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'465	assert os.exists(os.join_path(dir, 'gone.txt'))466	assert run(dir, 'load', id3, '--yes').code == 0467	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'three\n'468	assert run(dir, 'undo', '2', '--yes').code == 0469	assert run(dir, 'load', id2, '--yes').code == 0470	assert run(dir, 'undo', '99', '--yes').err.contains('nothing before')471	write(dir, 'a.txt', 'dirty\n')472	before := run(dir, 'log')473	refuse := run(dir, 'revert')474	assert refuse.code == 1475	assert refuse.err.contains('needs --yes when not interactive')476	assert run(dir, 'log').out == before.out477	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'dirty\n'478	write(dir, 'untracked.txt', 'remove\n')479	rv := run(dir, 'revert', '--yes')480	assert rv.code == 0481	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'482	assert !os.exists(os.join_path(dir, 'untracked.txt'))483	assert run(dir, 'revert', '--yes').out.contains('working tree already matches')484	assert run(dir, 'load', '--checkpoint', '--yes').code == 0485	assert run(dir, 'load', id2, '--json').code == 1486	assert run(dir, 'load', id2, '--json').err.contains('error')487	assert run(dir, 'load').code == 2488	assert run(dir, 'load', 'unknown-id', '--yes').code == 1489}490491fn test_flag_and_flagged_log() {492	dir := temp_repo('flag')493	defer { os.rmdir_all(dir) or {} }494	init_repo(dir)495	write(dir, 'flag.txt', 'one\n')496	saved := run(dir, 'save', 'flag me', '--json')497	id := saved.out.all_after('"id":"')[..12]498	flagged := run(dir, 'flag', id, '--reason', 'unsafe', '--json')499	assert flagged.code == 0500	assert flagged.out.contains('"flagged":true')501	assert flagged.out.contains('"reason":"unsafe"')502	list := run(dir, 'flag', '--json')503	assert list.code == 0504	assert list.out.contains(id)505	assert list.out.contains('unsafe')506	assert run(dir, 'log').out.contains('⚑')507	assert run(dir, 'flag', '--clear', id).code == 0508	assert run(dir, 'flag').out.contains('nothing is flagged')509	assert run(dir, 'flag', 'unknown-id').code == 1510	assert run(dir, 'flag').code == 0511}512513fn test_pluck_forward_reverse_dry_run_and_conflict() {514	dir := temp_repo('pluck')515	defer { os.rmdir_all(dir) or {} }516	init_repo(dir)517	write(dir, 'a.txt', 'one\n')518	first := run(dir, 'save', 'one', '--json').out519	id1 := first.all_after('"id":"')[..12]520	write(dir, 'a.txt', 'two\n')521	second := run(dir, 'save', 'two', '--json').out522	id2 := second.all_after('"id":"')[..12]523	assert run(dir, 'load', id1, '--yes').code == 0524	dry := run(dir, 'pluck', id2, '--dry-run')525	assert dry.code == 0526	assert dry.out.contains('a.txt')527	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'528	assert run(dir, 'pluck', id2, '--yes').code == 0529	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'530	assert run(dir, 'pluck', '--reverse', id2, '--yes').code == 0531	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'532	write(dir, 'a.txt', 'different\n')533	assert run(dir, 'pluck', id2, '--dry-run').code == 1534	assert run(dir, 'save', 'different').code == 0535	conflict := run(dir, 'pluck', id2, '--yes')536	assert conflict.code == 1537	assert conflict.err.contains('a.txt')538	assert run(dir, 'pluck').code == 2539	assert run(dir, 'pluck', 'unknown-id').code == 1540}541542fn test_peek_and_doctor() {543	dir := temp_repo('peek-doctor')544	defer { os.rmdir_all(dir) or {} }545	init_repo(dir)546	write(dir, 'peek.txt', 'peek me\n')547	assert run(dir, 'save', 'peekable').code == 0548	id := run(dir, 'log', '--json').out.all_after('"id":"')[..12]549	before_log := run(dir, 'log', '--json').out550	peek := run(dir, 'peek', id, '--json')551	assert peek.code == 0552	peek_path := peek.out.all_after('"path":"').before('"')553	assert peek.out.contains('"id":"${id}"')554	assert os.read_file(os.join_path(peek_path, 'peek.txt'))! == 'peek me\n'555	assert run(dir, 'status').out.contains('no changes')556	assert run(dir, 'log', '--json').out == before_log557	assert run(dir, 'peek').code == 2558	assert run(dir, 'peek', 'unknown-id').code == 1559	backup := os.join_path(dir, 'doctor.backup')560	healthy := run(dir, 'doctor')561	assert healthy.code == 0562	assert healthy.out.contains('is sound')563	report := run(dir, 'doctor', '--json')564	assert report.code == 0565	for key in ['problems', 'objects', 'saves', 'checkpoints', 'cached_files', 'peek_folders_removed',566		'backup'] {567		read_json_has(report.out, key)568	}569	backed := run(dir, 'doctor', '--backup', backup)570	assert backed.code == 0571	assert os.exists(backup)572	assert backed.out.contains(backup)573	assert run(dir, 'doctor', '--backup', backup).code == 1574	assert run(dir, 'peek', id, '--json').code == 0575	// A peek made today is left for whoever is reading it.576	kept := run(dir, 'doctor', '--json')577	assert kept.code == 0578	assert os.exists(peek_path)579	os.rmdir_all(peek_path) or {}580}581582fn test_strip_refuses_without_terminal() {583	dir := temp_repo('strip')584	defer { os.rmdir_all(dir) or {} }585	init_repo(dir)586	write(dir, 'secret.txt', 'keep\n')587	assert run(dir, 'save', 'secret').code == 0588	before_log := run(dir, 'log', '--json').out589	refused := run(dir, 'strip', 'secret.txt')590	assert refused.code == 1591	assert refused.err.contains('needs a terminal')592	assert run(dir, 'log', '--json').out == before_log593	assert os.read_file(os.join_path(dir, 'secret.txt'))! == 'keep\n'594	assert run(dir, 'log', '--json').out.contains('secret')595}596597fn test_saves_and_checkpoints_aliases() {598	dir := temp_repo('aliases')599	defer { os.rmdir_all(dir) or {} }600	init_repo(dir)601	write(dir, 'alias.txt', 'one\n')602	assert run(dir, 'save', 'plain save').code == 0603	assert run(dir, 'checkpoint', 'checkpoint save').code == 0604	saves := run(dir, 'saves')605	assert saves.code == 0606	assert saves.out.contains('plain save')607	assert saves.out.contains('checkpoint save')608	checkpoints := run(dir, 'checkpoints')609	assert checkpoints.code == 0610	assert checkpoints.out.contains('checkpoint save')611	assert !checkpoints.out.contains('plain save')612	json_result := run(dir, 'checkpoints', '--json')613	assert json_result.code == 0614	assert json_result.out.contains('"head_id"')615	assert json_result.out.contains('"saves"')616	assert json_result.out.contains('"is_checkpoint":true')617	assert !json_result.out.contains('"is_checkpoint":false')618}619620fn test_remote_configuration_is_isolated_and_atomic() {621	dir := temp_repo('remote')622	home := temp_repo('remote-home')623	defer {624		os.rmdir_all(dir) or {}625		os.rmdir_all(home) or {}626	}627	empty := run_home(dir, home, 'remote', '--json')628	assert empty.code == 0629	assert empty.out.contains('"configured":false')630	target := os.join_path(home, 'remote-store')631	set := run_home(dir, home, 'remote', 'folder', target)632	assert set.code == 0633	assert os.is_dir(target)634	state := run_home(dir, home, 'remote', '--json')635	assert state.code == 0636	assert state.out.contains('"kind":"folder"')637	assert state.out.contains(target)638	assert run_home(dir, home, 'remote', 's3', 'http://127.0.0.1:1', 'bucket', 'region').code == 1639	assert run_home(dir, home, 'remote', '--json').out.contains(target)640	assert run_home(dir, home, 'remote', 's3', 'http://127.0.0.1:1', 'bucket', 'region').err.contains('KOH_ACCESS_KEY')641	assert run_home(dir, home, 'remote', '--forget').code == 0642	assert run_home(dir, home, 'remote', '--json').out.contains('"configured":false')643}644645// A clone belongs to the repo it was stolen from, whatever its folder is646// called later: renaming it must not start a second repo on the remote.647fn test_a_renamed_clone_keeps_offering_to_its_repo() {648	syncroot := temp_repo('rename-clone')649	home := temp_repo('rename-clone-home')650	defer {651		os.rmdir_all(syncroot) or {}652		os.rmdir_all(home) or {}653	}654	remote := os.join_path(syncroot, 'remote')655	a := os.join_path(syncroot, 'A', 'proj')656	b_parent := os.join_path(syncroot, 'B')657	os.mkdir_all(a) or { panic(err) }658	os.mkdir_all(b_parent) or { panic(err) }659	init_repo(a)660	write(a, 'a.txt', 'from A\n')661	assert run_home(a, home, 'remote', 'folder', remote).code == 0662	assert run_home(a, home, 'save', 'A first').code == 0663	assert run_home(b_parent, home, 'steal', 'proj').code == 0664	renamed := os.join_path(b_parent, 'renamed')665	os.mv(os.join_path(b_parent, 'proj'), renamed) or { panic(err) }666	write(renamed, 'b.txt', 'from B\n')667	assert run_home(renamed, home, 'save', 'B first').code == 0668	assert !os.exists(os.join_path(remote, 'renamed'))669	assert run_home(a, home, 'steal').code == 0670	assert os.read_file(os.join_path(a, 'b.txt'))! == 'from B\n'671}672673fn test_offer_steal_folder_remote() {674	syncroot := temp_repo('sync')675	home := temp_repo('sync-home')676	defer {677		os.rmdir_all(syncroot) or {}678		os.rmdir_all(home) or {}679	}680	remote := os.join_path(syncroot, 'remote')681	a := os.join_path(syncroot, 'A', 'proj')682	b_parent := os.join_path(syncroot, 'B')683	os.mkdir_all(a) or { panic(err) }684	os.mkdir_all(b_parent) or { panic(err) }685	init_repo(a)686	write(a, 'a.txt', 'from A\n')687	assert run_home(a, home, 'remote', 'folder', remote).code == 0688	assert run_home(a, home, 'save', 'A first').code == 0689	clone := run_home(b_parent, home, 'steal', 'proj')690	assert clone.code == 0691	b := os.join_path(b_parent, 'proj')692	assert os.read_file(os.join_path(b, 'a.txt'))! == 'from A\n'693	write(b, 'b.txt', 'from B\n')694	assert run_home(b, home, 'save', 'B first').code == 0695	write(a, 'a2.txt', 'second\n')696	assert run_home(a, home, 'save', 'A second').code == 0697	assert run_home(a, home, 'steal').code == 0698	assert os.exists(os.join_path(a, 'b.txt'))699	assert run_home(b_parent, home, 'steal', '--list').out.contains('proj')700	write(a, 'clash.txt', 'base\n')701	assert run_home(a, home, 'save', 'clash base').code == 0702	assert run_home(b, home, 'steal').code == 0703	write(a, 'clash.txt', 'A version\n')704	assert run_home(a, home, 'save', 'A clash').code == 0705	write(b, 'clash.txt', 'B version\n')706	assert run_home(b, home, 'save', 'B clash').code == 0707	refused := run_home(b, home, 'steal')708	assert refused.code == 1709	assert refused.err.contains('--mine') || refused.err.contains('--theirs')710	b_head := run_home(b, home, 'status', '--json').out.all_after('"head_id":"')[..12]711	theirs := run_home(b, home, 'steal', '--theirs', '--json')712	assert theirs.code == 0713	// The pre-combine tree is off the line now; the way back must be named,714	// or an agent without the history view cannot find it.715	assert theirs.out.contains('"previous_head":"${b_head}"')716	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'A version\n'717	assert run_home(b, home, 'load', b_head, '--yes').code == 0718	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'B version\n'719	assert run_home(b, home, 'load', theirs.out.all_after('"head":"')[..12], '--yes').code == 0720	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'A version\n'721	write(a, 'clash.txt', 'A second\n')722	assert run_home(a, home, 'save', 'A second clash').code == 0723	write(b, 'clash.txt', 'B second\n')724	assert run_home(b, home, 'save', 'B second clash').code == 0725	assert run_home(b, home, 'steal', '--mine').code == 0726	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'B second\n'727	assert run_home(b, home, 'log').out.contains('combine: kept mine for')728}729730// A clone brings in the whole history, flags included; both output forms must731// say which saves came in flagged, and why.732fn test_a_clone_reports_flagged_saves() {733	syncroot := temp_repo('clone-flags')734	home := temp_repo('clone-flags-home')735	defer {736		os.rmdir_all(syncroot) or {}737		os.rmdir_all(home) or {}738	}739	a := os.join_path(syncroot, 'A', 'proj')740	os.mkdir_all(a) or { panic(err) }741	init_repo(a)742	assert run_home(a, home, 'remote', 'folder', os.join_path(syncroot, 'remote')).code == 0743	write(a, 'a.txt', 'one\n')744	id := run_home(a, home, 'save', 'risky', '--json').out.all_after('"id":"')[..12]745	assert run_home(a, home, 'flag', id, '--reason', 'broke the build').code == 0746	assert run_home(a, home, 'offer').code == 0747	for name in ['B', 'C'] {748		os.mkdir_all(os.join_path(syncroot, name)) or { panic(err) }749	}750	json_clone := run_home(os.join_path(syncroot, 'B'), home, 'steal', 'proj', '--json')751	assert json_clone.code == 0752	assert json_clone.out.contains('"flagged":["${id}"]')753	text_clone := run_home(os.join_path(syncroot, 'C'), home, 'steal', 'proj')754	assert text_clone.code == 0755	assert text_clone.out.contains('[${id}] came in flagged — broke the build')756}757758// A folder remote on a disk or share that is not mounted is simply not there.759// Creating it would put the saves in a stand-in folder the other machine never760// sees; the offer must say what is wrong instead.761fn test_an_unmounted_folder_remote_is_not_recreated() {762	syncroot := temp_repo('unmounted')763	home := temp_repo('unmounted-home')764	defer {765		os.rmdir_all(syncroot) or {}766		os.rmdir_all(home) or {}767	}768	mount := os.join_path(syncroot, 'nas')769	remote := os.join_path(mount, 'koh')770	a := os.join_path(syncroot, 'proj')771	os.mkdir_all(a) or { panic(err) }772	init_repo(a)773	assert run_home(a, home, 'remote', 'folder', remote).code == 0774	write(a, 'a.txt', 'one\n')775	assert run_home(a, home, 'save', 'first').code == 0776	os.rename(mount, os.join_path(syncroot, 'nas-unplugged')) or { panic(err) }777	os.mkdir(mount) or { panic(err) }778	offered := run_home(a, home, 'offer')779	assert offered.code == 1780	assert offered.err.contains('mounted')781	assert !os.exists(remote)782	write(a, 'a.txt', 'two\n')783	saved := run_home(a, home, 'save', 'second')784	assert saved.code == 0785	assert saved.out.contains('mounted')786	assert !os.exists(remote)787}788789fn test_man_and_koh2_handoff() {790	dir := temp_repo('man')791	home := temp_repo('man-home')792	defer {793		os.rmdir_all(dir) or {}794		os.rmdir_all(home) or {}795	}796	whole := run_home(dir, home, 'man')797	assert whole.code == 0798	assert whole.out.contains('NAME')799	assert whole.out.contains('COMMANDS')800	strip := run_home(dir, home, 'man', 'strip')801	assert strip.code == 0802	assert strip.out.contains('strip')803	assert !strip.out.contains('koh save ')804	assert run_home(dir, home, 'man', 'nonsense').code == 2805	legacy := temp_repo('legacy')806	defer { os.rmdir_all(legacy) or {} }807	os.mkdir_all(os.join_path(legacy, '.koh')) or { panic(err) }808	fake := os.join_path(home, 'bin')809	os.mkdir_all(fake) or { panic(err) }810	fake_koh := os.join_path(fake, 'koh2')811	os.write_file(fake_koh, '#!/bin/sh\nprintf "handoff:%s\\n" "$*"\nexit 7\n') or { panic(err) }812	os.chmod(fake_koh, 0o755) or { panic(err) }813	handoff := run_home_with_path(legacy, home, fake, 'status', '--json')814	assert handoff.code == 7815	assert handoff.out.contains('handoff:status --json')816	// One notice line, on stderr, so koh2's own output stays as it was.817	assert handoff.err.contains('Koh 2 repo')818	assert handoff.err.trim_space().split_into_lines().len == 1819	assert handoff.out.trim_space() == 'handoff:status --json'820}821822fn run_home_with_path(repo string, home string, bin_dir string, args ...string) Result {823	stamp := '${os.getpid()}-${time.now().unix_nano()}'824	base := os.join_path(os.temp_dir(), 'koh3-cli-${stamp}')825	out_path := '${base}.out'826	err_path := '${base}.err'827	code_path := '${base}.code'828	mut command := 'HOME=${q(home)} PATH=${q(bin_dir + ':' + os.getenv('PATH'))} ${q(binary)}'829	for arg in args {830		command += ' ${q(arg)}'831	}832	shell := 'cd ${q(repo)} && ${command} </dev/null >${q(out_path)} 2>${q(err_path)}; printf "%s" $? >${q(code_path)}'833	result := os.execute(shell)834	if result.exit_code != 0 {835		panic('could not run test command: ${result.output}')836	}837	code := os.read_file(code_path) or { panic(err) }838	out := os.read_file(out_path) or { '' }839	err := os.read_file(err_path) or { '' }840	os.rm(out_path) or {}841	os.rm(err_path) or {}842	os.rm(code_path) or {}843	return Result{844		code: code.int()845		out:  out846		err:  err847	}848}849850// --- migration -------------------------------------------------------------851852fn koh2_binary() string {853	return os.find_abs_path_of_executable('koh') or { '' }854}855856// run_koh2 runs the Koh 2 binary in a fixture; its own output is not under857// test here.858fn run_koh2(dir string, command string) {859	os.execute('cd ${q(dir)} && ${command} >/dev/null 2>&1')860}861862fn save_ids(dir string) []string {863	mut ids := []string{}864	for name in os.ls(os.join_path(dir, '.koh', 'snapshots')) or { []string{} } {865		if name.ends_with('.json') {866			ids << name.trim_right('.json')867		}868	}869	ids.sort()870	return ids871}872873fn test_migrate_converts_a_koh2_repo_and_keeps_every_save() {874	koh2 := koh2_binary()875	if koh2 == '' {876		println('skipping the migration tests: koh (Koh 2) is not on PATH')877		return878	}879	dir := temp_repo('migrate')880	defer { os.rmdir_all(dir) or {} }881	home := temp_repo('migrate-home')882	defer { os.rmdir_all(home) or {} }883	run_koh2(dir, '${q(koh2)} init')884	// One file large enough to be an object, one small enough to be inlined.885	write(dir, 'code.txt', 'x'.repeat(700))886	write(dir, 'tiny.txt', 'tiny\n')887	run_koh2(dir, '${q(koh2)} save "first save"')888	run_koh2(dir, '${q(koh2)} checkpoint "before something"')889	write(dir, 'code.txt', 'y'.repeat(700))890	run_koh2(dir, '${q(koh2)} save "second save"')891	original := save_ids(dir)892	assert original.len == 3893894	report := run_home(dir, home, 'migrate')895	assert report.code == 0896	assert report.out.contains('migrated 3 saves')897	// The swap: `.koh` is a file, the old data is archived, nothing is staging.898	assert os.is_file(os.join_path(dir, '.koh'))899	assert os.is_dir(os.join_path(dir, '.koh-v2'))900	assert os.is_file(os.join_path(dir, '.kohignore'))901	assert !os.exists(os.join_path(dir, '.koh-migrate'))902903	// Every save kept its original ID, and the new repo is sound.904	logged := run_home(dir, home, 'log', '--json')905	assert logged.code == 0906	for id in original {907		assert logged.out.contains(id)908	}909	assert run_home(dir, home, 'doctor').code == 0910	assert run_home(dir, home, 'status').code == 0911912	// Migrating again has nothing to convert.913	assert run_home(dir, home, 'migrate').code == 1914}915916fn test_migrate_refuses_a_tree_that_does_not_match_the_last_save() {917	koh2 := koh2_binary()918	if koh2 == '' {919		return920	}921	dir := temp_repo('migrate-dirty')922	defer { os.rmdir_all(dir) or {} }923	home := temp_repo('migrate-dirty-home')924	defer { os.rmdir_all(home) or {} }925	run_koh2(dir, '${q(koh2)} init')926	write(dir, 'code.txt', 'x'.repeat(700))927	run_koh2(dir, '${q(koh2)} save "only save"')928	write(dir, 'code.txt', 'unsaved change\n')929930	refused := run_home(dir, home, 'migrate')931	assert refused.code == 1932	assert refused.err.contains('save with koh2 first')933	// Nothing moved: still Koh 2, no archive, no staging file.934	assert os.is_dir(os.join_path(dir, '.koh'))935	assert !os.exists(os.join_path(dir, '.koh-v2'))936	assert !os.exists(os.join_path(dir, '.koh-migrate'))937}938939// Koh 2 never saved a root `.kohconfig`, root `.kohignore.<remote>` rules or940// `*.bundle` files, so a clean Koh 2 repo may hold them. Most real repos have941// a `.kohconfig`; migrate must not call them unsaved work.942fn test_migrate_passes_over_the_files_koh2_never_saved() {943	koh2 := koh2_binary()944	if koh2 == '' {945		return946	}947	dir := temp_repo('migrate-koh2-ignores')948	defer { os.rmdir_all(dir) or {} }949	home := temp_repo('migrate-koh2-ignores-home')950	defer { os.rmdir_all(home) or {} }951	run_koh2(dir, '${q(koh2)} init')952	write(dir, 'code.txt', 'x'.repeat(700))953	run_koh2(dir, '${q(koh2)} save "only save"')954	write(dir, '.kohconfig', 'stable_days = 14\n')955	write(dir, '.kohignore.public', 'private/\n')956	write(dir, 'lib/app.bundle', 'bundle\n')957	write(dir, 'ios/Settings.bundle/Root.plist', 'settings\n')958	// Koh 2 keeps saving a file under a folder pattern added later, where959	// Koh 3 reads the same rule as covering the folder: the saved file is on960	// disk and matches, so the tree is clean.961	write(dir, 'native/t.dSYM/Info.plist', 'plist\n')962	run_koh2(dir, '${q(koh2)} save --agent test --session test "add the dsym"')963	// Koh 2 skips *.bundle even when its rules no longer list it.964	ignore_path := os.join_path(dir, '.koh', 'ignore')965	rules := os.read_file(ignore_path)!.split_into_lines().filter(it != '*.bundle')966	os.write_file(ignore_path, rules.join('\n') + '\nnative/*.dSYM\n')!967	// A saved file the walk skips still has to match what was saved.968	write(dir, 'native/t.dSYM/Info.plist', 'changed\n')969	changed := run_home(dir, home, 'migrate')970	assert changed.code == 1971	assert changed.err.contains('native/t.dSYM/Info.plist does not match')972	write(dir, 'native/t.dSYM/Info.plist', 'plist\n')973	assert os.execute('cd ${q(dir)} && ${q(koh2)} status --json').output.contains('"dirty":false')974975	migrated := run_home(dir, home, 'migrate')976	assert migrated.code == 0, migrated.err977	// They stay where they were, for the user to keep or delete.978	assert os.read_file(os.join_path(dir, '.kohconfig'))! == 'stable_days = 14\n'979}