cli_test.v

36.2 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}9899fn test_save_checkpoint_and_status() {100	dir := temp_repo('save')101	defer { os.rmdir_all(dir) or {} }102	init_repo(dir)103	write(dir, 'tracked.txt', 'one\n')104	r := run(dir, 'save', 'first message', '--agent', 'agent-7', '--session', 'session-a', '--json')105	assert r.code == 0106	for key in ['id', 'parent', 'message', 'created_at', 'machine', 'is_checkpoint', 'agent',107		'session', 'files', 'size_bytes'] {108		read_json_has(r.out, key)109	}110	assert r.out.contains('"message":"first message"')111	assert r.out.contains('"agent":"agent-7"')112	assert r.out.contains('"session":"session-a"')113	assert r.out.contains('"is_checkpoint":false')114	assert run(dir, 'save', 'again').code == 1115	assert run(dir, 'save', 'again').err.contains('nothing has changed since the last save')116	assert run(dir, 'save').code == 2117	assert run(dir, 'save', 'x', '--bogus').code == 2118	cp := run(dir, 'checkpoint', 'still first', '--json')119	assert cp.code == 0120	assert cp.out.contains('"is_checkpoint":true')121	assert cp.out.contains('"parent":')122	clean := run(dir, 'status')123	assert clean.code == 0124	assert clean.out.contains('no changes')125	write(dir, 'tracked.txt', 'two\n')126	write(dir, 'new.txt', 'new\n')127	os.rm(os.join_path(dir, 'tracked.txt')) or { panic(err) }128	write(dir, '.kohignore', '*.log\n')129	status := run(dir, 'status')130	assert status.code == 0131	assert status.out.contains('+')132	assert status.out.contains('~') || status.out.contains('-')133	assert status.out.contains('added')134	js := run(dir, 'status', '--json')135	assert js.code == 0136	for key in ['head_id', 'head_msg', 'dirty', 'modified', 'added', 'deleted', 'ignore_changed'] {137		read_json_has(js.out, key)138	}139	assert js.out.contains('"ignore_changed":true')140}141142fn test_status_requires_repo_and_ignore_rules() {143	dir := temp_repo('status')144	defer { os.rmdir_all(dir) or {} }145	assert run(dir, 'status').code == 1146	init_repo(dir)147	write(dir, '.kohignore', '*.log\nbuild/\n')148	write(dir, 'keep.txt', 'keep\n')149	write(dir, 'ignored.log', 'ignore\n')150	write(dir, 'build/output.txt', 'ignore\n')151	assert run(dir, 'save', 'keep').code == 0152	assert run(dir, 'status').out.contains('no changes')153	assert !run(dir, 'status').out.contains('ignored.log')154	assert !run(dir, 'status').out.contains('build/output.txt')155	assert !run(dir, 'status').out.contains('LOG.md')156}157158// LOG.md is a convenience written after the save commits. If it cannot be159// written, the save still happened, and an agent that retried on a failure160// would only be told nothing had changed.161fn test_a_save_succeeds_when_log_md_cannot_be_written() {162	dir := temp_repo('logmd')163	defer { os.rmdir_all(dir) or {} }164	init_repo(dir)165	os.mkdir_all(os.join_path(dir, 'LOG.md')) or { panic(err) }166	write(dir, 'a.txt', 'one\n')167	r := run(dir, 'save', 'first', '--json')168	assert r.code == 0169	assert r.out.starts_with('{')170	assert r.err.contains('LOG.md')171	assert run(dir, 'log', '--json').out.contains('"message":"first"')172}173174// A folder of ignored files can sit where a restored file should go. Koh175// never touches ignored files, so the restore must stop and say so, not drop176// the file inside the folder under a temporary name.177fn test_a_restore_refuses_a_folder_of_ignored_files_in_the_way() {178	dir := temp_repo('dir-in-way')179	defer { os.rmdir_all(dir) or {} }180	init_repo(dir)181	write(dir, 'out', 'a file\n')182	first := run(dir, 'save', 'out is a file', '--json').out.all_after('"id":"')[..12]183	os.rm(os.join_path(dir, 'out')) or { panic(err) }184	write(dir, 'out/build.log', 'ignored\n')185	assert run(dir, 'save', 'out is gone').code == 0186	r := run(dir, 'load', first, '--yes')187	assert r.code == 1188	assert r.err.contains('out')189	assert os.ls(os.join_path(dir, 'out'))! == ['build.log']190}191192// Koh never follows a symlink, so a folder replaced by a link to somewhere193// else is not the repo's to write into: restoring through it would overwrite194// files outside the repo. The refusal comes before anything is recorded.195fn test_a_restore_never_writes_through_a_symlinked_folder() {196	dir := temp_repo('link-in-way')197	outside := temp_repo('link-target')198	defer {199		os.rmdir_all(dir) or {}200		os.rmdir_all(outside) or {}201	}202	init_repo(dir)203	write(dir, 'docs/a.md', 'saved\n')204	first := run(dir, 'save', 'docs', '--json').out.all_after('"id":"')[..12]205	os.rmdir_all(os.join_path(dir, 'docs')) or { panic(err) }206	write(outside, 'a.md', 'precious\n')207	os.symlink(outside, os.join_path(dir, 'docs')) or { panic(err) }208	assert run(dir, 'save', 'docs is a link now').code == 0209	head := run(dir, 'status', '--json').out210	r := run(dir, 'load', first, '--yes')211	assert r.code == 1212	assert r.err.contains('docs')213	assert os.read_file(os.join_path(outside, 'a.md'))! == 'precious\n'214	assert run(dir, 'status', '--json').out == head215}216217// A restore records its save first, then writes files. When the writing stops218// part way, the half-written tree is not somebody's work: saving it would219// record (and offer) a tree that undoes changes nobody asked to undo. Every220// command that would build on it points at revert, which finishes the job.221fn test_a_restore_cut_short_points_at_revert() {222	dir := temp_repo('cut-short')223	defer {224		os.chmod(os.join_path(dir, 'zz'), 0o755) or {}225		os.rmdir_all(dir) or {}226	}227	init_repo(dir)228	write(dir, 'zero', '0\n')229	assert run(dir, 'save', 'zero').code == 0230	write(dir, 'a.txt', 'v1\n')231	write(dir, 'zz/f', 'v1\n')232	assert run(dir, 'save', 'first').code == 0233	write(dir, 'a.txt', 'v2\n')234	write(dir, 'zz/f', 'v2\n')235	assert run(dir, 'save', 'second').code == 0236	// a.txt is written, then the read-only folder stops the restore: the237	// tree is genuinely half one save and half the other.238	os.chmod(os.join_path(dir, 'zz'), 0o555)!239	stopped := run(dir, 'undo', '--yes')240	assert stopped.code == 1241	assert stopped.err.contains('koh revert')242	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'v1\n'243	assert os.read_file(os.join_path(dir, 'zz/f'))! == 'v2\n'244	// Even a status that cannot read the tree says what happened.245	os.chmod(os.join_path(dir, 'zz'), 0o000)!246	assert run(dir, 'status').err.contains('koh revert')247	os.chmod(os.join_path(dir, 'zz'), 0o755)!248249	assert run(dir, 'status', '--json').out.contains('"restore_unfinished":true')250	for args in [['save', 'half'], ['checkpoint', 'half'], ['undo', '--yes']] {251		r := run(dir, ...args)252		assert r.code == 1253		assert r.err.contains('koh revert')254	}255	assert run(dir, 'revert', '--yes').code == 0256	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'v1\n'257	assert os.read_file(os.join_path(dir, 'zz/f'))! == 'v1\n'258	assert run(dir, 'status', '--json').out.contains('"restore_unfinished":false')259	write(dir, 'a.txt', 'v3\n')260	assert run(dir, 'save', 'carry on').code == 0261}262263// Doctor clears peek folders left from earlier days, never one somebody may264// be reading right now.265fn test_doctor_sweeps_only_old_peek_folders() {266	dir := temp_repo('peek-sweep')267	// V's temp_dir is /tmp on macOS whatever TMPDIR says, so these live in268	// the real temp directory under names no save could have.269	fresh := os.join_path(os.temp_dir(), 'koh-peek-fresh${os.getpid()}')270	old := os.join_path(os.temp_dir(), 'koh-peek-old${os.getpid()}')271	defer {272		os.rmdir_all(dir) or {}273		os.rmdir_all(fresh) or {}274		os.rmdir_all(old) or {}275	}276	init_repo(dir)277	write(dir, 'a.txt', 'one\n')278	assert run(dir, 'save', 'one').code == 0279	os.mkdir_all(fresh) or { panic(err) }280	os.mkdir_all(old) or { panic(err) }281	two_days_ago := time.now().unix() - 2 * 86400282	os.utime(old, two_days_ago, two_days_ago) or { panic(err) }283	assert run(dir, 'doctor', '--json').code == 0284	assert os.exists(fresh)285	assert !os.exists(old)286}287288// A file saved long ago and ignored since holds work no save has. Loading the289// old save must not write over it; the document says a restore never touches290// ignored files.291fn test_a_restore_never_overwrites_an_ignored_file() {292	dir := temp_repo('ignored-restore')293	defer { os.rmdir_all(dir) or {} }294	init_repo(dir)295	write(dir, '.env', 'KEY=saved long ago\n')296	first := run(dir, 'save', 'with env', '--json').out.all_after('"id":"')[..12]297	write(dir, '.kohignore', '.env\n')298	assert run(dir, 'save', 'ignore env').code == 0299	write(dir, '.env', 'KEY=never saved\n')300	assert run(dir, 'load', first, '--yes').code == 0301	assert os.read_file(os.join_path(dir, '.env'))! == 'KEY=never saved\n'302303	// Where the ignored file is missing, the restore still brings it back.304	other := temp_repo('ignored-restore-missing')305	defer { os.rmdir_all(other) or {} }306	init_repo(other)307	write(other, '.env', 'KEY=saved long ago\n')308	again := run(other, 'save', 'with env', '--json').out.all_after('"id":"')[..12]309	write(other, '.kohignore', '.env\n')310	assert run(other, 'save', 'ignore env').code == 0311	os.rm(os.join_path(other, '.env')) or { panic(err) }312	assert run(other, 'load', again, '--yes').code == 0313	assert os.read_file(os.join_path(other, '.env'))! == 'KEY=saved long ago\n'314}315316// A going-back preview lists paths only. Running diff(1) per file to draw it317// cost 27 s for 5,000 changed files, so it must not run diff at all.318fn test_a_going_back_preview_does_not_run_diff() {319	dir := temp_repo('preview-nodiff')320	home := temp_repo('preview-nodiff-home')321	defer {322		os.rmdir_all(dir) or {}323		os.rmdir_all(home) or {}324	}325	init_repo(dir)326	write(dir, 'a.txt', 'one\n')327	assert run_home(dir, home, 'save', 'one').code == 0328	write(dir, 'a.txt', 'two\n')329	assert run_home(dir, home, 'save', 'two').code == 0330	fake := os.join_path(home, 'bin')331	os.mkdir_all(fake) or { panic(err) }332	marker := os.join_path(home, 'diff-ran')333	os.write_file(os.join_path(fake, 'diff'), '#!/bin/sh\ntouch ${q(marker)}\nexit 2\n') or {334		panic(err)335	}336	os.chmod(os.join_path(fake, 'diff'), 0o755) or { panic(err) }337	assert run_home_with_path(dir, home, fake, 'undo', '--yes').code == 0338	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'339	assert !os.exists(marker)340}341342// A restore rewrites only what differs. Rewriting every file resets every343// mtime, so the next status has to hash the whole tree again.344fn test_a_restore_leaves_unchanged_files_alone() {345	dir := temp_repo('restore-skip')346	defer { os.rmdir_all(dir) or {} }347	init_repo(dir)348	write(dir, 'a.txt', 'one\n')349	write(dir, 'same.txt', 'never changes\n')350	assert run(dir, 'save', 'one').code == 0351	write(dir, 'a.txt', 'two\n')352	assert run(dir, 'save', 'two').code == 0353	long_ago := i64(1700000000)354	os.utime(os.join_path(dir, 'same.txt'), long_ago, long_ago) or { panic(err) }355	assert run(dir, 'undo', '--yes').code == 0356	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'357	assert os.file_last_mod_unix(os.join_path(dir, 'same.txt')) == long_ago358}359360// `save` records the executable bit, so `status` has to see it too, or a361// chmod would be invisible until it turned up in a save.362fn test_status_sees_an_executable_bit_change() {363	dir := temp_repo('chmod')364	defer { os.rmdir_all(dir) or {} }365	init_repo(dir)366	write(dir, 'run.sh', 'echo hi\n')367	assert run(dir, 'save', 'script').code == 0368	os.chmod(os.join_path(dir, 'run.sh'), 0o755) or { panic(err) }369	status := run(dir, 'status', '--json')370	assert status.out.contains('"dirty":true')371	assert status.out.contains('"modified":["run.sh"]')372}373374fn test_log_and_diff() {375	dir := temp_repo('history')376	defer { os.rmdir_all(dir) or {} }377	init_repo(dir)378	write(dir, 'a.txt', 'one\n')379	first := run(dir, 'save', 'one', '--session', 'alpha', '--json')380	id1 := first.out.all_after('"id":"')[..12]381	write(dir, 'a.txt', 'two\n')382	second := run(dir, 'save', 'two', '--session', 'beta', '--json')383	id2 := second.out.all_after('"id":"')[..12]384	cp := run(dir, 'checkpoint', 'checkpoint', '--json')385	assert cp.code == 0386	log := run(dir, 'log')387	assert log.code == 0388	assert log.out.contains('▸')389	assert log.out.contains('◐')390	lj := run(dir, 'log', '--json')391	assert lj.code == 0392	assert lj.out.contains('"head_id"')393	assert lj.out.contains('"saves"')394	assert run(dir, 'log', '--since', 'today').out.contains('two')395	session := run(dir, 'log', '--session', 'alpha')396	assert session.out.contains('one')397	assert !session.out.contains('two')398	write(dir, 'a.txt', 'three\n')399	d := run(dir, 'diff')400	assert d.code == 0401	assert d.out.contains('--- a/')402	assert d.out.contains('+++ b/')403	assert run(dir, 'diff', id1).code == 0404	assert run(dir, 'diff', id1, id2).code == 0405	dj := run(dir, 'diff', '--json')406	assert dj.code == 0407	assert dj.out.contains('"from"')408	assert dj.out.contains('"to"')409	assert dj.out.contains('"files"')410	assert dj.out.contains('"change":"modified"')411	assert run(dir, 'diff', 'not-a-real-id').code == 1412	assert run(dir, 'diff', id1, id2, 'third').code == 1413	write(dir, 'blob.bin', '\x00\x01\x02')414	diff_binary := run(dir, 'diff', '--json')415	assert diff_binary.out.contains('"binary":true')416	assert diff_binary.out.contains('Binary files differ')417}418419fn test_undo_revert_and_load() {420	dir := temp_repo('restore')421	defer { os.rmdir_all(dir) or {} }422	init_repo(dir)423	write(dir, 'a.txt', 'one\n')424	one := run(dir, 'save', 'one', '--json').out425	id1 := one.all_after('"id":"')[..12]426	write(dir, 'a.txt', 'two\n')427	write(dir, 'gone.txt', 'gone\n')428	second := run(dir, 'save', 'two', '--json').out429	id2 := second.all_after('"id":"')[..12]430	write(dir, 'a.txt', 'three\n')431	third := run(dir, 'save', 'three', '--json').out432	id3 := third.all_after('"id":"')[..12]433	// Unsaved work — here a file never saved — blocks every going-back but434	// revert, as in Koh 2: a restore must never overwrite what only the disk has.435	write(dir, 'never.txt', 'keep me\n')436	log_before := run(dir, 'log').out437	for args in [['undo', '--yes'], ['load', id1, '--yes'], ['pluck', id2, '--yes']] {438		blocked := run(dir, ...args)439		assert blocked.code == 1440		assert blocked.err.contains('unsaved changes')441	}442	assert run(dir, 'log').out == log_before443	os.rm(os.join_path(dir, 'never.txt')) or { panic(err) }444	write(dir, 'a.txt', 'edited, never saved\n')445	assert run(dir, 'undo', '--yes').err.contains('unsaved changes')446	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'edited, never saved\n'447	write(dir, 'a.txt', 'three\n')448	os.rm(os.join_path(dir, 'gone.txt')) or { panic(err) }449	assert run(dir, 'load', id1, '--yes').err.contains('unsaved changes')450	write(dir, 'gone.txt', 'gone\n')451	undo := run(dir, 'undo', '--yes', '--json')452	assert undo.code == 0453	if !undo.out.contains(id2) {454		panic('undo JSON did not name ${id2}: ${undo.out}')455	}456	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'457	assert os.exists(os.join_path(dir, 'gone.txt'))458	assert run(dir, 'load', id3, '--yes').code == 0459	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'three\n'460	assert run(dir, 'undo', '2', '--yes').code == 0461	assert run(dir, 'load', id2, '--yes').code == 0462	assert run(dir, 'undo', '99', '--yes').err.contains('nothing before')463	write(dir, 'a.txt', 'dirty\n')464	before := run(dir, 'log')465	refuse := run(dir, 'revert')466	assert refuse.code == 1467	assert refuse.err.contains('needs --yes when not interactive')468	assert run(dir, 'log').out == before.out469	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'dirty\n'470	write(dir, 'untracked.txt', 'remove\n')471	rv := run(dir, 'revert', '--yes')472	assert rv.code == 0473	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'474	assert !os.exists(os.join_path(dir, 'untracked.txt'))475	assert run(dir, 'revert', '--yes').out.contains('working tree already matches')476	assert run(dir, 'load', '--checkpoint', '--yes').code == 0477	assert run(dir, 'load', id2, '--json').code == 1478	assert run(dir, 'load', id2, '--json').err.contains('error')479	assert run(dir, 'load').code == 2480	assert run(dir, 'load', 'unknown-id', '--yes').code == 1481}482483fn test_flag_and_flagged_log() {484	dir := temp_repo('flag')485	defer { os.rmdir_all(dir) or {} }486	init_repo(dir)487	write(dir, 'flag.txt', 'one\n')488	saved := run(dir, 'save', 'flag me', '--json')489	id := saved.out.all_after('"id":"')[..12]490	flagged := run(dir, 'flag', id, '--reason', 'unsafe', '--json')491	assert flagged.code == 0492	assert flagged.out.contains('"flagged":true')493	assert flagged.out.contains('"reason":"unsafe"')494	list := run(dir, 'flag', '--json')495	assert list.code == 0496	assert list.out.contains(id)497	assert list.out.contains('unsafe')498	assert run(dir, 'log').out.contains('⚑')499	assert run(dir, 'flag', '--clear', id).code == 0500	assert run(dir, 'flag').out.contains('nothing is flagged')501	assert run(dir, 'flag', 'unknown-id').code == 1502	assert run(dir, 'flag').code == 0503}504505fn test_pluck_forward_reverse_dry_run_and_conflict() {506	dir := temp_repo('pluck')507	defer { os.rmdir_all(dir) or {} }508	init_repo(dir)509	write(dir, 'a.txt', 'one\n')510	first := run(dir, 'save', 'one', '--json').out511	id1 := first.all_after('"id":"')[..12]512	write(dir, 'a.txt', 'two\n')513	second := run(dir, 'save', 'two', '--json').out514	id2 := second.all_after('"id":"')[..12]515	assert run(dir, 'load', id1, '--yes').code == 0516	dry := run(dir, 'pluck', id2, '--dry-run')517	assert dry.code == 0518	assert dry.out.contains('a.txt')519	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'520	assert run(dir, 'pluck', id2, '--yes').code == 0521	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'522	assert run(dir, 'pluck', '--reverse', id2, '--yes').code == 0523	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'524	write(dir, 'a.txt', 'different\n')525	assert run(dir, 'pluck', id2, '--dry-run').code == 1526	assert run(dir, 'save', 'different').code == 0527	conflict := run(dir, 'pluck', id2, '--yes')528	assert conflict.code == 1529	assert conflict.err.contains('a.txt')530	assert run(dir, 'pluck').code == 2531	assert run(dir, 'pluck', 'unknown-id').code == 1532}533534fn test_peek_and_doctor() {535	dir := temp_repo('peek-doctor')536	defer { os.rmdir_all(dir) or {} }537	init_repo(dir)538	write(dir, 'peek.txt', 'peek me\n')539	assert run(dir, 'save', 'peekable').code == 0540	id := run(dir, 'log', '--json').out.all_after('"id":"')[..12]541	before_log := run(dir, 'log', '--json').out542	peek := run(dir, 'peek', id, '--json')543	assert peek.code == 0544	peek_path := peek.out.all_after('"path":"').before('"')545	assert peek.out.contains('"id":"${id}"')546	assert os.read_file(os.join_path(peek_path, 'peek.txt'))! == 'peek me\n'547	assert run(dir, 'status').out.contains('no changes')548	assert run(dir, 'log', '--json').out == before_log549	assert run(dir, 'peek').code == 2550	assert run(dir, 'peek', 'unknown-id').code == 1551	backup := os.join_path(dir, 'doctor.backup')552	healthy := run(dir, 'doctor')553	assert healthy.code == 0554	assert healthy.out.contains('is sound')555	report := run(dir, 'doctor', '--json')556	assert report.code == 0557	for key in ['problems', 'objects', 'saves', 'checkpoints', 'cached_files', 'peek_folders_removed',558		'backup'] {559		read_json_has(report.out, key)560	}561	backed := run(dir, 'doctor', '--backup', backup)562	assert backed.code == 0563	assert os.exists(backup)564	assert backed.out.contains(backup)565	assert run(dir, 'doctor', '--backup', backup).code == 1566	assert run(dir, 'peek', id, '--json').code == 0567	// A peek made today is left for whoever is reading it.568	kept := run(dir, 'doctor', '--json')569	assert kept.code == 0570	assert os.exists(peek_path)571	os.rmdir_all(peek_path) or {}572}573574fn test_strip_refuses_without_terminal() {575	dir := temp_repo('strip')576	defer { os.rmdir_all(dir) or {} }577	init_repo(dir)578	write(dir, 'secret.txt', 'keep\n')579	assert run(dir, 'save', 'secret').code == 0580	before_log := run(dir, 'log', '--json').out581	refused := run(dir, 'strip', 'secret.txt')582	assert refused.code == 1583	assert refused.err.contains('needs a terminal')584	assert run(dir, 'log', '--json').out == before_log585	assert os.read_file(os.join_path(dir, 'secret.txt'))! == 'keep\n'586	assert run(dir, 'log', '--json').out.contains('secret')587}588589fn test_saves_and_checkpoints_aliases() {590	dir := temp_repo('aliases')591	defer { os.rmdir_all(dir) or {} }592	init_repo(dir)593	write(dir, 'alias.txt', 'one\n')594	assert run(dir, 'save', 'plain save').code == 0595	assert run(dir, 'checkpoint', 'checkpoint save').code == 0596	saves := run(dir, 'saves')597	assert saves.code == 0598	assert saves.out.contains('plain save')599	assert saves.out.contains('checkpoint save')600	checkpoints := run(dir, 'checkpoints')601	assert checkpoints.code == 0602	assert checkpoints.out.contains('checkpoint save')603	assert !checkpoints.out.contains('plain save')604	json_result := run(dir, 'checkpoints', '--json')605	assert json_result.code == 0606	assert json_result.out.contains('"head_id"')607	assert json_result.out.contains('"saves"')608	assert json_result.out.contains('"is_checkpoint":true')609	assert !json_result.out.contains('"is_checkpoint":false')610}611612fn test_remote_configuration_is_isolated_and_atomic() {613	dir := temp_repo('remote')614	home := temp_repo('remote-home')615	defer {616		os.rmdir_all(dir) or {}617		os.rmdir_all(home) or {}618	}619	empty := run_home(dir, home, 'remote', '--json')620	assert empty.code == 0621	assert empty.out.contains('"configured":false')622	target := os.join_path(home, 'remote-store')623	set := run_home(dir, home, 'remote', 'folder', target)624	assert set.code == 0625	assert os.is_dir(target)626	state := run_home(dir, home, 'remote', '--json')627	assert state.code == 0628	assert state.out.contains('"kind":"folder"')629	assert state.out.contains(target)630	assert run_home(dir, home, 'remote', 's3', 'http://127.0.0.1:1', 'bucket', 'region').code == 1631	assert run_home(dir, home, 'remote', '--json').out.contains(target)632	assert run_home(dir, home, 'remote', 's3', 'http://127.0.0.1:1', 'bucket', 'region').err.contains('KOH_ACCESS_KEY')633	assert run_home(dir, home, 'remote', '--forget').code == 0634	assert run_home(dir, home, 'remote', '--json').out.contains('"configured":false')635}636637// A clone belongs to the repo it was stolen from, whatever its folder is638// called later: renaming it must not start a second repo on the remote.639fn test_a_renamed_clone_keeps_offering_to_its_repo() {640	syncroot := temp_repo('rename-clone')641	home := temp_repo('rename-clone-home')642	defer {643		os.rmdir_all(syncroot) or {}644		os.rmdir_all(home) or {}645	}646	remote := os.join_path(syncroot, 'remote')647	a := os.join_path(syncroot, 'A', 'proj')648	b_parent := os.join_path(syncroot, 'B')649	os.mkdir_all(a) or { panic(err) }650	os.mkdir_all(b_parent) or { panic(err) }651	init_repo(a)652	write(a, 'a.txt', 'from A\n')653	assert run_home(a, home, 'remote', 'folder', remote).code == 0654	assert run_home(a, home, 'save', 'A first').code == 0655	assert run_home(b_parent, home, 'steal', 'proj').code == 0656	renamed := os.join_path(b_parent, 'renamed')657	os.mv(os.join_path(b_parent, 'proj'), renamed) or { panic(err) }658	write(renamed, 'b.txt', 'from B\n')659	assert run_home(renamed, home, 'save', 'B first').code == 0660	assert !os.exists(os.join_path(remote, 'renamed'))661	assert run_home(a, home, 'steal').code == 0662	assert os.read_file(os.join_path(a, 'b.txt'))! == 'from B\n'663}664665fn test_offer_steal_folder_remote() {666	syncroot := temp_repo('sync')667	home := temp_repo('sync-home')668	defer {669		os.rmdir_all(syncroot) or {}670		os.rmdir_all(home) or {}671	}672	remote := os.join_path(syncroot, 'remote')673	a := os.join_path(syncroot, 'A', 'proj')674	b_parent := os.join_path(syncroot, 'B')675	os.mkdir_all(a) or { panic(err) }676	os.mkdir_all(b_parent) or { panic(err) }677	init_repo(a)678	write(a, 'a.txt', 'from A\n')679	assert run_home(a, home, 'remote', 'folder', remote).code == 0680	assert run_home(a, home, 'save', 'A first').code == 0681	clone := run_home(b_parent, home, 'steal', 'proj')682	assert clone.code == 0683	b := os.join_path(b_parent, 'proj')684	assert os.read_file(os.join_path(b, 'a.txt'))! == 'from A\n'685	write(b, 'b.txt', 'from B\n')686	assert run_home(b, home, 'save', 'B first').code == 0687	write(a, 'a2.txt', 'second\n')688	assert run_home(a, home, 'save', 'A second').code == 0689	assert run_home(a, home, 'steal').code == 0690	assert os.exists(os.join_path(a, 'b.txt'))691	assert run_home(b_parent, home, 'steal', '--list').out.contains('proj')692	write(a, 'clash.txt', 'base\n')693	assert run_home(a, home, 'save', 'clash base').code == 0694	assert run_home(b, home, 'steal').code == 0695	write(a, 'clash.txt', 'A version\n')696	assert run_home(a, home, 'save', 'A clash').code == 0697	write(b, 'clash.txt', 'B version\n')698	assert run_home(b, home, 'save', 'B clash').code == 0699	refused := run_home(b, home, 'steal')700	assert refused.code == 1701	assert refused.err.contains('--mine') || refused.err.contains('--theirs')702	b_head := run_home(b, home, 'status', '--json').out.all_after('"head_id":"')[..12]703	theirs := run_home(b, home, 'steal', '--theirs', '--json')704	assert theirs.code == 0705	// The pre-combine tree is off the line now; the way back must be named,706	// or an agent without the history view cannot find it.707	assert theirs.out.contains('"previous_head":"${b_head}"')708	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'A version\n'709	assert run_home(b, home, 'load', b_head, '--yes').code == 0710	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'B version\n'711	assert run_home(b, home, 'load', theirs.out.all_after('"head":"')[..12], '--yes').code == 0712	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'A version\n'713	write(a, 'clash.txt', 'A second\n')714	assert run_home(a, home, 'save', 'A second clash').code == 0715	write(b, 'clash.txt', 'B second\n')716	assert run_home(b, home, 'save', 'B second clash').code == 0717	assert run_home(b, home, 'steal', '--mine').code == 0718	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'B second\n'719	assert run_home(b, home, 'log').out.contains('combine: kept mine for')720}721722// A clone brings in the whole history, flags included; both output forms must723// say which saves came in flagged, and why.724fn test_a_clone_reports_flagged_saves() {725	syncroot := temp_repo('clone-flags')726	home := temp_repo('clone-flags-home')727	defer {728		os.rmdir_all(syncroot) or {}729		os.rmdir_all(home) or {}730	}731	a := os.join_path(syncroot, 'A', 'proj')732	os.mkdir_all(a) or { panic(err) }733	init_repo(a)734	assert run_home(a, home, 'remote', 'folder', os.join_path(syncroot, 'remote')).code == 0735	write(a, 'a.txt', 'one\n')736	id := run_home(a, home, 'save', 'risky', '--json').out.all_after('"id":"')[..12]737	assert run_home(a, home, 'flag', id, '--reason', 'broke the build').code == 0738	assert run_home(a, home, 'offer').code == 0739	for name in ['B', 'C'] {740		os.mkdir_all(os.join_path(syncroot, name)) or { panic(err) }741	}742	json_clone := run_home(os.join_path(syncroot, 'B'), home, 'steal', 'proj', '--json')743	assert json_clone.code == 0744	assert json_clone.out.contains('"flagged":["${id}"]')745	text_clone := run_home(os.join_path(syncroot, 'C'), home, 'steal', 'proj')746	assert text_clone.code == 0747	assert text_clone.out.contains('[${id}] came in flagged — broke the build')748}749750// A folder remote on a disk or share that is not mounted is simply not there.751// Creating it would put the saves in a stand-in folder the other machine never752// sees; the offer must say what is wrong instead.753fn test_an_unmounted_folder_remote_is_not_recreated() {754	syncroot := temp_repo('unmounted')755	home := temp_repo('unmounted-home')756	defer {757		os.rmdir_all(syncroot) or {}758		os.rmdir_all(home) or {}759	}760	mount := os.join_path(syncroot, 'nas')761	remote := os.join_path(mount, 'koh')762	a := os.join_path(syncroot, 'proj')763	os.mkdir_all(a) or { panic(err) }764	init_repo(a)765	assert run_home(a, home, 'remote', 'folder', remote).code == 0766	write(a, 'a.txt', 'one\n')767	assert run_home(a, home, 'save', 'first').code == 0768	os.rename(mount, os.join_path(syncroot, 'nas-unplugged')) or { panic(err) }769	os.mkdir(mount) or { panic(err) }770	offered := run_home(a, home, 'offer')771	assert offered.code == 1772	assert offered.err.contains('mounted')773	assert !os.exists(remote)774	write(a, 'a.txt', 'two\n')775	saved := run_home(a, home, 'save', 'second')776	assert saved.code == 0777	assert saved.out.contains('mounted')778	assert !os.exists(remote)779}780781fn test_man_and_koh2_handoff() {782	dir := temp_repo('man')783	home := temp_repo('man-home')784	defer {785		os.rmdir_all(dir) or {}786		os.rmdir_all(home) or {}787	}788	whole := run_home(dir, home, 'man')789	assert whole.code == 0790	assert whole.out.contains('NAME')791	assert whole.out.contains('COMMANDS')792	strip := run_home(dir, home, 'man', 'strip')793	assert strip.code == 0794	assert strip.out.contains('strip')795	assert !strip.out.contains('koh save ')796	assert run_home(dir, home, 'man', 'nonsense').code == 2797	legacy := temp_repo('legacy')798	defer { os.rmdir_all(legacy) or {} }799	os.mkdir_all(os.join_path(legacy, '.koh')) or { panic(err) }800	fake := os.join_path(home, 'bin')801	os.mkdir_all(fake) or { panic(err) }802	fake_koh := os.join_path(fake, 'koh2')803	os.write_file(fake_koh, '#!/bin/sh\nprintf "handoff:%s\\n" "$*"\nexit 7\n') or { panic(err) }804	os.chmod(fake_koh, 0o755) or { panic(err) }805	handoff := run_home_with_path(legacy, home, fake, 'status', '--json')806	assert handoff.code == 7807	assert handoff.out.contains('handoff:status --json')808	// One notice line, on stderr, so koh2's own output stays as it was.809	assert handoff.err.contains('Koh 2 repo')810	assert handoff.err.trim_space().split_into_lines().len == 1811	assert handoff.out.trim_space() == 'handoff:status --json'812}813814fn run_home_with_path(repo string, home string, bin_dir string, args ...string) Result {815	stamp := '${os.getpid()}-${time.now().unix_nano()}'816	base := os.join_path(os.temp_dir(), 'koh3-cli-${stamp}')817	out_path := '${base}.out'818	err_path := '${base}.err'819	code_path := '${base}.code'820	mut command := 'HOME=${q(home)} PATH=${q(bin_dir + ':' + os.getenv('PATH'))} ${q(binary)}'821	for arg in args {822		command += ' ${q(arg)}'823	}824	shell := 'cd ${q(repo)} && ${command} </dev/null >${q(out_path)} 2>${q(err_path)}; printf "%s" $? >${q(code_path)}'825	result := os.execute(shell)826	if result.exit_code != 0 {827		panic('could not run test command: ${result.output}')828	}829	code := os.read_file(code_path) or { panic(err) }830	out := os.read_file(out_path) or { '' }831	err := os.read_file(err_path) or { '' }832	os.rm(out_path) or {}833	os.rm(err_path) or {}834	os.rm(code_path) or {}835	return Result{836		code: code.int()837		out:  out838		err:  err839	}840}841842// --- migration -------------------------------------------------------------843844fn koh2_binary() string {845	return os.find_abs_path_of_executable('koh') or { '' }846}847848// run_koh2 runs the Koh 2 binary in a fixture; its own output is not under849// test here.850fn run_koh2(dir string, command string) {851	os.execute('cd ${q(dir)} && ${command} >/dev/null 2>&1')852}853854fn save_ids(dir string) []string {855	mut ids := []string{}856	for name in os.ls(os.join_path(dir, '.koh', 'snapshots')) or { []string{} } {857		if name.ends_with('.json') {858			ids << name.trim_right('.json')859		}860	}861	ids.sort()862	return ids863}864865fn test_migrate_converts_a_koh2_repo_and_keeps_every_save() {866	koh2 := koh2_binary()867	if koh2 == '' {868		println('skipping the migration tests: koh (Koh 2) is not on PATH')869		return870	}871	dir := temp_repo('migrate')872	defer { os.rmdir_all(dir) or {} }873	home := temp_repo('migrate-home')874	defer { os.rmdir_all(home) or {} }875	run_koh2(dir, '${q(koh2)} init')876	// One file large enough to be an object, one small enough to be inlined.877	write(dir, 'code.txt', 'x'.repeat(700))878	write(dir, 'tiny.txt', 'tiny\n')879	run_koh2(dir, '${q(koh2)} save "first save"')880	run_koh2(dir, '${q(koh2)} checkpoint "before something"')881	write(dir, 'code.txt', 'y'.repeat(700))882	run_koh2(dir, '${q(koh2)} save "second save"')883	original := save_ids(dir)884	assert original.len == 3885886	report := run_home(dir, home, 'migrate')887	assert report.code == 0888	assert report.out.contains('migrated 3 saves')889	// The swap: `.koh` is a file, the old data is archived, nothing is staging.890	assert os.is_file(os.join_path(dir, '.koh'))891	assert os.is_dir(os.join_path(dir, '.koh-v2'))892	assert os.is_file(os.join_path(dir, '.kohignore'))893	assert !os.exists(os.join_path(dir, '.koh-migrate'))894895	// Every save kept its original ID, and the new repo is sound.896	logged := run_home(dir, home, 'log', '--json')897	assert logged.code == 0898	for id in original {899		assert logged.out.contains(id)900	}901	assert run_home(dir, home, 'doctor').code == 0902	assert run_home(dir, home, 'status').code == 0903904	// Migrating again has nothing to convert.905	assert run_home(dir, home, 'migrate').code == 1906}907908fn test_migrate_refuses_a_tree_that_does_not_match_the_last_save() {909	koh2 := koh2_binary()910	if koh2 == '' {911		return912	}913	dir := temp_repo('migrate-dirty')914	defer { os.rmdir_all(dir) or {} }915	home := temp_repo('migrate-dirty-home')916	defer { os.rmdir_all(home) or {} }917	run_koh2(dir, '${q(koh2)} init')918	write(dir, 'code.txt', 'x'.repeat(700))919	run_koh2(dir, '${q(koh2)} save "only save"')920	write(dir, 'code.txt', 'unsaved change\n')921922	refused := run_home(dir, home, 'migrate')923	assert refused.code == 1924	assert refused.err.contains('save with koh2 first')925	// Nothing moved: still Koh 2, no archive, no staging file.926	assert os.is_dir(os.join_path(dir, '.koh'))927	assert !os.exists(os.join_path(dir, '.koh-v2'))928	assert !os.exists(os.join_path(dir, '.koh-migrate'))929}930931// Koh 2 never saved a root `.kohconfig`, root `.kohignore.<remote>` rules or932// `*.bundle` files, so a clean Koh 2 repo may hold them. Most real repos have933// a `.kohconfig`; migrate must not call them unsaved work.934fn test_migrate_passes_over_the_files_koh2_never_saved() {935	koh2 := koh2_binary()936	if koh2 == '' {937		return938	}939	dir := temp_repo('migrate-koh2-ignores')940	defer { os.rmdir_all(dir) or {} }941	home := temp_repo('migrate-koh2-ignores-home')942	defer { os.rmdir_all(home) or {} }943	run_koh2(dir, '${q(koh2)} init')944	write(dir, 'code.txt', 'x'.repeat(700))945	run_koh2(dir, '${q(koh2)} save "only save"')946	write(dir, '.kohconfig', 'stable_days = 14\n')947	write(dir, '.kohignore.public', 'private/\n')948	write(dir, 'lib/app.bundle', 'bundle\n')949	write(dir, 'ios/Settings.bundle/Root.plist', 'settings\n')950	// Koh 2 keeps saving a file under a folder pattern added later, where951	// Koh 3 reads the same rule as covering the folder: the saved file is on952	// disk and matches, so the tree is clean.953	write(dir, 'native/t.dSYM/Info.plist', 'plist\n')954	run_koh2(dir, '${q(koh2)} save --agent test --session test "add the dsym"')955	// Koh 2 skips *.bundle even when its rules no longer list it.956	ignore_path := os.join_path(dir, '.koh', 'ignore')957	rules := os.read_file(ignore_path)!.split_into_lines().filter(it != '*.bundle')958	os.write_file(ignore_path, rules.join('\n') + '\nnative/*.dSYM\n')!959	// A saved file the walk skips still has to match what was saved.960	write(dir, 'native/t.dSYM/Info.plist', 'changed\n')961	changed := run_home(dir, home, 'migrate')962	assert changed.code == 1963	assert changed.err.contains('native/t.dSYM/Info.plist does not match')964	write(dir, 'native/t.dSYM/Info.plist', 'plist\n')965	assert os.execute('cd ${q(dir)} && ${q(koh2)} status --json').output.contains('"dirty":false')966967	migrated := run_home(dir, home, 'migrate')968	assert migrated.code == 0, migrated.err969	// They stay where they were, for the user to keep or delete.970	assert os.read_file(os.join_path(dir, '.kohconfig'))! == 'stable_days = 14\n'971}