Skip to content
suit Artifact [20f1dc97dc]
Login

Artifact [20f1dc97dc]

Artifact 20f1dc97dc3079aa7c66167f6a8fd7e5dfbbfb2426fb9376756297402442dc70:


#!/bin/sh
# Shell tests for the store: open, status, commit, update, back. They run on
# test/fixtures/wardrobe.fossil, so they need no stock fossil; the cases that
# compare against stock fossil say so and skip when it is not installed.
# SUIT names the binary under test (default build/dev/suit).

SUIT=${SUIT:-build/dev/suit}
case $SUIT in /*) ;; *) SUIT=$PWD/$SUIT ;; esac
ROOT=$PWD
FIXTURE=$ROOT/test/fixtures/wardrobe.fossil
LINKS=$ROOT/test/fixtures/wardrobe-link.fossil
LINKS_V1=$ROOT/test/fixtures/wardrobe-link-v1.fossil
mkdir -p build/tmp
T=$(mktemp -d "$ROOT/build/tmp/store.XXXXXX") || exit 1
trap 'rm -rf "$T"' EXIT INT TERM

total=0
failed=0
pass() { total=$((total + 1)); echo "ok $1"; }
bad() {
    total=$((total + 1)); failed=$((failed + 1))
    echo "FAIL $1${2:+: $2}"
}
skip() { echo "skip $1: $2"; }
have_fossil() { command -v fossil >/dev/null 2>&1; }

export USER=tester
unset LOGNAME

# check NAME WANT_RC [STDERR_SUBSTRING] -- COMMAND...   (output in $T/out, $T/err)
check() {
    cname=$1; cwant=$2; cmsg=$3; shift 4
    "$@" >"$T/out" 2>"$T/err"; crc=$?
    if [ "$crc" != "$cwant" ]; then bad "$cname" "exit $crc, want $cwant: $(cat "$T/err")"
    elif [ -n "$cmsg" ] && ! grep -qF -- "$cmsg" "$T/err"; then bad "$cname" "want '$cmsg' in: $(cat "$T/err")"
    else pass "$cname"; fi
}

# fresh NAME: a new SUIT_HOME with the fixture wardrobe as NAME
fresh() {
    rm -rf "$T/home"
    mkdir -p "$T/home/wardrobes"
    cp "$FIXTURE" "$T/home/wardrobes/$1.fossil"
    export SUIT_HOME="$T/home"
}

# tree DIR: every file with its content sum and mode bits, to compare two trees
tree() {
    (cd "$1" && find . \( -name .fslckout -o -name '.suit-tmp.*' \) -prune -o -type f -print | sort | while read -r f; do
        if [ -x "$f" ]; then m=x; else m=-; fi
        printf '%s %s %s\n' "$f" "$(cksum < "$f")" "$m"
    done)
}

store=$T/home/store

# fan FUNC NAME...: FUNC NAME in a subshell of its own for each NAME, up to
# TEST_JOBS at a time (default 1: one after another); each one's output goes
# to $T/fan/FUNC.NAME. fan_show prints those files in order and counts their
# ok and FAIL lines, since a subshell's counters are lost.
fan() {
    ffn=$1; shift; mkdir -p "$T/fan"; fq=; fall=
    for fnm in "$@"; do
        if [ "${TEST_JOBS:-1}" -le 1 ]; then ( "$ffn" "$fnm" ) >"$T/fan/$ffn.$fnm" 2>&1; continue; fi
        if [ "$(set -- $fq; echo $#)" -ge "$TEST_JOBS" ]; then
            ffirst=${fq%% *}; wait "$ffirst"; fq=${fq#"$ffirst"}; fq=${fq# }
        fi
        ( "$ffn" "$fnm" ) >"$T/fan/$ffn.$fnm" 2>&1 &
        fq=${fq:+$fq }$!; fall="$fall $!"
    done
    # not a bare wait: the http server's deadline timer is also a child
    [ -z "$fall" ] || wait $fall
}
fan_show() {
    ffn=$1; shift
    for fnm in "$@"; do
        cat "$T/fan/$ffn.$fnm"
        total=$((total + $(grep -c '^ok ' "$T/fan/$ffn.$fnm") + $(grep -c '^FAIL ' "$T/fan/$ffn.$fnm")))
        failed=$((failed + $(grep -c '^FAIL ' "$T/fan/$ffn.$fnm")))
    done
}

# ---- open -------------------------------------------------------------------

fresh wd
check open-new-store 0 "" -- "$SUIT" store open wd
tree "$store/wd" > "$T/tree1"
if [ "$(wc -l < "$T/tree1" | tr -d ' ')" = 4 ] && grep -q "^./run.sh .* x$" "$T/tree1" && grep -q "^./skills/gamma.md .* -$" "$T/tree1" && [ ! -e "$store/wd/skills/beta" ]; then pass open-extracts-tip-files-and-modes; else bad open-extracts-tip-files-and-modes "$(cat "$T/tree1")"; fi
[ "$(cat "$store/wd/skills/alpha/SKILL.md")" = "alpha v2" ] && pass open-file-contents || bad open-file-contents
check open-twice-is-idempotent 0 "" -- "$SUIT" store open wd
tree "$store/wd" > "$T/tree2"
cmp -s "$T/tree1" "$T/tree2" && pass open-twice-changes-nothing || bad open-twice-changes-nothing
check status-clean-after-open 0 "" -- "$SUIT" store status wd
[ ! -s "$T/out" ] && pass status-clean-prints-nothing || bad status-clean-prints-nothing "$(cat "$T/out")"

check open-bad-name 2 "is not a wardrobe name" -- "$SUIT" store open 'bad/name'
check open-empty-name 2 "is not a wardrobe name" -- "$SUIT" store open ''
check open-no-such-wardrobe 1 "no wardrobe at $T/home/wardrobes/nosuch.fossil" -- "$SUIT" store open nosuch
check open-no-user 1 "cannot tell who you are" -- env -u USER -u LOGNAME "$SUIT" store open wd
check open-empty-user 1 "cannot tell who you are" -- env USER= "$SUIT" store open wd
check open-empty-user-and-logname 1 "cannot tell who you are" -- env USER= LOGNAME= "$SUIT" store open wd
check open-user-from-logname 0 "" -- env -u USER LOGNAME=other "$SUIT" store open wd
check open-no-home-at-all 1 "neither SUIT_HOME nor HOME is set" -- env -u SUIT_HOME -u HOME "$SUIT" store open wd

# -- the folders open makes
for n in 1 2 3; do
    fresh wd
    check "open-mkdir-$n-fails" 1 "cannot create" -- env SUIT_FAULT=mkdir:$n:EACCES "$SUIT" store open wd
done

# -- a wardrobe that is not one
fresh wd
printf 'this is not a database' > "$T/home/wardrobes/wd.fossil"
check open-corrupt-wardrobe 1 "store wd: open the wardrobe failed" -- "$SUIT" store open wd
fresh wd
: > "$T/home/wardrobes/wd.fossil"
check open-empty-wardrobe-file 1 "failed" -- "$SUIT" store open wd

# -- an open that stops part way is finished by the next one
fresh wd
check open-stops-at-first-file-write 1 "extract the files failed" -- env SUIT_FAULT=rename:2 "$SUIT" store open wd
check open-resumes-after-a-stop 0 "" -- "$SUIT" store open wd
tree "$store/wd" > "$T/tree3"
cmp -s "$T/tree1" "$T/tree3" && pass open-resume-matches-fresh-open || bad open-resume-matches-fresh-open "$(diff "$T/tree1" "$T/tree3")"
check status-clean-after-resume 0 "" -- "$SUIT" store status wd
[ ! -s "$T/out" ] && pass status-clean-after-resume-prints-nothing || bad status-clean-after-resume-prints-nothing "$(cat "$T/out")"
if ls "$store/wd"/.suit-tmp.* "$store/wd"/*/.suit-tmp.* >/dev/null 2>&1; then bad failed-open-leaves-no-temp-file; else pass failed-open-leaves-no-temp-file; fi

# ---- status ------------------------------------------------------------------

fresh wd
"$SUIT" store open wd >/dev/null 2>&1
cp "$FIXTURE" "$T/home/wardrobes/other.fossil"
check status-before-open 1 "open the working copy failed" -- "$SUIT" store status other
printf -- '---\nedited\n' > "$store/wd/skills/alpha/SKILL.md"
printf 'new\n' > "$store/wd/skills/delta.md"
mkdir -p "$store/wd/newdir/deeper"
printf 'deep\n' > "$store/wd/newdir/deeper/file.md"
rm "$store/wd/agents/reviewer.md"
chmod -x "$store/wd/run.sh"
"$SUIT" store status wd > "$T/status" 2>"$T/err"; rc=$?
sort "$T/status" > "$T/status.sorted"
want='added newdir/deeper/file.md
added skills/delta.md
deleted agents/reviewer.md
edited run.sh
edited skills/alpha/SKILL.md'
if [ $rc -eq 0 ] && [ "$(cat "$T/status.sorted")" = "$want" ]; then pass status-lists-edits-additions-deletions; else bad status-lists-edits-additions-deletions "rc $rc: $(cat "$T/status")"; fi
"$SUIT" store status wd > "$T/status2" 2>/dev/null
sort "$T/status2" | cmp -s - "$T/status.sorted" && pass status-twice-is-the-same || bad status-twice-is-the-same
# status looks and changes nothing: an untracked file stays untracked
printf 'x\n' > "$T/probe"
printf 'tmp\n' > "$store/wd/.suit-tmp.123.4"
"$SUIT" store status wd 2>/dev/null | grep -q suit-tmp && bad status-hides-our-temp-names || pass status-hides-our-temp-names
rm -f "$store/wd/.suit-tmp.123.4"

# ---- commit ------------------------------------------------------------------

check commit-everything 0 "" -- "$SUIT" commit wd -m "local work"
grep -q "^checked in [0-9a-f]\{12\}$" "$T/out" && pass commit-says-what-it-did || bad commit-says-what-it-did "$(cat "$T/out")"
check status-clean-after-commit 0 "" -- "$SUIT" store status wd
[ ! -s "$T/out" ] && pass status-after-commit-prints-nothing || bad status-after-commit-prints-nothing "$(cat "$T/out")"
check commit-clean-does-nothing 0 "" -- "$SUIT" commit wd -m "nothing"
[ ! -s "$T/out" ] && pass commit-clean-prints-nothing || bad commit-clean-prints-nothing
printf 'more\n' >> "$store/wd/run.sh"
check commit-empty-message-fails-on-real-changes 1 "check in failed" -- "$SUIT" commit wd -m ""
check commit-usage-no-message 2 "usage" -- "$SUIT" commit wd
check commit-usage-wrong-flag 2 "usage" -- "$SUIT" commit wd -x text
check store-usage-missing-name 2 "usage" -- "$SUIT" store open
check store-usage-unknown-verb 2 "usage" -- "$SUIT" store frobnicate wd
check back-usage 2 "usage" -- "$SUIT" back
cp "$FIXTURE" "$T/home/wardrobes/nowhere.fossil"
check store-commit-before-open 1 "open the working copy failed" -- "$SUIT" commit nowhere -m x

# ---- update ------------------------------------------------------------------
# Two stores on one repository file: y is behind, x makes the next version.

fresh x
ln -s x.fossil "$T/home/wardrobes/y.fossil"
"$SUIT" store open x >/dev/null 2>&1
"$SUIT" store open y >/dev/null 2>&1
printf -- '---\nalpha v3\n' > "$store/x/skills/alpha/SKILL.md"
printf 'epsilon v3\n' > "$store/x/skills/epsilon.md"
rm "$store/x/skills/gamma.md"
chmod +x "$store/x/skills/epsilon.md"
"$SUIT" commit x -m "third" >/dev/null 2>&1
tree "$store/y" > "$T/y-before"

check update-conflict-with-an-untracked-file 13 "" -- sh -c 'printf "mine\n" > "$1/skills/epsilon.md"; "$2" store update y' sh "$store/y" "$SUIT"
if [ "$(cat "$T/out")" = "conflict skills/epsilon.md" ]; then pass update-conflict-names-the-file; else bad update-conflict-names-the-file "$(cat "$T/out")"; fi
rm "$store/y/skills/epsilon.md"
tree "$store/y" > "$T/y-after-conflict"
cmp -s "$T/y-before" "$T/y-after-conflict" && pass update-conflict-changes-nothing || bad update-conflict-changes-nothing

printf 'local edit\n' > "$store/y/agents/reviewer.md"
check update-refuses-with-local-changes 12 "" -- "$SUIT" store update y
[ "$(cat "$T/out")" = "edited agents/reviewer.md" ] && pass update-refusal-lists-the-files || bad update-refusal-lists-the-files "$(cat "$T/out")"
check update-refuses-with-a-deleted-file 12 "" -- sh -c 'cp "$1/agents/reviewer.md" "$1/keep"; rm "$1/agents/reviewer.md"; "$2" store update y' sh "$store/y" "$SUIT"
grep -q "^deleted agents/reviewer.md$" "$T/out" && pass update-refusal-lists-deletions || bad update-refusal-lists-deletions "$(cat "$T/out")"

# Start clean for the cases that update.
fresh x
ln -s x.fossil "$T/home/wardrobes/y.fossil"
"$SUIT" store open x >/dev/null 2>&1
"$SUIT" store open y >/dev/null 2>&1
printf -- '---\nalpha v3\n' > "$store/x/skills/alpha/SKILL.md"
printf 'epsilon v3\n' > "$store/x/skills/epsilon.md"
rm "$store/x/skills/gamma.md"
chmod +x "$store/x/skills/epsilon.md"
printf '#!/bin/sh\necho v3\n' > "$store/x/run.sh"
"$SUIT" commit x -m "third" >/dev/null 2>&1
tree "$store/y" > "$T/y-v2"
check update-to-new-tip 0 "" -- "$SUIT" store update y
grep -q "^updated to [0-9a-f]\{12\}$" "$T/out" && pass update-says-the-version || bad update-says-the-version "$(cat "$T/out")"
tree "$store/y" > "$T/y-v3"
tree "$store/x" > "$T/x-v3"
cmp -s "$T/y-v3" "$T/x-v3" && pass update-makes-y-identical-to-x || bad update-makes-y-identical-to-x "$(diff "$T/y-v3" "$T/x-v3")"
grep -q "^./skills/epsilon.md .* x$" "$T/y-v3" && grep -q "^./run.sh .* x$" "$T/y-v3" && [ ! -e "$store/y/skills/gamma.md" ] && pass update-adds-removes-and-keeps-modes || bad update-adds-removes-and-keeps-modes
check status-clean-after-update 0 "" -- "$SUIT" store status y
[ ! -s "$T/out" ] && pass status-after-update-prints-nothing || bad status-after-update-prints-nothing "$(cat "$T/out")"
check update-at-the-tip 0 "" -- "$SUIT" store update y
tree "$store/y" > "$T/y-v3b"
cmp -s "$T/y-v3" "$T/y-v3b" && pass update-at-the-tip-changes-nothing || bad update-at-the-tip-changes-nothing

# -- back
check back-after-update 0 "" -- "$SUIT" back y
grep -q "^back at [0-9a-f]\{12\}$" "$T/out" && pass back-says-the-version || bad back-says-the-version "$(cat "$T/out")"
tree "$store/y" > "$T/y-back"
cmp -s "$T/y-v2" "$T/y-back" && pass back-restores-the-previous-bytes-and-modes || bad back-restores-the-previous-bytes-and-modes "$(diff "$T/y-v2" "$T/y-back")"
check status-clean-after-back 0 "" -- "$SUIT" store status y
[ ! -s "$T/out" ] && pass status-after-back-prints-nothing || bad status-after-back-prints-nothing "$(cat "$T/out")"
check back-twice-has-nothing 14 "nothing to go back to" -- "$SUIT" back y
check update-again-after-back 0 "" -- "$SUIT" store update y
tree "$store/y" > "$T/y-v3c"
cmp -s "$T/y-v3" "$T/y-v3c" && pass update-after-back-reaches-the-tip-again || bad update-after-back-reaches-the-tip-again
printf 'after\n' >> "$store/y/run.sh"
"$SUIT" commit y -m "y moves on" >/dev/null 2>&1
check back-after-a-commit 14 "cannot go back: the store has changed since the update" -- "$SUIT" back y

# -- an update that fails part way puts every file back
fresh x
ln -s x.fossil "$T/home/wardrobes/y.fossil"
"$SUIT" store open x >/dev/null 2>&1
"$SUIT" store open y >/dev/null 2>&1
for f in skills/alpha/SKILL.md skills/gamma.md agents/reviewer.md; do printf -- '---\nv3 of %s\n' "$f" > "$store/x/$f"; done
"$SUIT" commit x -m third >/dev/null 2>&1
tree "$store/y" > "$T/y-v2"
check update-stops-when-a-write-fails 1 "update failed" -- env SUIT_FAULT=rename:3 "$SUIT" store update y
grep -q "the files are back at the version they were at" "$T/err" && pass update-failure-puts-files-back || bad update-failure-puts-files-back "$(cat "$T/err")"
tree "$store/y" > "$T/y-failed"
cmp -s "$T/y-v2" "$T/y-failed" && pass update-failure-leaves-old-bytes || bad update-failure-leaves-old-bytes "$(diff "$T/y-v2" "$T/y-failed")"
if ls "$store/y"/.suit-tmp.* "$store/y"/*/.suit-tmp.* >/dev/null 2>&1; then bad update-failure-leaves-no-temp-file; else pass update-failure-leaves-no-temp-file; fi
check status-clean-after-failed-update 0 "" -- "$SUIT" store status y
[ ! -s "$T/out" ] && pass status-after-failed-update-prints-nothing || bad status-after-failed-update-prints-nothing "$(cat "$T/out")"
check update-and-put-back-both-fail 1 "could not put the files back" -- env SUIT_FAULT=rename:3,rename:4 "$SUIT" store update y

# -- repair after the update and the put-back both failed
[ -f "$T/home/y.journal" ] && pass failed-put-back-leaves-a-journal || bad failed-put-back-leaves-a-journal
cp "$T/home/y.journal" "$T/journal.good"
tree "$store/y" > "$T/y-half"
cmp -s "$T/y-v2" "$T/y-half" && bad store-is-half-updated "the files did not change" || pass store-is-half-updated
for cmd in "store status y" "store open y" "store update y" "commit y -m x" "back y"; do
    # shellcheck disable=SC2086
    check "journal-stops-[$cmd]" 15 "store y has an unfinished update; run \`suit store repair y\`" -- "$SUIT" $cmd
done
check repair-after-double-failure 0 "" -- "$SUIT" store repair y
grep -q "^repaired; back at [0-9a-f]\{12\}$" "$T/out" && pass repair-says-the-version || bad repair-says-the-version "$(cat "$T/out")"
tree "$store/y" > "$T/y-repaired"
cmp -s "$T/y-v2" "$T/y-repaired" && pass repair-restores-the-old-bytes || bad repair-restores-the-old-bytes "$(diff "$T/y-v2" "$T/y-repaired")"
[ ! -e "$T/home/y.journal" ] && pass repair-removes-the-journal || bad repair-removes-the-journal
check status-clean-after-repair 0 "" -- "$SUIT" store status y
[ ! -s "$T/out" ] && pass status-after-repair-prints-nothing || bad status-after-repair-prints-nothing "$(cat "$T/out")"
check repair-twice-is-a-no-op 0 "" -- "$SUIT" store repair y
[ "$(cat "$T/out")" = "nothing to repair" ] && pass second-repair-says-nothing-to-repair || bad second-repair-says-nothing-to-repair "$(cat "$T/out")"
tree "$store/y" > "$T/y-repaired2"
cmp -s "$T/y-repaired" "$T/y-repaired2" && pass second-repair-changes-nothing || bad second-repair-changes-nothing
check update-after-repair 0 "" -- "$SUIT" store update y
tree "$store/x" > "$T/x-now"; tree "$store/y" > "$T/y-now"
cmp -s "$T/x-now" "$T/y-now" && pass update-after-repair-reaches-the-new-version || bad update-after-repair-reaches-the-new-version

# -- repair without a journal never throws edits away
printf 'my edit\n' > "$store/y/agents/reviewer.md"
check repair-refuses-local-edits 12 "" -- "$SUIT" store repair y
[ "$(cat "$T/out")" = "edited agents/reviewer.md" ] && pass repair-refusal-lists-the-edits || bad repair-refusal-lists-the-edits "$(cat "$T/out")"
[ "$(cat "$store/y/agents/reviewer.md")" = "my edit" ] && pass repair-refusal-keeps-the-edit || bad repair-refusal-keeps-the-edit

# -- the journal, read badly
write_journal() { cp "$T/journal.good" "$T/home/y.journal"; }
write_journal
# The C library words errno 5 its own way (glibc and macOS spell it out,
# musl shortens it). Ask the binary under test.
EIO=$(SUIT_FAULT=open:1 "$SUIT" check test/fixtures/example.conf 2>&1 | sed -n 's/.*cannot open: //p')
[ -n "$EIO" ] || { echo "FAIL cannot learn the errno wording"; exit 1; }
check repair-journal-open-fails 1 "cannot read $T/home/y.journal: $EIO" -- env SUIT_FAULT=open:1 "$SUIT" store repair y
check repair-journal-read-fails 1 "could not be read: $EIO" -- env SUIT_FAULT=read:1 "$SUIT" store repair y
printf 'garbage' > "$T/home/y.journal"
check repair-damaged-journal 1 "is damaged" -- "$SUIT" store repair y
awk 'BEGIN { for (i = 0; i < 40; i++) printf "from-this-is-not-a-journal-line-%d\n", i }' > "$T/home/y.journal"
check repair-oversized-journal 1 "is damaged" -- "$SUIT" store repair y
printf 'from ffffffffffffffffffffffffffffffffffffffff\nto ffffffffffffffffffffffffffffffffffffffff\n' > "$T/home/y.journal"
check repair-journal-names-an-unknown-version 1 "names a version this wardrobe does not have" -- "$SUIT" store repair y
write_journal
check repair-journal-read-interrupted-retries 0 "" -- env SUIT_FAULT=read:1:EINTR "$SUIT" store repair y
write_journal
check repair-journal-short-reads 0 "" -- env SUIT_FAULT=read:1:short "$SUIT" store repair y
[ ! -e "$T/home/y.journal" ] && pass repair-after-a-good-journal-removes-it || bad repair-after-a-good-journal-removes-it
check update-cannot-write-the-journal 1 "cannot write $T/home/y.journal: $EIO" -- env SUIT_FAULT=open:1 "$SUIT" store update y
[ ! -e "$T/home/y.journal" ] && pass failed-journal-write-leaves-no-journal || bad failed-journal-write-leaves-no-journal

# -- a crash in the middle of an update, then repair
fresh x
ln -s x.fossil "$T/home/wardrobes/y.fossil"
"$SUIT" store open x >/dev/null 2>&1
"$SUIT" store open y >/dev/null 2>&1
mkdir -p "$store/x/many"
i=0
while [ $i -lt 100 ]; do printf 'old %d\n' $i > "$store/x/many/f$i"; i=$((i + 1)); done
"$SUIT" commit x -m many >/dev/null 2>&1
"$SUIT" store update y >/dev/null 2>&1
i=0
while [ $i -lt 100 ]; do printf 'new %d\n' $i > "$store/x/many/f$i"; i=$((i + 1)); done
"$SUIT" commit x -m many2 >/dev/null 2>&1
tree "$store/y" > "$T/y-pre-crash"
SUIT_FAULT=rename:2:delay "$SUIT" store update y >/dev/null 2>&1 &
victim=$!
i=0
while [ ! -f "$T/home/y.journal" ] && [ $i -lt 400 ]; do sleep 0.05; i=$((i + 1)); done
sleep 0.5
kill -9 "$victim" 2>/dev/null
wait "$victim" 2>/dev/null
[ -f "$T/home/y.journal" ] && pass killed-update-leaves-its-journal || bad killed-update-leaves-its-journal
tree "$store/y" > "$T/y-crashed"
cmp -s "$T/y-pre-crash" "$T/y-crashed" && bad killed-update-had-started "no file had changed" || pass killed-update-had-started
check killed-update-blocks-status 15 "unfinished update" -- "$SUIT" store status y
check repair-after-kill 0 "" -- "$SUIT" store repair y
tree "$store/y" > "$T/y-after-kill"
cmp -s "$T/y-pre-crash" "$T/y-after-kill" && pass repair-after-kill-restores-the-old-bytes || bad repair-after-kill-restores-the-old-bytes "$(diff "$T/y-pre-crash" "$T/y-after-kill" | head -4)"
check status-clean-after-kill-and-repair 0 "" -- "$SUIT" store status y
[ ! -s "$T/out" ] && pass status-after-kill-and-repair-prints-nothing || bad status-after-kill-and-repair-prints-nothing "$(cat "$T/out")"
check update-after-kill-and-repair 0 "" -- "$SUIT" store update y
tree "$store/x" > "$T/x-after"; tree "$store/y" > "$T/y-after"
cmp -s "$T/x-after" "$T/y-after" && pass update-after-kill-and-repair-reaches-the-new-version || bad update-after-kill-and-repair-reaches-the-new-version

# -- symlinks are refused, with the path
rm -rf "$T/home"; mkdir -p "$T/home/wardrobes"; export SUIT_HOME="$T/home"
cp "$LINKS" "$T/home/wardrobes/ln.fossil"
check open-refuses-a-version-with-a-symlink 16 "this version of the wardrobe has a symlink at link.md; symlinks are not supported" -- "$SUIT" store open ln
[ ! -e "$store/ln/skills" ] && pass refused-open-extracts-nothing || bad refused-open-extracts-nothing
cp "$LINKS_V1" "$T/home/wardrobes/zz.fossil"
"$SUIT" store open zz >/dev/null 2>&1
cp "$LINKS" "$T/home/wardrobes/zz.fossil"
tree "$store/zz" > "$T/zz-before"
check update-refuses-a-version-with-a-symlink 16 "has a symlink at link.md" -- "$SUIT" store update zz
tree "$store/zz" > "$T/zz-after"
cmp -s "$T/zz-before" "$T/zz-after" && pass refused-update-changes-nothing || bad refused-update-changes-nothing
[ ! -e "$T/home/zz.journal" ] && pass refused-update-writes-no-journal || bad refused-update-writes-no-journal

fresh wd
"$SUIT" store open wd >/dev/null 2>&1
ln -s agents/reviewer.md "$store/wd/skills/ref.md"
mkdir -p "$store/wd/sub/deep"
ln -s ../../run.sh "$store/wd/sub/deep/runlink"
ln -s agents "$store/wd/dirlink"
printf 'a real change\n' > "$store/wd/skills/gamma.md"
check commit-refuses-symlinks 3 "dirlink: symlink, not supported" -- "$SUIT" commit wd -m links
grep -qF "skills/ref.md: symlink, not supported" "$T/err" && grep -qF "sub/deep/runlink: symlink, not supported" "$T/err" && pass commit-names-every-symlink || bad commit-names-every-symlink "$(cat "$T/err")"
"$SUIT" store status wd 2>/dev/null | grep -q "^edited skills/gamma.md$" && pass refused-commit-keeps-the-change || bad refused-commit-keeps-the-change
rm "$store/wd/skills/ref.md" "$store/wd/sub/deep/runlink" "$store/wd/dirlink"
check commit-after-removing-the-symlinks 0 "" -- "$SUIT" commit wd -m "no links now"
deep=$store/wd
i=0; while [ $i -lt 70 ]; do deep=$deep/d; i=$((i + 1)); done
mkdir -p "$deep"
check commit-refuses-folders-nested-too-deep 1 "are nested more than 64 deep" -- "$SUIT" commit wd -m deep
rm -rf "$store/wd/d"

for spec in open:2 write:2 fsync:2 close:2; do
    fresh x
    ln -s x.fossil "$T/home/wardrobes/y.fossil"
    "$SUIT" store open x >/dev/null 2>&1
    "$SUIT" store open y >/dev/null 2>&1
    printf -- '---\nv3\n' > "$store/x/skills/alpha/SKILL.md"
    "$SUIT" commit x -m third >/dev/null 2>&1
    tree "$store/y" > "$T/y-pre"
    SUIT_FAULT=$spec "$SUIT" store update y >/dev/null 2>&1; rc=$?
    tree "$store/y" > "$T/y-post"
    if [ $rc -ne 1 ] || ! cmp -s "$T/y-pre" "$T/y-post"; then bad "update-fault-${spec%%:*}-keeps-old-bytes" "rc $rc"; else pass "update-fault-${spec%%:*}-keeps-old-bytes"; fi
done

# -- no reader ever sees half a file
files=150
fresh x
ln -s x.fossil "$T/home/wardrobes/y.fossil"
"$SUIT" store open x >/dev/null 2>&1
"$SUIT" store open y >/dev/null 2>&1
mkdir -p "$store/x/many"
i=0
while [ $i -lt $files ]; do
    awk -v n=$i 'BEGIN { for (k = 0; k < 400; k++) printf "old content of file %d line %d\n", n, k }' > "$store/x/many/f$i"
    i=$((i + 1))
done
"$SUIT" commit x -m many >/dev/null 2>&1
"$SUIT" store update y >/dev/null 2>&1
i=0; : > "$T/old"; : > "$T/new"
while [ $i -lt $files ]; do
    cksum < "$store/y/many/f$i" | sed "s/^/f$i /" >> "$T/old"
    awk -v n=$i 'BEGIN { for (k = 0; k < 400; k++) printf "new content of file %d line %d\n", n, k }' > "$store/x/many/f$i"
    i=$((i + 1))
done
"$SUIT" commit x -m many2 >/dev/null 2>&1
i=0
while [ $i -lt $files ]; do
    cksum < "$store/x/many/f$i" | sed "s/^/f$i /" >> "$T/new"
    i=$((i + 1))
done
# One rename in 20 ms, so the update takes seconds and a reader has time to look.
SUIT_FAULT=rename:1:delay "$SUIT" store update y >/dev/null 2>&1 &
updater=$!
seen_old=0; seen_new=0; wrong=0; rounds=0
while kill -0 "$updater" 2>/dev/null && [ $rounds -lt 400 ]; do
    i=0
    while [ $i -lt $files ]; do
        line="f$i $(cksum < "$store/y/many/f$i" 2>/dev/null)"
        if grep -qxF -- "$line" "$T/old"; then seen_old=$((seen_old + 1))
        elif grep -qxF -- "$line" "$T/new"; then seen_new=$((seen_new + 1))
        else wrong=$((wrong + 1)); fi
        i=$((i + 1))
    done
    rounds=$((rounds + 1))
done
wait "$updater"; urc=$?
if [ "$urc" -eq 0 ] && [ "$wrong" -eq 0 ] && [ "$seen_old" -gt 0 ] && [ "$seen_new" -gt 0 ]; then pass reader-never-sees-a-half-written-file; else bad reader-never-sees-a-half-written-file "update $urc, $wrong half-written reads, $seen_old old, $seen_new new"; fi
echo "   (a reader looked $((seen_old + seen_new + wrong)) times: $seen_old old, $seen_new new, $wrong neither)"
tree "$store/y" > "$T/y-many"
tree "$store/x" > "$T/x-many"
cmp -s "$T/y-many" "$T/x-many" && pass concurrent-update-ends-identical-to-source || bad concurrent-update-ends-identical-to-source

# ---- stock fossil ------------------------------------------------------------

if have_fossil; then
    # A check-in made by suit is readable by stock fossil.
    fresh wd
    "$SUIT" store open wd >/dev/null 2>&1
    printf -- '---\nfossil reads this\n' > "$store/wd/skills/alpha/SKILL.md"
    printf 'new file\n' > "$store/wd/skills/zeta.md"
    "$SUIT" commit wd -m "made by suit" >/dev/null 2>&1
    R=$T/home/wardrobes/wd.fossil
    if fossil timeline -R "$R" -n 3 2>/dev/null | grep -q "made by suit (user: tester"; then pass fossil-timeline-shows-the-checkin; else bad fossil-timeline-shows-the-checkin; fi
    [ "$(fossil cat skills/alpha/SKILL.md -R "$R" -r tip 2>/dev/null)" = "$(printf -- '---\nfossil reads this')" ] && pass fossil-cat-reads-edited-file || bad fossil-cat-reads-edited-file
    [ "$(fossil cat skills/zeta.md -R "$R" -r tip 2>/dev/null)" = "new file" ] && pass fossil-cat-reads-added-file || bad fossil-cat-reads-added-file
    fossil test-integrity -R "$R" >/dev/null 2>&1 && pass fossil-integrity-after-suit-checkin || bad fossil-integrity-after-suit-checkin
    rm "$store/wd/agents/reviewer.md"
    "$SUIT" commit wd -m "deleted by suit" >/dev/null 2>&1
    fossil cat agents/reviewer.md -R "$R" -r tip >/dev/null 2>&1 && bad fossil-sees-the-deletion || pass fossil-sees-the-deletion

    # Trunk's only newer check-in moved to another branch: nowhere to update to.
    fresh wd
    "$SUIT" store open wd >/dev/null 2>&1
    R=$T/home/wardrobes/wd.fossil
    mkdir "$T/co"
    (cd "$T/co" && fossil open "$R" >/dev/null 2>&1 && printf 'elsewhere\n' > elsewhere.md && fossil add elsewhere.md >/dev/null 2>&1 && fossil commit --branch other --user fixture -m "other branch" >/dev/null 2>&1)
    before=$(tree "$store/wd" | cksum)
    check update-with-no-leaf-on-the-branch-stays-put 0 "" -- "$SUIT" store update wd
    grep -q "^updated to [0-9a-f]\{12\}$" "$T/out" && pass update-with-no-leaf-says-the-version || bad update-with-no-leaf-says-the-version "$(cat "$T/out")"
    [ "$(tree "$store/wd" | cksum)" = "$before" ] && pass update-with-no-leaf-changes-nothing || bad update-with-no-leaf-changes-nothing
    rm -rf "$T/co"

    # Differential: about 600 files, an executable script, and a deletion across
    # two check-ins. The store matches stock fossil's checkout at each version.
    D=$T/diff
    rm -rf "$D"; mkdir -p "$D/co" "$D/home/wardrobes"
    (
        cd "$D/co" || exit 1
        fossil new --admin-user fixture "$D/big.fossil" >/dev/null 2>&1
        fossil open "$D/big.fossil" >/dev/null 2>&1
        d=0
        while [ $d -lt 30 ]; do
            mkdir -p "skills/s$d/ref"
            f=0
            while [ $f -lt 20 ]; do
                awk -v d=$d -v f=$f 'BEGIN { for (k = 0; k < 30; k++) printf "skill %d file %d line %d\n", d, f, k }' > "skills/s$d/ref/f$f.md"
                f=$((f + 1))
            done
            d=$((d + 1))
        done
        printf '#!/bin/sh\necho big\n' > run.sh; chmod +x run.sh
        fossil add . >/dev/null 2>&1
        fossil commit --user fixture -m one >/dev/null 2>&1
        cp "$D/big.fossil" "$D/v1.fossil"
        sleep 1
        printf 'changed\n' >> skills/s3/ref/f4.md
        printf '#!/bin/sh\necho big two\n' > run.sh
        fossil rm skills/s7/ref/f9.md >/dev/null 2>&1
        printf 'added later\n' > skills/s7/ref/extra.md
        fossil add skills/s7/ref/extra.md >/dev/null 2>&1
        fossil commit --user fixture -m two >/dev/null 2>&1
        cp "$D/big.fossil" "$D/v2.fossil"
    )
    count=$(cd "$D/co" && find skills -type f | wc -l | tr -d ' ')
    [ "$count" -ge 600 ] && pass differential-wardrobe-has-about-600-files || bad differential-wardrobe-has-about-600-files "$count files"
    export SUIT_HOME="$D/home"
    cp "$D/v1.fossil" "$D/home/wardrobes/big.fossil"
    "$SUIT" store open big >/dev/null 2>&1
    rm -rf "$D/fco1"; mkdir "$D/fco1"
    (cd "$D/fco1" && fossil open "$D/v1.fossil" >/dev/null 2>&1)
    tree "$D/fco1" > "$T/f-v1"
    tree "$D/home/store/big" > "$T/s-v1"
    cmp -s "$T/f-v1" "$T/s-v1" && pass differential-v1-store-equals-fossil-checkout || bad differential-v1-store-equals-fossil-checkout "$(diff "$T/f-v1" "$T/s-v1" | head -5)"
    cp "$D/v2.fossil" "$D/home/wardrobes/big.fossil"
    check differential-update-to-v2 0 "" -- "$SUIT" store update big
    rm -rf "$D/fco2"; mkdir "$D/fco2"
    (cd "$D/fco2" && fossil open "$D/v2.fossil" >/dev/null 2>&1)
    tree "$D/fco2" > "$T/f-v2"
    tree "$D/home/store/big" > "$T/s-v2"
    cmp -s "$T/f-v2" "$T/s-v2" && pass differential-v2-store-equals-fossil-checkout || bad differential-v2-store-equals-fossil-checkout "$(diff "$T/f-v2" "$T/s-v2" | head -5)"
    grep -q "^./run.sh .* x$" "$T/s-v2" && pass differential-executable-bit-kept || bad differential-executable-bit-kept
    [ ! -e "$D/home/store/big/skills/s7/ref/f9.md" ] && pass differential-deleted-file-is-gone || bad differential-deleted-file-is-gone
    check back-in-the-differential-store 0 "" -- "$SUIT" back big
    tree "$D/home/store/big" > "$T/s-back"
    cmp -s "$T/f-v1" "$T/s-back" && pass differential-back-equals-v1 || bad differential-back-equals-v1
else
    skip differential "stock fossil is not installed"
    skip fossil-reads-suit-checkins "stock fossil is not installed"
fi

# ---- the lint: each rule through suit lint -------------------------------------

lintcase() { printf '%s\n' "$4" > "$store/wd/lintme.txt"; check "$1" "$2" "$3" -- "$SUIT" lint wd; }
fresh wd
"$SUIT" store open wd >/dev/null 2>&1
lintcase lint-clean-store 0 "" "nothing to see"
[ ! -s "$T/out" ] && [ ! -s "$T/err" ] && pass lint-clean-prints-nothing || bad lint-clean-prints-nothing
lintcase lint-private-key 3 "lintme.txt:1: token-shaped value" "x -----BEGIN RSA PRIVATE KEY----- x"
lintcase lint-certificate-is-fine 0 "" "-----BEGIN CERTIFICATE-----"
lintcase lint-private-key-must-share-a-line 0 "" "-----BEGIN
PRIVATE KEY-----"
lintcase lint-aws-key 3 "token-shaped" "id AKIAABCDEFGHIJKLMNOP."
lintcase lint-aws-key-15-is-fine 0 "" "AKIAABCDEFGHIJKLMNO"
lintcase lint-aws-key-lower-case-is-fine 0 "" "AKIAabcdefghijklmnop"
for p in ghp_ gho_ ghs_ github_pat_; do
    lintcase "lint-$p-20" 3 "token-shaped" "t ${p}abcdefghij0123456789"
    lintcase "lint-$p-19-is-fine" 0 "" "t ${p}abcdefghij012345678"
done
lintcase lint-sk-20 3 "token-shaped" "sk-abcdefghij0123456789"
lintcase lint-sk-19-is-fine 0 "" "sk-abcdefghij012345678"
lintcase lint-sk-with-dash-and-underscore 3 "token-shaped" "sk-abc-def_ghi-0123456789"
for p in xoxb- xoxp- xoxa-; do
    lintcase "lint-$p-10" 3 "token-shaped" "$p""0123456789"
    lintcase "lint-$p-9-is-fine" 0 "" "$p""012345678"
done
for w in token secret password passwd api_key apikey api-key; do
    lintcase "lint-credential-$w" 3 "token-shaped" "$w = abcdefghijklmnopqrstuvwx"
done
lintcase lint-credential-quoted-colon 3 "token-shaped" "\"My_API_Key\" :  \"abcdefghij0123456789+/=-_\""
lintcase lint-credential-mixed-case 3 "token-shaped" "PassWord=AbCdEfGhIjKlMnOpQrStUvWx"
lintcase lint-credential-inside-a-word 3 "token-shaped" "my_tokens_list: abcdefghijklmnopqrstuvwx"
lintcase lint-credential-23-is-fine 0 "" "secret = abcdefghijklmnopqrstuvw"
lintcase lint-credential-with-a-space-is-fine 0 "" "secret = abcdefghijklmnop rstuvwxyzabc"
lintcase lint-credential-dollar-is-fine 0 "" 'token = $TOKEN_FROM_THE_ENVIRONMENT_X'
lintcase lint-credential-brace-is-fine 0 "" 'token = ${TOKEN_FROM_THE_ENVIRONMENT}'
lintcase lint-credential-angle-is-fine 0 "" 'password: <your password goes here please>'
lintcase lint-credential-mustache-is-fine 0 "" 'password: {{ lookup_the_password_here }}'
lintcase lint-credential-all-the-same-is-fine 0 "" 'secret = xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
lintcase lint-credential-no-value-is-fine 0 "" 'token ='
lintcase lint-credential-no-separator-is-fine 0 "" 'secret abcdefghijklmnopqrstuvwxyz0123'
for t in "Co-Authored-By: someone" "Generated WITH a tool" "generated by AI" "Claude-Session: x" "written by ai" "Assisted By AI"; do
    lintcase "lint-attribution-$(echo "$t" | tr ' :' '__')" 3 "lintme.txt:1: attribution text" "see $t"
done
lintcase lint-attribution-near-miss-is-fine 0 "" "co-authored by hand; generated by hand; assisted by a friend"

# ---- the lint: binary files, suit.lint, skills, sizes ---------------------------

rm -f "$store/wd/lintme.txt"
printf 'AKIAABCDEFGHIJKLMNOP\0\ngenerated with\n' > "$store/wd/blob.bin"
check lint-skips-a-binary-file 0 "" -- "$SUIT" lint wd
{ head -c 8191 /dev/zero | tr '\0' 'a'; printf '\nAKIAABCDEFGHIJKLMNOP\0'; } > "$store/wd/late.bin"
check lint-nul-after-the-probe-is-text 3 "late.bin:2: token-shaped" -- "$SUIT" lint wd
rm "$store/wd/late.bin" "$store/wd/blob.bin"
printf 'Co-Authored-By: x\nAKIAABCDEFGHIJKLMNOP\n' > "$store/wd/notes.txt"
printf 'allow notes.txt\n' > "$store/wd/suit.lint"
check lint-allow-exempts-a-file 0 "" -- "$SUIT" lint wd
printf 'allow other.txt\n' > "$store/wd/suit.lint"
check lint-allow-is-for-that-file-only 3 "notes.txt:1: attribution text" -- "$SUIT" lint wd
grep -qF "notes.txt:2: token-shaped" "$T/err" && pass lint-reports-every-line || bad lint-reports-every-line "$(cat "$T/err")"
printf 'plain\nsome ACME-Internal text\n' > "$store/wd/notes.txt"
printf 'forbid acme-internal\n' > "$store/wd/suit.lint"
check lint-forbid-any-letter-case 3 "notes.txt:2: text this wardrobe forbids" -- "$SUIT" lint wd
printf 'forbid acme\nallow notes.txt\n' > "$store/wd/suit.lint"
check lint-forbid-and-allow 0 "" -- "$SUIT" lint wd
printf 'frobnicate x\n' > "$store/wd/suit.lint"
check lint-bad-suit-lint-is-a-problem 3 "suit.lint:1:" -- "$SUIT" lint wd
printf 'forbid acme\n' > "$store/wd/suit.lint"
printf 'ok\n' > "$store/wd/notes.txt"
check lint-suit-lint-is-not-scanned-for-its-own-forbid 0 "" -- "$SUIT" lint wd
rm "$store/wd/suit.lint"
mkdir "$store/wd/suit.lint"
check lint-suit-lint-unreadable 1 "suit.lint: cannot read: " -- "$SUIT" lint wd
rmdir "$store/wd/suit.lint"
{ printf 'ok\n'; head -c 65537 /dev/zero | tr '\0' 'a'; printf '\n'; } > "$store/wd/long.txt"
check lint-line-over-64-KiB 3 "long.txt:2: line is longer than 64 KiB" -- "$SUIT" lint wd
rm "$store/wd/long.txt"
head -c 4194305 /dev/zero | tr '\0' 'a' > "$store/wd/huge.txt"
check lint-file-over-4-MiB 3 "huge.txt: larger than 4 MiB, not scanned" -- "$SUIT" lint wd
yes aaaaaaaaaaaaaaa | head -c 4194304 > "$store/wd/huge.txt"
check lint-file-of-4-MiB-is-scanned 0 "" -- "$SUIT" lint wd
rm "$store/wd/huge.txt"
mkdir -p "$store/wd/skills/nohead" "$store/wd/skills/none" "$store/wd/skills/good"
printf 'text\n' > "$store/wd/skills/nohead/SKILL.md"
printf 'text\n' > "$store/wd/skills/nohead/extra.md"
printf 'text\n' > "$store/wd/skills/none/extra.md"
printf '%s\n' '---' 'name: x' '---' > "$store/wd/skills/good/SKILL.md"
check lint-skill-without-a-header 3 "skills/nohead/SKILL.md:1: no header" -- "$SUIT" lint wd
check lint-skill-without-a-skill-file 3 "skills/none: no SKILL.md" -- "$SUIT" lint wd
[ "$(grep -c nohead "$T/err")" = 1 ] && pass lint-says-a-skill-once || bad lint-says-a-skill-once "$(cat "$T/err")"
grep -q good "$T/err" && bad lint-good-skill-is-fine "$(cat "$T/err")" || pass lint-good-skill-is-fine
rm -rf "$store/wd/skills/nohead" "$store/wd/skills/none"
mkdir "$store/wd/skills/dir"; mkdir "$store/wd/skills/dir/SKILL.md"; printf 'x\n' > "$store/wd/skills/dir/SKILL.md/f"
check lint-skill-file-that-is-a-folder 3 "skills/dir: no SKILL.md" -- "$SUIT" lint wd
rm -rf "$store/wd/skills/dir"

# ---- the lint: what it looks at, and what goes wrong -----------------------------

fresh wd
"$SUIT" store open wd >/dev/null 2>&1
rm -rf "$store/wd/skills/alpha"
rm "$store/wd/agents/reviewer.md"
check lint-does-not-look-at-deleted-files-or-folders 0 "" -- "$SUIT" lint wd
check lint-stat-of-a-deleted-skill-folder-fails 1 "cannot read skills/alpha: $EIO" -- env SUIT_FAULT=lstat:2:EIO "$SUIT" lint wd
i=0; while [ $i -lt 1000 ]; do echo 'AKIAABCDEFGHIJKLMNOP'; i=$((i + 1)); done > "$store/wd/many.txt"
check lint-reports-the-first-problems 3 "many.txt:1: token-shaped value" -- "$SUIT" lint wd
[ "$(wc -l < "$T/err" | tr -d ' ')" -le 400 ] && grep -q '^\.\.\. and [0-9][0-9]* more$' "$T/err" && pass lint-counts-the-problems-it-left-out || bad lint-counts-the-problems-it-left-out "$(tail -2 "$T/err")"
rm "$store/wd/many.txt"
fresh wd
"$SUIT" store open wd >/dev/null 2>&1
printf 'x\n' > "$store/wd/lintme.txt"
mkdir -p "$store/wd/skills/gd"
printf -- '---\n' > "$store/wd/skills/gd/SKILL.md"
check lint-store-with-new-files-is-clean 0 "" -- "$SUIT" lint wd
check lint-open-of-suit-lint-fails 1 "suit.lint: cannot open: $EIO" -- env SUIT_FAULT=open:1:EIO "$SUIT" lint wd
check lint-open-of-a-file-fails 1 "cannot read lintme.txt: $EIO" -- env SUIT_FAULT=open:2:EIO "$SUIT" lint wd
check lint-open-of-skill-file-fails 1 "cannot read skills/gd/SKILL.md: $EIO" -- env SUIT_FAULT=open:3:EIO "$SUIT" lint wd
check lint-open-of-skill-file-fails-in-the-scan 1 "cannot read skills/gd/SKILL.md: $EIO" -- env SUIT_FAULT=open:4:EIO "$SUIT" lint wd
check lint-read-of-a-file-fails 1 "cannot read lintme.txt: $EIO" -- env SUIT_FAULT=read:1:EIO "$SUIT" lint wd
check lint-read-of-a-skill-file-fails 1 "cannot read skills/gd/SKILL.md: $EIO" -- env SUIT_FAULT=read:3:EIO "$SUIT" lint wd
check lint-read-interrupted-retries 0 "" -- env SUIT_FAULT=read:1:EINTR "$SUIT" lint wd
check lint-stat-of-a-file-fails 1 "cannot read lintme.txt: $EIO" -- env SUIT_FAULT=lstat:1:EIO "$SUIT" lint wd
check lint-stat-of-a-skill-file-fails 1 "cannot read skills/gd/SKILL.md: $EIO" -- env SUIT_FAULT=lstat:2:EIO "$SUIT" lint wd
check lint-stat-of-a-skill-file-fails-in-the-scan 1 "cannot read skills/gd/SKILL.md: $EIO" -- env SUIT_FAULT=lstat:3:EIO "$SUIT" lint wd
check lint-before-open 1 "no wardrobe at" -- "$SUIT" lint nowhere
check lint-usage 2 "usage" -- "$SUIT" lint
check lint-usage-extra-word 2 "usage" -- "$SUIT" lint wd more
check lint-name-is-checked 2 "is not a wardrobe name" -- "$SUIT" lint "bad/name"
ln -s lintme.txt "$store/wd/link.txt"
check lint-symlink 3 "link.txt: symlink, not supported" -- "$SUIT" lint wd
rm "$store/wd/link.txt"
tree "$store/wd" > "$T/l-before"; cksum < "$T/home/wardrobes/wd.fossil" > "$T/l-repo"
printf 'Generated with a tool\n' > "$store/wd/lintme.txt"
"$SUIT" lint wd >/dev/null 2>&1
printf 'x\n' > "$store/wd/lintme.txt"
tree "$store/wd" > "$T/l-after"; cksum < "$T/home/wardrobes/wd.fossil" > "$T/l-repo2"
cmp -s "$T/l-before" "$T/l-after" && cmp -s "$T/l-repo" "$T/l-repo2" && pass lint-changes-nothing || bad lint-changes-nothing

# ---- commit runs the lint; a large deletion is held ------------------------------

fresh wd
"$SUIT" store open wd >/dev/null 2>&1
printf 'one\n' > "$store/wd/one.txt"
check commit-clean-change-is-checked-in 0 "" -- "$SUIT" commit wd -m "a clean one"
grep -q '^checked in [0-9a-f]\{12\}$' "$T/out" && pass commit-clean-says-what-it-did || bad commit-clean-says-what-it-did "$(cat "$T/out")"
printf 'two\nAKIAABCDEFGHIJKLMNOP\n' > "$store/wd/two.txt"
printf 'one more\n' >> "$store/wd/one.txt"
tree "$store/wd" > "$T/c-before"; cksum < "$T/home/wardrobes/wd.fossil" > "$T/c-repo"
check commit-refused-by-the-lint 3 "two.txt:2: token-shaped value" -- "$SUIT" commit wd -m "no"
tree "$store/wd" > "$T/c-after"; cksum < "$T/home/wardrobes/wd.fossil" > "$T/c-repo2"
cmp -s "$T/c-before" "$T/c-after" && cmp -s "$T/c-repo" "$T/c-repo2" && pass refused-commit-changes-nothing || bad refused-commit-changes-nothing
[ ! -s "$T/out" ] && pass refused-commit-prints-no-check-in || bad refused-commit-prints-no-check-in
"$SUIT" store status wd 2>/dev/null | grep -q '^added two.txt$' && pass refused-commit-keeps-the-changes || bad refused-commit-keeps-the-changes
printf 'two\n' > "$store/wd/two.txt"
check commit-after-the-fix 0 "" -- "$SUIT" commit wd -m "fixed"
check commit-usage-extra-argument 2 "usage" -- "$SUIT" commit wd -m x y
check commit-usage-too-many-arguments 2 "usage" -- "$SUIT" commit wd -m x --confirm-deletions y
check commit-usage-wrong-last-word 2 "usage" -- "$SUIT" commit wd -m x --confirm
check commit-usage-confirm-without-message 2 "usage" -- "$SUIT" commit wd --confirm-deletions x y

# 26 files on top of the fixture's four: 30 tracked. BASE30 and BASE29 are those wardrobes.
mkbase() {
    fresh base
    "$SUIT" store open base >/dev/null 2>&1
    i=1; while [ $i -le "$1" ]; do printf 'f%s\n' "$i" > "$store/base/f$i.txt"; i=$((i + 1)); done
    "$SUIT" commit base -m "files" >/dev/null 2>&1
}
mkbase 26; cp "$T/home/wardrobes/base.fossil" "$T/base30.fossil"
mkbase 25; cp "$T/home/wardrobes/base.fossil" "$T/base29.fossil"
# deleting BASE N: a fresh wardrobe "wd" from BASE with the first N files deleted
deleting() {
    fresh wd; cp "$1" "$T/home/wardrobes/wd.fossil"
    "$SUIT" store open wd >/dev/null 2>&1
    i=1; while [ $i -le "$2" ]; do rm "$store/wd/f$i.txt"; i=$((i + 1)); done
}
deleting "$T/base30.fossil" 5
check commit-deleting-5-of-30-is-not-held 0 "" -- "$SUIT" commit wd -m del
deleting "$T/base30.fossil" 6
check commit-deleting-6-of-30-a-fifth-is-not-held 0 "" -- "$SUIT" commit wd -m del
deleting "$T/base30.fossil" 7
check commit-deleting-7-of-30-is-held 4 "held wd: 7 of 30 files deleted" -- "$SUIT" commit wd -m del
"$SUIT" store status wd 2>/dev/null | grep -c '^deleted f' | grep -q '^7$' && pass held-commit-checks-nothing-in || bad held-commit-checks-nothing-in
check commit-held-deletions-confirmed 0 "" -- "$SUIT" commit wd -m del --confirm-deletions
grep -q '^checked in ' "$T/out" && pass confirmed-commit-checks-in || bad confirmed-commit-checks-in
deleting "$T/base29.fossil" 6
check commit-deleting-6-of-29-just-over-a-fifth-is-held 4 "held wd: 6 of 29 files deleted" -- "$SUIT" commit wd -m del
deleting "$T/base30.fossil" 26
check commit-deleting-most-of-it-is-held 4 "held wd: 26 of 30 files deleted" -- "$SUIT" commit wd -m del
check commit-confirm-when-held-by-size 0 "" -- "$SUIT" commit wd -m del --confirm-deletions

# ---- tend ------------------------------------------------------------------------

att=$T/home/attention
fresh wd
"$SUIT" store open wd >/dev/null 2>&1
check tend-with-nothing-to-do 0 "" -- "$SUIT" tend wd
[ ! -s "$T/out" ] && [ ! -s "$T/err" ] && [ ! -e "$att" ] && pass tend-with-nothing-to-do-writes-nothing || bad tend-with-nothing-to-do-writes-nothing
printf 'one\n' > "$store/wd/one.txt"
printf 'two\n' > "$store/wd/two.txt"
check tend-checks-in-a-clean-change 0 "" -- "$SUIT" tend wd
grep -q '^checked in [0-9a-f]\{12\}$' "$T/out" && pass tend-says-what-it-did || bad tend-says-what-it-did "$(cat "$T/out")"
[ ! -s "$T/err" ] && [ ! -e "$att" ] && pass tend-clean-leaves-no-attention || bad tend-clean-leaves-no-attention
"$SUIT" store status wd 2>&1 | grep -q . && bad tend-leaves-the-store-clean || pass tend-leaves-the-store-clean
if have_fossil; then
    fossil timeline -R "$T/home/wardrobes/wd.fossil" -n 1 2>/dev/null | grep -qF "Edits on this machine: 2 files" && pass tend-message-without-a-machine-name || bad tend-message-without-a-machine-name
    "$SUIT" machine laptop >/dev/null 2>&1
    printf 'three\n' > "$store/wd/three.txt"
    "$SUIT" tend wd >/dev/null 2>&1
    fossil timeline -R "$T/home/wardrobes/wd.fossil" -n 1 2>/dev/null | grep -qF "Edits on laptop: 1 files" && pass tend-message-names-the-machine || bad tend-message-names-the-machine
else
    skip tend-message "stock fossil is not installed"
    "$SUIT" machine laptop >/dev/null 2>&1
fi
printf 'bad\nco-authored-by: me\n' > "$store/wd/bad.txt"
printf 'AKIAABCDEFGHIJKLMNOP\n' > "$store/wd/two.txt"
check tend-lint-failure 3 "bad.txt:2: attribution text" -- "$SUIT" tend wd
[ ! -s "$T/out" ] && pass tend-lint-failure-checks-nothing-in || bad tend-lint-failure-checks-nothing-in
[ "$(sed -n 1p "$att")" = "lint wd" ] && grep -qx "  bad.txt:2: attribution text" "$att" && grep -qx "  two.txt:1: token-shaped value" "$att" && [ "$(wc -l < "$att" | tr -d ' ')" = 3 ] && pass tend-writes-the-lint-item || bad tend-writes-the-lint-item "$(cat "$att")"
"$SUIT" tend wd >/dev/null 2>&1; [ "$(wc -l < "$att" | tr -d ' ')" = 3 ] && pass tend-again-does-not-repeat-the-item || bad tend-again-does-not-repeat-the-item
printf 'lint other\n  x.txt:1: y\n' >> "$att"
printf 'bad\n' > "$store/wd/bad.txt"
check tend-lint-failure-with-the-other-items 3 "two.txt:1: token-shaped" -- "$SUIT" tend wd
grep -q '^lint other$' "$att" && grep -q '^  x.txt:1: y$' "$att" && pass tend-keeps-other-wardrobes-items || bad tend-keeps-other-wardrobes-items "$(cat "$att")"
printf 'two\n' > "$store/wd/two.txt"
check tend-after-the-fix 0 "" -- "$SUIT" tend wd
grep -q '^lint wd$' "$att" && bad tend-success-removes-its-item || pass tend-success-removes-its-item
[ "$(cat "$att")" = "lint other
  x.txt:1: y" ] && pass tend-success-keeps-the-others || bad tend-success-keeps-the-others "$(cat "$att")"
printf 'lint wd\n  z:1: w\n' >> "$att"
check tend-nothing-to-do-removes-the-item 0 "" -- "$SUIT" tend wd
grep -q '^lint wd$' "$att" && bad tend-nothing-to-do-clears-its-item || pass tend-nothing-to-do-clears-its-item
rm "$att"
printf 'lint wd\n  z:1: w\n' > "$att"
check tend-nothing-to-do-and-last-item 0 "" -- "$SUIT" tend wd
[ ! -e "$att" ] && pass tend-removes-the-file-when-empty || bad tend-removes-the-file-when-empty
check tend-usage 2 "usage" -- "$SUIT" tend a b
check tend-before-open 1 "no wardrobe at" -- "$SUIT" tend nowhere

# ---- tend: held deletions, the attention file, and failures ----------------------

deleting "$T/base30.fossil" 5
check tend-deleting-5-of-30-is-checked-in 0 "" -- "$SUIT" tend wd
deleting "$T/base30.fossil" 6
check tend-deleting-a-fifth-is-checked-in 0 "" -- "$SUIT" tend wd
deleting "$T/base30.fossil" 7
att=$T/home/attention
check tend-deleting-7-of-30-is-held 4 "held wd: 7 of 30 files deleted" -- "$SUIT" tend wd
[ "$(cat "$att")" = "held wd: 7 of 30 files deleted" ] && pass tend-writes-the-held-item || bad tend-writes-the-held-item "$(cat "$att")"
"$SUIT" store status wd 2>/dev/null | grep -c '^deleted f' | grep -q '^7$' && pass held-tend-checks-nothing-in || bad held-tend-checks-nothing-in
printf 'z\n' > "$store/wd/f1.txt"
i=2; while [ $i -le 7 ]; do printf 'f%s\n' "$i" > "$store/wd/f$i.txt"; i=$((i + 1)); done
check tend-after-the-files-are-back 0 "" -- "$SUIT" tend wd
[ ! -e "$att" ] && pass tend-removes-the-held-item || bad tend-removes-the-held-item "$(cat "$att")"
deleting "$T/base29.fossil" 6
check tend-deleting-6-of-29-is-held 4 "held wd: 6 of 29 files deleted" -- "$SUIT" tend wd
check commit-says-the-same-when-held 4 "held wd: 6 of 29 files deleted" -- "$SUIT" commit wd -m x
rm -f "$att"
check tend-held-attention-write-fails 1 "cannot write $att: $EIO" -- env SUIT_FAULT=rename:1:EIO "$SUIT" tend wd
check commit-confirms-what-tend-held 0 "" -- "$SUIT" commit wd -m x --confirm-deletions

# ---- the attention file and its failures ------------------------------------------

attn() { fresh wd; "$SUIT" store open wd >/dev/null 2>&1; att=$T/home/attention; "$SUIT" machine laptop >/dev/null 2>&1; }
attn
printf 'AKIAABCDEFGHIJKLMNOP\n' > "$store/wd/a.txt"
seed() { printf 'lint other\n  x:1: y\n' > "$att"; }
seed
check attention-open-fails 1 "cannot open $att: $EIO" -- env SUIT_FAULT=open:3:EIO "$SUIT" tend wd
check attention-temporary-file-fails 1 "cannot write $att: $EIO" -- env SUIT_FAULT=open:4:EIO "$SUIT" tend wd
check attention-read-fails 1 "cannot read $att: $EIO" -- env SUIT_FAULT=read:3:EIO "$SUIT" tend wd
check attention-rename-fails 1 "cannot write $att: $EIO" -- env SUIT_FAULT=rename:1:EIO "$SUIT" tend wd
[ "$(cat "$att")" = "lint other
  x:1: y" ] && pass attention-failed-write-keeps-the-file || bad attention-failed-write-keeps-the-file "$(cat "$att")"
check attention-read-interrupted-retries 3 "a.txt:1: token-shaped" -- env SUIT_FAULT=read:3:EINTR "$SUIT" tend wd
head -c 131073 /dev/zero | tr '\0' 'a' > "$att"
check attention-file-too-big 1 "$att is over 131072 bytes" -- "$SUIT" tend wd
yes 'lint o' | head -c 131000 > "$att"
check attention-file-would-be-too-big 1 "$att would be over 131072 bytes" -- "$SUIT" tend wd
rm -f "$att"
rm "$store/wd/a.txt"
printf 'lint wd\n  x:1: y\n' > "$att"
check attention-nothing-to-do-open-fails 1 "cannot open $att: $EIO" -- env SUIT_FAULT=open:2:EIO "$SUIT" tend wd
check attention-remove-fails 1 "cannot remove $att: $EIO" -- env SUIT_FAULT=unlink:1:EIO "$SUIT" tend wd
check attention-remove-of-a-vanished-file-is-fine 0 "" -- env SUIT_FAULT=unlink:1:ENOENT "$SUIT" tend wd
rm -f "$att"
printf 'ok\n' > "$store/wd/a.txt"
printf 'lint wd\n  x:1: y\n' > "$att"
check tend-machine-file-open-fails 1 "cannot open $T/home/machine: $EIO" -- env SUIT_FAULT=open:3:EIO "$SUIT" tend wd
check tend-clearing-the-item-fails 1 "cannot open $att: $EIO" -- env SUIT_FAULT=open:4:EIO "$SUIT" tend wd
"$SUIT" store status wd 2>/dev/null | grep -q '^added a.txt$' && bad tend-checked-in-before-clearing || pass tend-checked-in-before-clearing
printf 'ok2\n' > "$store/wd/a.txt"
printf 'bad name\n' > "$T/home/machine"
check tend-bad-machine-name 1 "machine" -- "$SUIT" tend wd
"$SUIT" store status wd 2>/dev/null | grep -q '^edited a.txt$' && pass tend-bad-machine-name-checks-nothing-in || bad tend-bad-machine-name-checks-nothing-in

# ---- status shows what needs you ---------------------------------------------------

fresh mine
"$SUIT" store open mine >/dev/null 2>&1
: > "$store/mine/suit.conf"
export HOME=$T/home-dir; mkdir -p "$HOME"
check status-without-attention 0 "" -- "$SUIT" status
grep -q 'needs you' "$T/out" && bad status-says-nothing-needs-you || pass status-says-nothing-needs-you
printf 'lint mine\n  skills/x.md:3: token-shaped value\nheld other: 7 of 30 files deleted\n' > "$T/home/attention"
check status-with-attention 0 "" -- "$SUIT" status
[ "$(sed -n '/^needs you:$/,$p' "$T/out")" = "needs you:
lint mine
  skills/x.md:3: token-shaped value
held other: 7 of 30 files deleted" ] && pass status-lists-what-needs-you || bad status-lists-what-needs-you "$(cat "$T/out")"
check status-attention-unreadable 1 "cannot open $T/home/attention: $EIO" -- env SUIT_FAULT=open:4:EIO "$SUIT" status

# ---- more of the attention file; deletions that were already unmanaged -------------

deleting "$T/base30.fossil" 7
att=$T/home/attention
printf 'lint wd\n  q\nlonger wd\n  y\nlint wx\n  z\n' > "$att"
check tend-held-keeps-items-of-other-kinds-and-names 4 "held wd" -- "$SUIT" tend wd
[ "$(cat "$att")" = "lint wd
  q
longer wd
  y
lint wx
  z
held wd: 7 of 30 files deleted" ] && pass attention-keeps-other-kinds-and-names || bad attention-keeps-other-kinds-and-names "$(cat "$att")"
check commit-with-an-empty-message-fails-after-deleting 1 "check in failed" -- "$SUIT" commit wd -m "" --confirm-deletions
check lint-sees-files-already-unmanaged 0 "" -- "$SUIT" lint wd
check commit-counts-files-already-unmanaged 4 "held wd: 7 of 30 files deleted" -- "$SUIT" commit wd -m x
check commit-confirms-files-already-unmanaged 0 "" -- "$SUIT" commit wd -m x --confirm-deletions
attn
printf 'AKIAABCDEFGHIJKLMNOP\n' > "$store/wd/a.txt"
printf 'lint wx\n  z\nlint wd\n  a.txt:1: token-shaped valuf\n' > "$att"
check tend-replaces-an-item-of-the-same-length 3 "a.txt:1: token-shaped value" -- "$SUIT" tend wd
[ "$(cat "$att")" = "lint wx
  z
lint wd
  a.txt:1: token-shaped value" ] && pass attention-replaces-the-item-in-place-of-the-old || bad attention-replaces-the-item-in-place-of-the-old "$(cat "$att")"
rm "$store/wd/a.txt"
fresh wd
"$SUIT" store open wd >/dev/null 2>&1
rm "$store/wd/agents/reviewer.md"
ln -s ../run.sh "$store/wd/agents/reviewer.md"
check lint-tracked-file-replaced-by-a-symlink 3 "agents/reviewer.md: symlink, not supported" -- "$SUIT" lint wd
[ "$(wc -l < "$T/err" | tr -d ' ')" = 1 ] && pass lint-says-a-symlink-once || bad lint-says-a-symlink-once "$(cat "$T/err")"
fresh mine
"$SUIT" store open mine >/dev/null 2>&1
: > "$store/mine/suit.conf"
printf 'lint zz' > "$T/home/attention"
check status-attention-without-a-final-newline 0 "" -- "$SUIT" status
[ "$(sed -n '/^needs you:$/,$p' "$T/out")" = "needs you:
lint zz" ] && pass status-shows-a-last-line-without-a-newline || bad status-shows-a-last-line-without-a-newline "$(cat "$T/out")"

# ---- remote, login, sync -----------------------------------------------------

export HOME=$T/h0
mkdir -p "$HOME"
RT=$T/net
rm -rf "$RT"; mkdir -p "$RT"
fresh wd
mkdir -p "$SUIT_HOME"

check remote-none-is-reported 1 "no remote is set for wd" -- "$SUIT" remote wd
check remote-set 0 "" -- "$SUIT" remote wd "file://$RT/r.fossil"
check remote-show 0 "" -- "$SUIT" remote wd
[ "$(cat "$T/out")" = "file://$RT/r.fossil" ] && pass remote-show-prints-the-address || bad remote-show-prints-the-address "$(cat "$T/out")"
[ "$(cat "$SUIT_HOME/remotes")" = "wd file://$RT/r.fossil" ] && pass remotes-file-is-one-line || bad remotes-file-is-one-line "$(cat "$SUIT_HOME/remotes")"
check remote-set-http 0 "" -- "$SUIT" remote wd http://example.com:8080/repo
check remote-replaces 0 "" -- "$SUIT" remote wd https://example.com/repo
[ "$(wc -l < "$SUIT_HOME/remotes" | tr -d ' ')" = 1 ] && pass remote-replace-keeps-one-line || bad remote-replace-keeps-one-line
check remote-second-wardrobe 0 "" -- "$SUIT" remote aa http://h/p
[ "$(cut -d' ' -f1 "$SUIT_HOME/remotes" | tr '\n' ' ')" = "aa wd " ] && pass remotes-are-sorted-by-name || bad remotes-are-sorted-by-name "$(cat "$SUIT_HOME/remotes")"
check remote-clear 0 "" -- "$SUIT" remote wd --none
check remote-cleared-is-none 1 "no remote is set for wd" -- "$SUIT" remote wd
check remote-clear-of-none-is-fine 0 "" -- "$SUIT" remote wd --none
check remote-bad-name 2 "is not a wardrobe name" -- "$SUIT" remote 'bad name' http://h/p
check remote-bad-scheme 2 "starts with file://, http:// or https://" -- "$SUIT" remote wd ftp://h/p
check remote-relative-file 2 "needs an absolute path" -- "$SUIT" remote wd file://rel/x
check remote-file-query 2 "no query, fragment or % escape" -- "$SUIT" remote wd 'file:///a?b'
check remote-http-no-path 2 "http://HOST[:PORT]/PATH" -- "$SUIT" remote wd http://host
check remote-http-query 2 "no query, fragment or % escape" -- "$SUIT" remote wd 'http://host/a#b'
check remote-bad-host 2 "the host is letters" -- "$SUIT" remote wd 'http://ho_st/p'
check remote-empty-host 2 "the host is letters" -- "$SUIT" remote wd 'http://:80/p'
check remote-bad-port 2 "the port is 1 to 65535" -- "$SUIT" remote wd http://host:0/p
check remote-port-too-big 2 "the port is 1 to 65535" -- "$SUIT" remote wd http://host:65536/p
check remote-port-letters 2 "the port is 1 to 65535" -- "$SUIT" remote wd http://host:8a/p
check remote-port-long 2 "the port is 1 to 65535" -- "$SUIT" remote wd http://host:123456/p
check remote-port-empty 2 "the port is 1 to 65535" -- "$SUIT" remote wd http://host:/p
check remote-space 2 "printable characters only" -- "$SUIT" remote wd 'http://host/a b'
check remote-empty-url 2 "1 to 1024 characters" -- "$SUIT" remote wd ''
check remote-long-url 2 "1 to 1024 characters" -- "$SUIT" remote wd "http://h/$(printf 'a%.0s' $(seq 1 1100))"
check remote-user-in-address 2 "credentials do not go in the address" -- "$SUIT" remote wd http://alice@host/p
check remote-password-in-address 2 "credentials do not go in the address" -- "$SUIT" remote wd http://alice:hunter2xyz@host/p
check remote-password-in-https-address 2 "credentials do not go in the address" -- "$SUIT" remote wd https://alice:hunter2xyz@host/p
grep -q hunter2xyz "$T/out" "$T/err" "$SUIT_HOME/remotes" 2>/dev/null && bad address-password-never-echoed || pass address-password-never-echoed

# the remotes file: every strict error, with its line number
bad_remotes() {
    printf '%s' "$2" > "$SUIT_HOME/remotes"
    check "remotes-$1" 1 "remotes:$3" -- "$SUIT" remote wd
}
bad_remotes no-newline 'wd file:///a' "1: line has no newline"
bad_remotes one-field "wd
" "1: expected NAME URL"
bad_remotes extra-field "wd file:///a x
" "1: expected NAME URL"
bad_remotes bad-name "a/b file:///a
" "1: not a wardrobe name"
bad_remotes bad-url "wd ftp://x/y
" "1: an address starts with"
bad_remotes duplicate "wd file:///a
wd file:///b
" "2: duplicate remote for wd"
bad_remotes nul-byte "wd file:///a$(printf '\001')
" "1: an address has printable characters only"
printf 'wd file:///a\0b\n' > "$SUIT_HOME/remotes"
check remotes-nul-byte-in-line 1 "remotes:1: NUL byte in line" -- "$SUIT" remote wd
{ printf 'wd http://h/'; head -c 1400 /dev/zero | tr '\0' a; printf '\n'; } > "$SUIT_HOME/remotes"
check remotes-line-too-long 1 "remotes:1: line is over the limit" -- "$SUIT" remote wd
head -c 70000 /dev/zero | tr '\0' a > "$SUIT_HOME/remotes"
check remotes-file-too-big 1 "file is 65537 bytes, limit is 65536" -- "$SUIT" remote wd
: > "$SUIT_HOME/remotes"
for i in $(seq 1 256); do echo "w$i file:///a" ; done > "$SUIT_HOME/remotes"
check remotes-full-file-reads 0 "" -- "$SUIT" remote w256
echo "w257 file:///a" >> "$SUIT_HOME/remotes"
check remotes-too-many-in-file 1 "too many remotes (limit 256)" -- "$SUIT" remote wd
sed -i.bak '$d' "$SUIT_HOME/remotes"; rm "$SUIT_HOME/remotes.bak"
check remote-too-many-to-add 1 "too many remotes (limit 256)" -- "$SUIT" remote wd http://h/p
check remote-replace-when-full 0 "" -- "$SUIT" remote w1 http://h/p
: > "$SUIT_HOME/remotes"
for i in $(seq 1 64); do printf 'w%d http://h/%s\n' "$i" "$(head -c 1000 /dev/zero | tr '\0' a)"; done > "$SUIT_HOME/remotes"
check remote-file-too-big-to-write 1 "cannot write" -- "$SUIT" remote wd "http://h/$(head -c 1000 /dev/zero | tr '\0' b)"
check remote-open-fails 1 "cannot read: $EIO" -- env SUIT_FAULT=open:1 "$SUIT" remote wd
check remote-read-fails 1 "cannot read: $EIO" -- env SUIT_FAULT=read:1 "$SUIT" remote wd
check remote-write-fails 1 "cannot write $SUIT_HOME/remotes: $EIO" -- env SUIT_FAULT=rename:1 "$SUIT" remote wd http://h/p
check remote-no-home 1 "" -- env -u SUIT_HOME HOME= "$SUIT" remote wd
rm -f "$SUIT_HOME/remotes"

# ---- login and logout ---------------------------------------------------------

SECRET=s3cr3t-9f2k
CRED=$SUIT_HOME/credentials
rm -f "$CRED"
login() { printf '%s\n' "$2" | "$SUIT" login "$1" "$3"; }
checkl() { cn=$1; cw=$2; cm=$3; cs=$4; shift 4; printf '%s\n' "$cs" | "$@" >"$T/out" 2>"$T/err"; cr=$?
    if [ "$cr" != "$cw" ]; then bad "$cn" "exit $cr, want $cw: $(cat "$T/err")"
    elif [ -n "$cm" ] && ! grep -qF -- "$cm" "$T/err"; then bad "$cn" "want '$cm' in: $(cat "$T/err")"
    else pass "$cn"; fi; }
checkl login-writes-the-file 0 "" "$SECRET" "$SUIT" login wd alice
[ "$(cat "$CRED")" = "wd alice $SECRET" ] && pass credentials-is-one-line || bad credentials-is-one-line
[ "$(ls -l "$CRED" | cut -c1-10)" = "-rw-------" ] && pass credentials-is-mode-0600 || bad credentials-is-mode-0600 "$(ls -l "$CRED")"
rm "$CRED"
(umask 0; printf '%s\n' "$SECRET" | "$SUIT" login wd alice)
[ "$(ls -l "$CRED" | cut -c1-10)" = "-rw-------" ] && pass credentials-is-0600-under-any-umask || bad credentials-is-0600-under-any-umask
checkl login-replaces 0 "" "other-secret-1" "$SUIT" login wd bob
[ "$(cat "$CRED")" = "wd bob other-secret-1" ] && pass login-replaces-the-line || bad login-replaces-the-line
checkl login-second 0 "" "second-secret-2" "$SUIT" login aa carol
[ "$(cut -d' ' -f1,2 "$CRED" | tr '\n' ' ')" = "aa carol wd bob " ] && pass logins-are-sorted-by-name || bad logins-are-sorted-by-name
check logout 0 "" -- "$SUIT" logout wd
[ "$(cat "$CRED")" = "aa carol second-secret-2" ] && pass logout-removes-only-its-line || bad logout-removes-only-its-line
check logout-of-nothing 0 "" -- "$SUIT" logout wd
[ "$(cat "$CRED")" = "aa carol second-secret-2" ] && pass logout-of-nothing-changes-nothing || bad logout-of-nothing-changes-nothing
check logout-last 0 "" -- "$SUIT" logout aa
[ ! -s "$CRED" ] && [ "$(ls -l "$CRED" | cut -c1-10)" = "-rw-------" ] && pass logout-of-the-last-leaves-an-empty-private-file || bad logout-of-the-last-leaves-an-empty-private-file
printf 'nonl-secret' | "$SUIT" login wd alice
[ "$(cat "$CRED")" = "wd alice nonl-secret" ] && pass login-takes-a-last-line-without-newline || bad login-takes-a-last-line-without-newline
checkl login-empty-secret 2 "the secret is 1 to 256 printable characters, no space" "" "$SUIT" login wd alice
checkl login-secret-with-space 2 "the secret is 1 to 256" "two words" "$SUIT" login wd alice
checkl login-secret-with-control 2 "the secret is 1 to 256" "$(printf 'a\001b')" "$SUIT" login wd alice
checkl login-secret-too-long 1 "cannot read the secret" "$(head -c 300 /dev/zero | tr '\0' x)" "$SUIT" login wd alice
checkl login-secret-just-too-long-with-newline 2 "the secret is 1 to 256" "$(head -c 257 /dev/zero | tr '\0' x)" "$SUIT" login wd alice
checkl login-secret-longest 0 "" "$(head -c 256 /dev/zero | tr '\0' x)" "$SUIT" login wd alice
checkl login-bad-user 2 "not a user name" "$SECRET" "$SUIT" login wd 'a b'
checkl login-bad-name 2 "is not a wardrobe name" "$SECRET" "$SUIT" login 'a b' alice
check logout-bad-name 2 "is not a wardrobe name" -- "$SUIT" logout 'a b'
printf '%s\n' "$SECRET" | env SUIT_FAULT=read:1 "$SUIT" login wd alice >"$T/out" 2>"$T/err"; [ $? = 1 ] && grep -q "cannot read the secret" "$T/err" && pass login-stdin-read-fails || bad login-stdin-read-fails "$(cat "$T/err")"
printf '%s\n' "$SECRET" | env SUIT_FAULT=read:1:EINTR "$SUIT" login wd alice >"$T/out" 2>"$T/err"; [ $? = 0 ] && pass login-stdin-interrupted-retries || bad login-stdin-interrupted-retries "$(cat "$T/err")"
printf '%s\n' "$SECRET" | env SUIT_FAULT=rename:1 "$SUIT" login wd alice >"$T/out" 2>"$T/err"; [ $? = 1 ] && grep -q "cannot write $CRED: $EIO" "$T/err" && pass login-write-fails || bad login-write-fails "$(cat "$T/err")"
check logout-write-fails 1 "cannot write $CRED: $EIO" -- env SUIT_FAULT=rename:1 "$SUIT" logout wd
check logout-open-fails 1 "credentials:0: cannot read: $EIO" -- env SUIT_FAULT=open:1 "$SUIT" logout wd
check logout-stat-fails 1 "cannot look at it: $EIO" -- env SUIT_FAULT=stat:1 "$SUIT" logout wd
check logout-no-home 1 "" -- env -u SUIT_HOME HOME= "$SUIT" logout wd
printf '%s\n' "$SECRET" | env -u SUIT_HOME HOME= "$SUIT" login wd alice >/dev/null 2>&1; [ $? = 1 ] && pass login-no-home || bad login-no-home

# the credentials file: permissions and every strict error. The secret is
# never in a message.
printf 'wd alice %s\n' "$SECRET" > "$CRED"
for m in 640 604 660 666 644 620 602; do
    chmod $m "$CRED"
    printf '%s\n' "$SECRET" | "$SUIT" login wd alice >"$T/out" 2>"$T/err"
    [ $? = 1 ] && grep -q "credentials:0: group or other can use it" "$T/err" && pass "login-refuses-mode-$m" || bad "login-refuses-mode-$m" "$(cat "$T/err")"
    check "logout-refuses-mode-$m" 1 "group or other can use it" -- "$SUIT" logout wd
done
[ "$(cat "$CRED")" = "wd alice $SECRET" ] && pass refused-login-leaves-the-file || bad refused-login-leaves-the-file
chmod 400 "$CRED"
checkl login-over-a-read-only-owner-file 0 "" "$SECRET" "$SUIT" login wd bob
[ "$(ls -l "$CRED" | cut -c1-10)" = "-r--------" ] && pass login-keeps-the-mode-it-found || bad login-keeps-the-mode-it-found "$(ls -l "$CRED")"
chmod 600 "$CRED"
rm "$CRED"; mkdir "$CRED"
checkl login-refuses-a-folder 1 "not a regular file" "$SECRET" "$SUIT" login wd alice
rmdir "$CRED"
bad_creds() {
    printf '%s' "$2" > "$CRED"; chmod 600 "$CRED"
    printf '%s\n' "$SECRET" | "$SUIT" login wd alice >"$T/out" 2>"$T/err"
    [ $? = 1 ] && grep -q "credentials:$3" "$T/err" && pass "credentials-$1" || bad "credentials-$1" "$(cat "$T/err")"
    grep -q "$SECRET\|hunter2" "$T/out" "$T/err" && bad "credentials-$1-leaks" "$(cat "$T/err")"
}
bad_creds no-newline 'wd alice hunter2xx' "1: line has no newline"
bad_creds two-fields "wd alice
" "1: expected NAME USER SECRET"
bad_creds space-in-secret "wd alice hunter2 xx
" "1: expected NAME USER SECRET"
bad_creds bad-name "a/b alice hunter2xx
" "1: not a wardrobe name"
bad_creds bad-user "wd a@b hunter2xx
" "1: not a user name"
bad_creds control-in-secret "wd alice hunter$(printf '\001')2
" "1: the secret is 1 to 256"
bad_creds empty-secret "wd alice 
" "1: the secret is 1 to 256"
bad_creds four-fields "wd alice hunter2xx more
" "1: expected NAME USER SECRET"
bad_creds duplicate "wd alice hunter2xx
wd bob hunter3xx
" "2: duplicate login for wd"
printf 'wd alice hunter2\0xx\n' > "$CRED"
printf '%s\n' "$SECRET" | "$SUIT" login wd alice >"$T/out" 2>"$T/err"; [ $? = 1 ] && grep -q "credentials:1: NUL byte in line" "$T/err" && pass credentials-nul-byte || bad credentials-nul-byte "$(cat "$T/err")"
{ printf 'wd alice '; head -c 1400 /dev/zero | tr '\0' a; printf '\n'; } > "$CRED"
printf '%s\n' "$SECRET" | "$SUIT" login wd alice >"$T/out" 2>"$T/err"; [ $? = 1 ] && grep -q "credentials:1: line is over the limit" "$T/err" && pass credentials-line-too-long || bad credentials-line-too-long "$(cat "$T/err")"
head -c 70000 /dev/zero | tr '\0' a > "$CRED"
printf '%s\n' "$SECRET" | "$SUIT" login wd alice >"$T/out" 2>"$T/err"; [ $? = 1 ] && grep -q "credentials:0: file is 65537 bytes" "$T/err" && pass credentials-file-too-big || bad credentials-file-too-big "$(cat "$T/err")"
for i in $(seq 1 256); do echo "w$i alice $SECRET"; done > "$CRED"
printf '%s\n' "$SECRET" | "$SUIT" login w1 bob >"$T/out" 2>"$T/err"; [ $? = 0 ] && pass login-replaces-in-a-full-file || bad login-replaces-in-a-full-file "$(cat "$T/err")"
printf '%s\n' "$SECRET" | "$SUIT" login new alice >"$T/out" 2>"$T/err"; [ $? = 1 ] && grep -q "too many logins (limit 256)" "$T/err" && pass login-too-many || bad login-too-many "$(cat "$T/err")"
echo "w257 alice $SECRET" >> "$CRED"
check logout-too-many-in-file 1 "credentials:257: too many logins (limit 256)" -- "$SUIT" logout w1
for i in $(seq 1 250); do printf 'w%d alice %s\n' "$i" "$(head -c 250 /dev/zero | tr '\0' k)"; done > "$CRED"
chmod 600 "$CRED"
[ "$(wc -c < "$CRED" | tr -d ' ')" = 65392 ] && pass the-big-credentials-file-reads-as-it-should || bad the-big-credentials-file-reads-as-it-should "$(wc -c < "$CRED")"
printf '%s\n' "$(head -c 250 /dev/zero | tr '\0' y)" | "$SUIT" login zz alice >"$T/out" 2>"$T/err"; [ $? = 1 ] && grep -q "cannot write $CRED: " "$T/err" && pass login-file-too-big-to-write || bad login-file-too-big-to-write "$(cat "$T/err")"
rm -f "$CRED"

# the last corners of the two parsers
check remote-port-below-digits 2 "the port is 1 to 65535" -- "$SUIT" remote wd 'http://host:8-/p'
check remote-non-ascii 2 "printable characters only" -- "$SUIT" remote wd "http://host/$(printf '\303\251')"
checkl login-secret-non-ascii 2 "the secret is 1 to 256" "$(printf 's\303\251')" "$SUIT" login wd alice
checkl login-user-too-long 2 "not a user name" "$SECRET" "$SUIT" login wd "$(head -c 65 /dev/zero | tr '\0' u)"
printf 'wd file:///a b c\n' > "$SUIT_HOME/remotes"
check remotes-four-fields 1 "remotes:1: expected NAME URL" -- "$SUIT" remote wd
printf 'wd alice sec ret more\n' > "$CRED"; chmod 600 "$CRED"
printf '%s\n' "$SECRET" | "$SUIT" login wd alice >"$T/out" 2>"$T/err"; [ $? = 1 ] && grep -q "credentials:1: expected NAME USER SECRET" "$T/err" && pass credentials-five-fields || bad credentials-five-fields "$(cat "$T/err")"
printf 'wd file:///a\n' > "$SUIT_HOME/remotes"
check remote-read-interrupted-retries 0 "" -- env SUIT_FAULT=read:1:EINTR "$SUIT" remote wd
rm -f "$SUIT_HOME/remotes"
# a credentials file that overflows with entries still to write
for i in $(seq 1 250); do printf 'w%d alice %s\n' "$i" "$(head -c 250 /dev/zero | tr '\0' k)"; done > "$CRED"
echo 'zzz u s' >> "$CRED"; chmod 600 "$CRED"
printf '%s\n' "$(head -c 250 /dev/zero | tr '\0' y)" | "$SUIT" login w1a alice >"$T/out" 2>"$T/err"; [ $? = 1 ] && grep -q "cannot write $CRED: " "$T/err" && pass login-overflows-with-entries-left || bad login-overflows-with-entries-left "$(cat "$T/err")"
rm -f "$CRED"

# wrong argument counts
check remote-with-no-name 2 "usage:" -- "$SUIT" remote
check remote-with-too-many 2 "usage:" -- "$SUIT" remote wd http://h/p extra
check login-with-no-user 2 "usage:" -- "$SUIT" login wd
check logout-with-no-name 2 "usage:" -- "$SUIT" logout
check sync-with-no-name 2 "usage:" -- "$SUIT" sync

# ---- sync over file:// ---------------------------------------------------------
# libfossil's file:// channel runs stock `fossil test-http`, so these need it.

if have_fossil; then
RT=$T/net
rm -rf "$RT"; mkdir -p "$RT"
newremote() { # the remote's repository: the fixture, with fossil's own background process off
    cp "$FIXTURE" "$RT/R.fossil"
    fossil settings backoffice-disable 1 -R "$RT/R.fossil" >/dev/null 2>&1
}
newremote
mach() { # mach NAME: a machine with its own home, the fixture wardrobe as wd, its store open
    SUIT_HOME=$RT/$1; export SUIT_HOME; S=$SUIT_HOME/store/wd
    rm -rf "$SUIT_HOME"; mkdir -p "$SUIT_HOME/wardrobes"
    cp "$FIXTURE" "$SUIT_HOME/wardrobes/wd.fossil"
    "$SUIT" store open wd >/dev/null 2>&1
    "$SUIT" remote wd "file://$RT/R.fossil"
}
on() { SUIT_HOME=$RT/$1; export SUIT_HOME; S=$SUIT_HOME/store/wd; }
leaves() { fossil leaves -R "$RT/R.fossil" | grep -c '^ *('; }

mach A
mach B
on A
check sync-with-nothing-to-do 0 "" -- "$SUIT" sync wd
[ ! -s "$T/out" ] && [ ! -s "$T/err" ] && pass sync-with-nothing-to-do-says-nothing || bad sync-with-nothing-to-do-says-nothing "$(cat "$T/out" "$T/err")"
printf 'one\n' > "$S/new.txt"
check tend-checks-in-then-syncs 0 "" -- "$SUIT" tend wd
grep -q '^checked in' "$T/out" && pass tend-still-checks-in || bad tend-still-checks-in "$(cat "$T/out")"
fossil cat new.txt -r tip -R "$RT/R.fossil" > "$T/got" 2>/dev/null; [ "$(cat "$T/got")" = one ] && pass tend-pushed-its-check-in || bad tend-pushed-its-check-in
on B
check sync-brings-the-working-copy-forward 0 "" -- "$SUIT" sync wd
grep -q '^updated to' "$T/out" && pass sync-says-it-updated || bad sync-says-it-updated "$(cat "$T/out")"
[ "$(tree "$RT/A/store/wd")" = "$(tree "$RT/B/store/wd")" ] && pass two-machines-are-byte-identical || bad two-machines-are-byte-identical
check sync-again-is-quiet 0 "" -- "$SUIT" sync wd
[ ! -s "$T/out" ] && pass sync-again-says-nothing || bad sync-again-says-nothing "$(cat "$T/out")"
[ "$(leaves)" = 1 ] && pass remote-has-one-leaf || bad remote-has-one-leaf "$(leaves)"

# edits on both machines to different files merge cleanly
newremote; mach A; mach B
printf 'base\nmid\nend\n' > "$RT/A/store/wd/shared.txt"
on A; "$SUIT" tend wd >/dev/null 2>&1
on B; "$SUIT" sync wd >/dev/null 2>&1
echo 'a-only' > "$RT/A/store/wd/only-a.txt"
echo 'b-only' > "$RT/B/store/wd/only-b.txt"
on A; "$SUIT" tend wd >/dev/null 2>&1
printf 'alpha\n' > "$RT/B/machine"
on B; check tend-merges-a-fork 0 "" -- "$SUIT" tend wd
[ "$(leaves)" = 1 ] && pass clean-merge-leaves-one-leaf-on-the-remote || bad clean-merge-leaves-one-leaf-on-the-remote "$(leaves)"
fossil timeline -n 1 -R "$RT/R.fossil" | grep -q 'Merge edits from alpha' && pass merge-check-in-names-the-machine || bad merge-check-in-names-the-machine "$(fossil timeline -n 1 -R "$RT/R.fossil")"
[ -f "$RT/B/store/wd/only-a.txt" ] && [ -f "$RT/B/store/wd/only-b.txt" ] && pass merge-has-both-edits || bad merge-has-both-edits
on A; check sync-takes-the-merge 0 "" -- "$SUIT" sync wd
[ "$(tree "$RT/A/store/wd")" = "$(tree "$RT/B/store/wd")" ] && pass merged-machines-are-byte-identical || bad merged-machines-are-byte-identical
newremote; mach A; mach B
on A; echo a1 > "$S/p.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; echo b1 > "$S/q.txt"; "$SUIT" commit wd -m local >/dev/null 2>&1
check sync-merges-without-a-machine-name 0 "" -- "$SUIT" sync wd
fossil timeline -n 1 -R "$RT/R.fossil" | grep -q 'Merge edits from this machine' && pass merge-without-a-machine-file-says-this-machine || bad merge-without-a-machine-file-says-this-machine
# the same edit made on both machines
newremote; mach A; mach B
on A; echo same > "$S/s.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; echo same > "$S/s.txt"; "$SUIT" commit wd -m local >/dev/null 2>&1
check sync-merges-identical-edits 0 "" -- "$SUIT" sync wd
[ "$(leaves)" = 2 ] && [ "$(cat "$RT/B/store/wd/s.txt")" = same ] && [ ! -e "$RT/B/wd.journal" ] && pass identical-edits-change-nothing-and-the-fork-stays-open || bad identical-edits-change-nothing-and-the-fork-stays-open "$(leaves)"

# edits to the same lines: nothing in the working copy changes, the attention
# file says so, and the local check-ins still reach the remote
base_pair() { # base_pair FILE...: both machines hold these files, checked in
    newremote
    mach A; mach B; on A
    for f in "$@"; do printf 'one\ntwo\nthree\n' > "$S/$f"; done
    "$SUIT" tend wd >/dev/null 2>&1; on B; "$SUIT" sync wd >/dev/null 2>&1
}
conflict_outcome() { # conflict_outcome NAME N: B syncs against a remote A has changed
    on B; before=$(tree "$RT/B/store/wd")
    check "$1-exits-13" 13 "" -- "$SUIT" sync wd
    [ "$(tree "$RT/B/store/wd")" = "$before" ] && pass "$1-changes-no-file" || bad "$1-changes-no-file"
    [ "$(cat "$RT/B/attention")" = "conflict wd: $2 files changed both here and on the remote" ] && pass "$1-writes-the-attention-line" || bad "$1-writes-the-attention-line" "$(cat "$RT/B/attention")"
    grep -rq '<<<<<<<\|>>>>>>>' "$RT/B/store/wd" && bad "$1-writes-no-marker" || pass "$1-writes-no-marker"
    [ "$(leaves)" = 2 ] && pass "$1-pushes-the-local-check-in" || bad "$1-pushes-the-local-check-in" "$(leaves)"
    "$SUIT" sync wd >/dev/null 2>&1; [ "$(grep -c '^conflict' "$RT/B/attention")" = 1 ] && pass "$1-attention-is-not-repeated" || bad "$1-attention-is-not-repeated"
}
base_pair c.txt d.txt
on A; printf 'one\nA\nthree\n' > "$S/c.txt"; printf 'one\nA\nthree\n' > "$S/d.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; printf 'one\nB\nthree\n' > "$S/c.txt"; printf 'one\nB\nthree\n' > "$S/d.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1
conflict_outcome same-lines 2
grep -q 'conflict c.txt' "$T/out" && pass conflict-names-the-file || bad conflict-names-the-file "$(cat "$T/out")"
base_pair c.txt
on A; rm "$S/c.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; printf 'one\nB\nthree\n' > "$S/c.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1
conflict_outcome edit-and-delete 1
base_pair
on A; printf 'a\000b\n' > "$S/bin.dat"; "$SUIT" tend wd >/dev/null 2>&1
on B; printf 'a\000c\n' > "$S/bin.dat"; "$SUIT" commit wd -m b >/dev/null 2>&1
conflict_outcome added-both-sides-binary 1
base_pair bin.dat
on A; printf 'a\000b\n' > "$S/bin.dat"; "$SUIT" tend wd >/dev/null 2>&1
on B; printf 'a\000c\n' > "$S/bin.dat"; "$SUIT" commit wd -m b >/dev/null 2>&1
conflict_outcome binary-edited-both-sides 1
base_pair
on A; echo from-a > "$S/clash.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; echo mine > "$S/mine.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1; echo untracked > "$S/clash.txt"
conflict_outcome added-over-an-untracked-file 1
[ "$(cat "$RT/B/store/wd/clash.txt")" = untracked ] && pass untracked-file-is-kept || bad untracked-file-is-kept

base_pair c.txt
on A; printf 'one\nA\nthree\n' > "$S/c.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; rm "$S/c.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1
conflict_outcome delete-and-edit 1
base_pair c.txt d.txt
on A; rm "$S/c.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; printf 'one\nB\nthree\n' > "$S/d.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1
check delete-there-and-edit-another-file-merges 0 "" -- "$SUIT" sync wd
[ ! -e "$RT/B/store/wd/c.txt" ] && [ "$(sed -n 2p "$RT/B/store/wd/d.txt")" = B ] && pass delete-and-edit-of-different-files-merge || bad delete-and-edit-of-different-files-merge
base_pair c.txt d.txt
on A; rm "$S/c.txt"; printf 'one\nA\nthree\n' > "$S/d.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; printf 'one\nB\nthree\n' > "$S/c.txt"; printf 'one\nB\nthree\n' > "$S/d.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1
before=$(tree "$RT/B/store/wd")
"$SUIT" sync wd > "$T/out" 2>"$T/err"; [ $? = 13 ] && [ "$(grep -c '^conflict' "$T/out")" = 2 ] && grep -q '2 files changed both' "$RT/B/attention" && pass two-kinds-of-conflict-are-counted-together || bad two-kinds-of-conflict-are-counted-together "$(cat "$T/out")"
# a fork that does not conflict is merged even when the attention file holds an old conflict
base_pair c.txt
printf 'conflict wd: 1 files changed both here and on the remote\nlint other\n' > "$RT/B/attention"
on A; echo a > "$S/a.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; echo b > "$S/b.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1
check sync-merges-a-fork-after-an-old-conflict 0 "" -- "$SUIT" sync wd
[ "$(cat "$RT/B/attention")" = "lint other" ] && pass old-conflict-line-is-cleared-by-the-merge || bad old-conflict-line-is-cleared-by-the-merge "$(cat "$RT/B/attention")"
printf 'conflict wd: 1 files changed both here and on the remote\n' > "$RT/B/attention"
check sync-with-no-fork-clears-the-old-conflict 0 "" -- "$SUIT" sync wd
[ ! -e "$RT/B/attention" ] && pass no-fork-clears-the-conflict-line || bad no-fork-clears-the-conflict-line
printf 'conflict wd: 1 files changed both here and on the remote\n' > "$RT/B/attention"
check sync-cannot-clear-the-old-conflict 1 "" -- env SUIT_FAULT=unlink:1 "$SUIT" sync wd
# local changes: the pull is done, nothing in the working copy changes
newremote; mach A; mach B; on A; echo a > "$S/a.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; echo mine > "$S/run.sh"; before=$(tree "$RT/B/store/wd")
check sync-with-local-changes 12 "local changes: run suit commit or wait for suit tend" -- "$SUIT" sync wd
[ "$(tree "$RT/B/store/wd")" = "$before" ] && pass sync-with-local-changes-changes-no-file || bad sync-with-local-changes-changes-no-file
fossil timeline -n 1 -R "$RT/B/wardrobes/wd.fossil" | grep -q 'Edits on this machine' && pass sync-with-local-changes-still-pulls || bad sync-with-local-changes-still-pulls "$(fossil timeline -n 2 -R "$RT/B/wardrobes/wd.fossil")"
[ "$(leaves)" = 1 ] && pass sync-with-local-changes-pushes-nothing || bad sync-with-local-changes-pushes-nothing

# a remote that cannot be used: the message names it, the store stays as it was
newremote; mach A; on A
echo kept > "$S/keep.txt"; before=$(tree "$S")
"$SUIT" remote wd "file://$RT/nope.fossil"
check sync-remote-file-missing 17 "sync wd: $RT/nope.fossil failed" -- "$SUIT" sync wd
echo junk > "$RT/junk.fossil"
"$SUIT" remote wd "file://$RT/junk.fossil"
check sync-remote-not-a-repository 17 "sync wd: $RT/junk.fossil failed" -- "$SUIT" sync wd
"$SUIT" remote wd http://127.0.0.1:1/r
check sync-remote-refuses-connection 17 "sync wd: 127.0.0.1:1 failed" -- "$SUIT" sync wd
"$SUIT" remote wd https://example.invalid/r
check sync-https-is-refused 18 "this build of suit cannot use https yet" -- "$SUIT" sync wd
[ "$(tree "$S")" = "$before" ] && [ ! -e "$RT/A/attention" ] && pass failed-syncs-leave-the-store-and-attention-alone || bad failed-syncs-leave-the-store-and-attention-alone
"$SUIT" remote wd --none
check sync-without-a-remote-is-quiet 0 "" -- "$SUIT" sync wd
"$SUIT" remote wd "file://$RT/R.fossil"
check sync-of-a-missing-wardrobe 1 "no wardrobe at" -- "$SUIT" sync nothere
printf 'wd file://\n' > "$RT/A/remotes"
check sync-with-a-bad-remotes-file 1 "remotes:1:" -- "$SUIT" sync wd
rm "$RT/A/remotes"
"$SUIT" remote wd "file://$RT/R.fossil"
printf 'wd alice %s\n' "$SECRET" > "$RT/A/credentials"; chmod 644 "$RT/A/credentials"
check sync-refuses-open-credentials 1 "group or other can use it" -- "$SUIT" sync wd
grep -q "$SECRET" "$T/out" "$T/err" && bad open-credentials-secret-not-printed || pass open-credentials-secret-not-printed
rm "$RT/A/credentials"
printf 'from 1\nto 2\n' > "$RT/A/wd.journal"
check sync-with-an-unfinished-update 15 "unfinished update" -- "$SUIT" sync wd
check tend-with-an-unfinished-update 15 "unfinished update" -- "$SUIT" tend wd
rm "$RT/A/wd.journal"
printf 'bad name!\n' > "$RT/A/machine"
newremote; mach A; mach B
on A; echo a > "$S/a.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; echo b > "$S/b.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1; printf 'bad name!\n' > "$RT/B/machine"
before=$(tree "$RT/B/store/wd")
check sync-with-a-bad-machine-file 1 "not a machine name" -- "$SUIT" sync wd
[ "$(tree "$RT/B/store/wd")" = "$before" ] && [ ! -e "$RT/B/wd.journal" ] && pass bad-machine-file-changes-nothing || bad bad-machine-file-changes-nothing
rm "$RT/B/machine"
# the attention file cannot be written when a conflict is found: exit 1, nothing changed
base_pair c.txt
on A; printf 'one\nA\nthree\n' > "$S/c.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; printf 'one\nB\nthree\n' > "$S/c.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1
before=$(tree "$RT/B/store/wd")
check conflict-attention-write-fails 1 "" -- env SUIT_FAULT=rename:1 "$SUIT" sync wd
[ "$(tree "$RT/B/store/wd")" = "$before" ] && pass failed-attention-write-changes-no-file || bad failed-attention-write-changes-no-file

# every failed system call during a sync leaves the working copy whole: the
# files it had or the files it was going to have, never a mixture
sweep_fault() { # sweep_fault RT3:SCENARIO:FAULT,...: SCENARIO's setup in a private $RT, then calls 1 to 40 of each FAULT fail in turn
    # The private $RT is as deep and its name as long as $T/net, and the machines
    # and the remote are made in it, so the path the remote is recorded under is
    # the one it is read from: which step call number N falls in depends on both.
    RT=$T/${1%%:*}; swspec=${1#*:}; scen=${swspec%%:*}; swfaults=$(echo "${swspec#*:}" | tr , ' ')
    rm -rf "$RT"; mkdir -p "$RT"
    newremote; mach A; mach B
    on A; echo a > "$S/a.txt"; "$SUIT" tend wd >/dev/null 2>&1
    if [ "$scen" = forked ]; then on B; echo b > "$S/b.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1; fi
    cp -R "$RT/B" "$RT/Bsnap"; cp "$RT/R.fossil" "$RT/Rsnap"
    on B; want_before=$(tree "$RT/B/store/wd")
    "$SUIT" sync wd >/dev/null 2>&1; want_after=$(tree "$RT/B/store/wd")
    sbad=""; shits=0
    for sname in $swfaults; do
        sn=1
        while [ $sn -le 40 ]; do
            rm -rf "$RT/B"; cp -R "$RT/Bsnap" "$RT/B"; cp "$RT/Rsnap" "$RT/R.fossil"
            SUIT_FAULT=$sname:$sn "$SUIT" sync wd >/dev/null 2>&1; src=$?
            [ -e "$RT/B/wd.journal" ] && { "$SUIT" store repair wd >/dev/null 2>&1 || sbad="$sbad repair-$sname-$sn"; }
            now=$(tree "$RT/B/store/wd")
            if [ "$src" != 0 ]; then
                shits=$((shits + 1))
                { [ "$now" = "$want_before" ] || [ "$now" = "$want_after" ]; } || sbad="$sbad mixed-$sname-$sn"
                [ -z "$("$SUIT" store status wd 2>&1)" ] || sbad="$sbad dirty-$sname-$sn"
            fi
            sn=$((sn + 1))
        done
    done
    echo "$shits $sbad"
}
sweep() { # sweep SCENARIO (behind or forked): try every fault; side by side, one worker per fault
    sw_kind=$(echo "$1" | cut -c1); sw_all=rename,write,open,read,unlink,mkdir,fsync,stat
    if [ "${TEST_JOBS:-1}" -le 1 ]; then sw_list="${sw_kind}00:$1:$sw_all"
    else
        sw_list=; sw_i=0
        for sw_f in $(echo "$sw_all" | tr , ' '); do
            sw_i=$((sw_i + 1)); sw_list="$sw_list ${sw_kind}0$sw_i:$1:$sw_f"
        done
    fi
    # shellcheck disable=SC2086
    fan sweep_fault $sw_list
    sbad=""; shits=0
    for sw_w in $sw_list; do
        if read -r sh_n sh_bad <"$T/fan/sweep_fault.$sw_w" && [ -n "$sh_n" ]; then
            shits=$((shits + sh_n)); sbad="$sbad${sh_bad:+ $sh_bad}"
        else sbad="$sbad worker-$sw_w-gave-no-result"; fi
        rm -rf "$T/${sw_w%%:*}"
    done
    [ -z "$sbad" ] && [ "$shits" -gt 0 ] && pass "sweep-$1-leaves-the-working-copy-whole ($shits failures)" || bad "sweep-$1" "hits $shits:$sbad"
}
sweep behind
sweep forked

behind() { # what a clone of $1 left in $SUIT_HOME
    ls "$SUIT_HOME/wardrobes" 2>/dev/null | grep -F -- "$1"
    [ -e "$SUIT_HOME/store/$1" ] && echo "store/$1"
    grep -s "^$1 " "$SUIT_HOME/remotes"
}
nothing_behind() { [ -z "$(behind "$1")" ] && pass "$2" || bad "$2" "left: $(behind "$1" | tr '\n' ' ')"; }
newmachine() { SUIT_HOME=$RT/$1; export SUIT_HOME; S=$SUIT_HOME/store/wd; rm -rf "$SUIT_HOME"; }

if command -v nc >/dev/null 2>&1; then
# http:// against a loopback fossil server with a login
newremote; mach A
cp "$RT/R.fossil" "$RT/S.fossil"
fossil user new alice contact "$SECRET" -R "$RT/S.fossil" >/dev/null 2>&1
fossil user capabilities alice oir -R "$RT/S.fossil" >/dev/null 2>&1
fossil settings backoffice-disable 1 -R "$RT/S.fossil" >/dev/null 2>&1
PORT=
for try in 1 2 3 4 5 6 7 8; do
    p=$(awk 'BEGIN { srand(); print 20000 + int(rand() * 30000) + '$try' * 7 }')
    nc -z 127.0.0.1 "$p" >/dev/null 2>&1 && continue
    fossil server "$RT/S.fossil" --port "$p" --localhost >"$RT/server.log" 2>&1 &
    SERVER=$!
    ( sleep 240; kill $SERVER 2>/dev/null ) >/dev/null 2>&1 &
    trap 'kill $SERVER 2>/dev/null; rm -rf "$T"' EXIT INT TERM
    i=0; while [ $i -lt 50 ] && ! nc -z 127.0.0.1 "$p" >/dev/null 2>&1; do i=$((i+1)); sleep 0.2; done
    kill -0 $SERVER 2>/dev/null && nc -z 127.0.0.1 "$p" >/dev/null 2>&1 && { PORT=$p; break; }
done
[ -n "$PORT" ] || bad http-server-did-not-start "$(cat "$RT/server.log")"
on A; echo web > "$S/web.txt"; "$SUIT" commit wd -m web >/dev/null 2>&1
"$SUIT" remote wd "http://127.0.0.1:$PORT/"
printf '%s\n' "wrong-secret-1" | "$SUIT" login wd alice
check http-wrong-password-is-refused 19 "sync wd: 127.0.0.1:$PORT failed" -- "$SUIT" sync wd
grep -q "wrong-secret-1" "$T/out" "$T/err" && bad wrong-secret-not-printed || pass wrong-secret-not-printed
"$SUIT" logout wd
check http-without-a-login-is-refused 19 "" -- "$SUIT" sync wd
printf '%s\n' "$SECRET" | "$SUIT" login wd alice
check http-sync-with-a-login 0 "" -- "$SUIT" sync wd
fossil cat web.txt -r tip -R "$RT/S.fossil" > "$T/got" 2>/dev/null; [ "$(cat "$T/got")" = web ] && pass http-push-reached-the-server || bad http-push-reached-the-server
for f in "$RT/A/remotes" "$RT/A/attention" "$RT/server.log"; do [ -e "$f" ] && grep -q "$SECRET" "$f" && bad "secret-not-in-$(basename "$f")"; done
grep -rl "$SECRET" "$RT/A" "$T/out" "$T/err" | grep -v '/credentials$' | grep -q . && bad secret-only-in-the-credentials-file || pass secret-only-in-the-credentials-file
# the server is made private: nobody may clone or pull without the login
fossil user capabilities alice oirg -R "$RT/S.fossil" >/dev/null 2>&1
fossil user capabilities nobody "" -R "$RT/S.fossil" >/dev/null 2>&1
fossil user capabilities anonymous "" -R "$RT/S.fossil" >/dev/null 2>&1
# clone of a wardrobe that needs a login, over http
newmachine H
check http-clone-without-a-login-is-refused 19 "clone wd: 127.0.0.1:$PORT failed" -- "$SUIT" clone wd "http://127.0.0.1:$PORT/"
nothing_behind wd http-refused-clone-leaves-nothing
printf '%s\n' "wrong-secret-1" | "$SUIT" login wd alice
check http-clone-with-the-wrong-password-is-refused 19 "" -- "$SUIT" clone wd "http://127.0.0.1:$PORT/"
grep -q "wrong-secret-1" "$T/out" "$T/err" && bad clone-wrong-secret-not-printed || pass clone-wrong-secret-not-printed
nothing_behind wd http-wrong-password-clone-leaves-nothing
printf '%s\n' "$SECRET" | "$SUIT" login wd alice
check http-clone-with-a-login 0 "" -- "$SUIT" clone wd "http://127.0.0.1:$PORT/"
[ "$(tree "$RT/H/store/wd")" = "$(tree "$RT/A/store/wd")" ] && [ -f "$RT/H/store/wd/web.txt" ] && pass http-clone-is-byte-identical || bad http-clone-is-byte-identical
[ "$(cat "$RT/H/remotes")" = "wd http://127.0.0.1:$PORT/" ] && pass http-clone-remote-has-no-login || bad http-clone-remote-has-no-login "$(cat "$RT/H/remotes")"
grep -rl "$SECRET" "$RT/H" "$T/out" "$T/err" | grep -v '/credentials$' | grep -q . && bad clone-secret-only-in-the-credentials-file || pass clone-secret-only-in-the-credentials-file
echo more > "$RT/H/store/wd/more.txt"
check http-tend-after-clone 0 "" -- "$SUIT" tend wd
fossil cat more.txt -r tip -R "$RT/S.fossil" > "$T/got" 2>/dev/null; [ "$(cat "$T/got")" = more ] && pass http-tend-after-clone-pushed || bad http-tend-after-clone-pushed
# a refused login counts as a failed sync
printf '%s\n' "wrong-secret-1" | "$SUIT" login wd alice
for i in 1 2 3; do "$SUIT" tend wd >"$T/out" 2>"$T/err"; r=$?; done
[ $r = 19 ] && [ "$(cat "$RT/H/wd.syncfail")" = 3 ] && grep -q "^sync wd: failing since 3 tries: 127.0.0.1:$PORT\$" "$RT/H/attention" && pass refused-login-counts-as-a-failed-sync || bad refused-login-counts-as-a-failed-sync "$r $(cat "$RT/H/attention")"
grep -q "wrong-secret-1" "$RT/H/attention" "$RT/H/wd.syncfail" && bad failing-line-has-no-secret || pass failing-line-has-no-secret
kill $SERVER 2>/dev/null
else
    skip http-cases "nc is not installed"
fi

# a login kept for a file:// remote is not used
newremote; mach A; mach B
printf '%s\n' "$SECRET" | "$SUIT" login wd alice
on A; echo a > "$S/a.txt"; "$SUIT" commit wd -m a >/dev/null 2>&1
SUIT_HOME=$RT/A; export SUIT_HOME; printf '%s\n' "$SECRET" | "$SUIT" login wd alice
check sync-file-remote-ignores-the-login 0 "" -- "$SUIT" sync wd
# a file deleted here and untouched there merges cleanly
base_pair c.txt d.txt
on A; printf 'one\nA\nthree\n' > "$S/d.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; rm "$S/c.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1
check delete-here-and-edit-another-file-merges 0 "" -- "$SUIT" sync wd
[ ! -e "$RT/B/store/wd/c.txt" ] && [ "$(sed -n 2p "$RT/B/store/wd/d.txt")" = A ] && pass delete-here-merges-with-the-other-edit || bad delete-here-merges-with-the-other-edit

# both machines deleted the same file and edited different ones
base_pair c.txt
on A; rm "$S/c.txt"; echo a > "$S/a.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; rm "$S/c.txt"; echo b > "$S/b.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1
check both-delete-the-same-file-and-merge 0 "" -- "$SUIT" sync wd
[ ! -e "$RT/B/store/wd/c.txt" ] && [ -f "$RT/B/store/wd/a.txt" ] && pass both-deleted-file-stays-deleted || bad both-deleted-file-stays-deleted


# ---- clone -------------------------------------------------------------------------
# Machine A has the wardrobe and a remote; machine M gets it with suit clone.

newremote; mach A
on A; echo a > "$S/a.txt"; "$SUIT" tend wd >/dev/null 2>&1
newmachine M
check clone-over-file 0 "" -- "$SUIT" clone wd "file://$RT/R.fossil"
[ "$(cat "$T/out")" = "cloned wd" ] && pass clone-says-it-cloned || bad clone-says-it-cloned "$(cat "$T/out")"
[ "$(tree "$RT/A/store/wd")" = "$(tree "$RT/M/store/wd")" ] && [ -f "$RT/M/store/wd/a.txt" ] && pass clone-working-copy-is-byte-identical || bad clone-working-copy-is-byte-identical
[ "$(cat "$RT/M/remotes")" = "wd file://$RT/R.fossil" ] && pass clone-records-the-remote || bad clone-records-the-remote "$(cat "$RT/M/remotes")"
[ "$(ls "$RT/M/wardrobes")" = wd.fossil ] && pass clone-leaves-only-the-repository || bad clone-leaves-only-the-repository "$(ls "$RT/M/wardrobes")"
check clone-store-is-clean 0 "" -- "$SUIT" store status wd
[ ! -s "$T/out" ] && pass clone-store-status-is-empty || bad clone-store-status-is-empty "$(cat "$T/out")"
check clone-sync-has-nothing-to-do 0 "" -- "$SUIT" sync wd
[ ! -s "$T/out" ] && [ ! -s "$T/err" ] && pass clone-sync-is-quiet || bad clone-sync-is-quiet "$(cat "$T/out" "$T/err")"

# an edit on the clone reaches A through two syncs
on M; echo b > "$S/b.txt"
check clone-edit-reaches-the-remote 0 "" -- "$SUIT" tend wd
on A
check clone-edit-reaches-the-other-machine 0 "" -- "$SUIT" sync wd
[ "$(cat "$RT/A/store/wd/b.txt")" = b ] && [ "$(tree "$RT/A/store/wd")" = "$(tree "$RT/M/store/wd")" ] && pass clone-edit-arrived-byte-identical || bad clone-edit-arrived-byte-identical

# refusals
on M; before=$(tree "$S"); sum=$(cksum < "$SUIT_HOME/wardrobes/wd.fossil")
check clone-refuses-an-existing-wardrobe 20 "there is already a wardrobe or a store of that name here" -- "$SUIT" clone wd "file://$RT/R.fossil"
[ "$(tree "$S")" = "$before" ] && [ "$(cksum < "$SUIT_HOME/wardrobes/wd.fossil")" = "$sum" ] && pass clone-never-overwrites || bad clone-never-overwrites
mkdir -p "$SUIT_HOME/store/onlystore"
check clone-refuses-an-existing-store 20 "already a wardrobe or a store" -- "$SUIT" clone onlystore "file://$RT/R.fossil"
[ -z "$(ls "$SUIT_HOME/wardrobes" | grep onlystore)" ] && pass clone-existing-store-gets-no-repository || bad clone-existing-store-gets-no-repository
rmdir "$SUIT_HOME/store/onlystore"
newmachine N
check clone-bad-name 2 "is not a wardrobe name" -- "$SUIT" clone 'bad/name' "file://$RT/R.fossil"
check clone-relative-file 2 "needs an absolute path" -- "$SUIT" clone x file://rel/x
check clone-bad-scheme 2 "starts with file://, http:// or https://" -- "$SUIT" clone x ftp://h/p
check clone-user-in-address 2 "credentials do not go in the address" -- "$SUIT" clone x http://alice@h/p
check clone-password-in-address 2 "credentials do not go in the address" -- "$SUIT" clone x http://alice:hunter2xyz@h/p
grep -q hunter2xyz "$T/err" && bad clone-does-not-repeat-the-password || pass clone-does-not-repeat-the-password
check clone-https-is-refused 18 "this build of suit cannot use https yet" -- "$SUIT" clone x https://example.invalid/r
check clone-remote-file-missing 17 "clone x: $RT/nope.fossil failed" -- "$SUIT" clone x "file://$RT/nope.fossil"
echo junk > "$RT/junk.fossil"
check clone-remote-not-a-repository 17 "clone x: $RT/junk.fossil failed" -- "$SUIT" clone x "file://$RT/junk.fossil"
check clone-remote-refuses-connection 17 "clone x: 127.0.0.1:1 failed" -- "$SUIT" clone x http://127.0.0.1:1/r
nothing_behind x clone-refusals-leave-nothing-behind
[ ! -e "$RT/N/remotes" ] && pass clone-refusals-write-no-remotes-file || bad clone-refusals-write-no-remotes-file
check clone-without-a-home 1 "" -- env -u SUIT_HOME HOME= "$SUIT" clone x "file://$RT/R.fossil"
check clone-with-no-url 2 "usage:" -- "$SUIT" clone x

# every failed system call during a clone leaves nothing behind; a call that
# does not matter leaves the whole clone
clone_fault() { # clone_fault FAULT: calls 1, 2, ... of FAULT fail in turn, on a machine of its own
    fname=$1; cm=F.$1
    n=1; quiet=0; failures=0; badstate=
    while [ $n -le 80 ] && [ $quiet -lt 3 ]; do
        newmachine "$cm"
        env SUIT_FAULT=$fname:$n "$SUIT" clone wd "file://$RT/R.fossil" >"$T/out.$cm" 2>"$T/err.$cm"; rc=$?
        if [ $rc = 0 ]; then
            quiet=$((quiet + 1))
            [ "$(tree "$SUIT_HOME/store/wd")" = "$(tree "$RT/A/store/wd")" ] && [ -n "$(grep '^wd ' "$SUIT_HOME/remotes")" ] || badstate="$badstate $fname:$n-incomplete"
        else
            quiet=0; failures=$((failures + 1))
            [ -z "$(behind wd)" ] || badstate="$badstate $fname:$n-left:$(behind wd | tr '\n' ,)"
        fi
        n=$((n + 1))
    done
    [ -z "$badstate" ] && pass "clone-fault-$fname-is-clean-$failures-failures" || bad "clone-fault-$fname" "$badstate"
}
clone_faults="open read write close fsync stat fstatat rename mkdir unlink lstat listdir rmdir spawn wait4 getenv getcwd"
fan clone_fault $clone_faults
fan_show clone_fault $clone_faults
newmachine F
check clone-store-fault-says-what 1 "" -- env SUIT_FAULT=mkdir:3 "$SUIT" clone wd "file://$RT/R.fossil"
nothing_behind wd clone-store-fault-leaves-nothing

# ---- tend with no name ---------------------------------------------------------------
mkw() { # mkw NAME: wardrobe NAME in the current home, its store open, no remote
    cp "$FIXTURE" "$SUIT_HOME/wardrobes/$1.fossil"; "$SUIT" store open "$1" >/dev/null 2>&1
}
SUIT_HOME=$RT/T0; export SUIT_HOME; rm -rf "$SUIT_HOME"
check tend-all-with-no-home-folder 0 "" -- "$SUIT" tend
[ ! -s "$T/out" ] && [ ! -s "$T/err" ] && pass tend-all-with-no-wardrobes-says-nothing || bad tend-all-with-no-wardrobes-says-nothing "$(cat "$T/out" "$T/err")"
mkdir -p "$SUIT_HOME/wardrobes"
check tend-all-with-an-empty-folder 0 "" -- "$SUIT" tend
[ ! -s "$T/out" ] && [ ! -s "$T/err" ] && pass tend-all-with-an-empty-folder-says-nothing || bad tend-all-with-an-empty-folder-says-nothing "$(cat "$T/out" "$T/err")"
check tend-all-without-a-home 1 "" -- env -u SUIT_HOME HOME= "$SUIT" tend
check tend-all-cannot-list 1 "cannot list $SUIT_HOME/wardrobes: $EIO" -- env SUIT_FAULT=listdir:1 "$SUIT" tend
check tend-with-two-names 2 "usage:" -- "$SUIT" tend a b
# files that are not wardrobes are left alone
: > "$SUIT_HOME/wardrobes/notes.txt"; : > "$SUIT_HOME/wardrobes/.fossil"; : > "$SUIT_HOME/wardrobes/bad name.fossil"
: > "$SUIT_HOME/wardrobes/$(printf 'n%.0s' $(seq 1 129)).fossil"; : > "$SUIT_HOME/wardrobes/x.fossil.clone"; : > "$SUIT_HOME/wardrobes/fossil"
check tend-all-skips-what-is-not-a-wardrobe 0 "" -- "$SUIT" tend
[ ! -s "$T/out" ] && [ ! -s "$T/err" ] && pass tend-all-skips-quietly || bad tend-all-skips-quietly "$(cat "$T/out" "$T/err")"
rm -f "$SUIT_HOME"/wardrobes/*

# one wardrobe
mkw one
check tend-all-with-one-clean-wardrobe 0 "" -- "$SUIT" tend
[ ! -s "$T/out" ] && [ ! -s "$T/err" ] && pass tend-all-one-clean-says-nothing || bad tend-all-one-clean-says-nothing "$(cat "$T/out" "$T/err")"
echo x > "$SUIT_HOME/store/one/new.txt"
check tend-all-checks-in 0 "" -- "$SUIT" tend
grep -q '^checked in' "$T/out" && pass tend-all-says-it-checked-in || bad tend-all-says-it-checked-in "$(cat "$T/out")"

# three wardrobes; the middle one fails its lint, the others are still tended
rm -rf "$SUIT_HOME"; mkdir -p "$SUIT_HOME/wardrobes"
mkw cc; mkw aa; mkw bb
for w in aa bb cc; do echo "$w" > "$SUIT_HOME/store/$w/edit.txt"; done
printf 'token = abcdefghijklmnopqrstuvwxyz0123456789\n' > "$SUIT_HOME/store/bb/bad.txt"
"$SUIT" tend > "$T/out" 2> "$T/err"; rc=$?
[ $rc = 3 ] && pass tend-all-exits-with-the-failure || bad tend-all-exits-with-the-failure "exit $rc"
[ "$(grep -c '^suit: tend .*: did not end clean' "$T/err")" = 1 ] && grep -q '^suit: tend bb: did not end clean, exit 3$' "$T/err" && pass tend-all-names-the-wardrobe-that-failed || bad tend-all-names-the-wardrobe-that-failed "$(cat "$T/err")"
[ "$(grep -c '^checked in' "$T/out")" = 2 ] && pass tend-all-checked-in-the-others || bad tend-all-checked-in-the-others "$(cat "$T/out")"
for w in aa cc; do "$SUIT" store status $w > "$T/st"; [ ! -s "$T/st" ] || bad "tend-all-$w-is-clean" "$(cat "$T/st")"; done
"$SUIT" store status bb | grep -q 'bad.txt' && grep -q '^lint bb' "$SUIT_HOME/attention" && pass tend-all-leaves-the-lint-for-bb || bad tend-all-leaves-the-lint-for-bb
# the highest code wins, and lines come in name order
rm "$SUIT_HOME/store/bb/bad.txt"; echo again > "$SUIT_HOME/store/aa/more.txt"
printf 'token = abcdefghijklmnopqrstuvwxyz0123456789\n' > "$SUIT_HOME/store/aa/bad.txt"
"$SUIT" remote bb http://127.0.0.1:1/r; "$SUIT" remote cc https://example.invalid/r
"$SUIT" tend > "$T/out" 2> "$T/err"; rc=$?
[ $rc = 18 ] && pass tend-all-exits-with-the-highest-code || bad tend-all-exits-with-the-highest-code "exit $rc"
grep '^suit: tend ' "$T/err" | tr '\n' '|' > "$T/lines"
[ "$(cat "$T/lines")" = "suit: tend aa: did not end clean, exit 3|suit: tend bb: did not end clean, exit 17|suit: tend cc: did not end clean, exit 18|" ] && pass tend-all-reports-in-name-order || bad tend-all-reports-in-name-order "$(cat "$T/lines")"

# too many wardrobes
rm -rf "$SUIT_HOME"; mkdir -p "$SUIT_HOME/wardrobes"
for i in $(seq 1 1025); do : > "$SUIT_HOME/wardrobes/w$i.fossil"; done
check tend-all-refuses-too-many 1 "more than 1024 wardrobes" -- "$SUIT" tend

# a clone that fails after the store is open takes it all away again, even when
# the rollback itself cannot look at a file
for n in 1 2 3 4 5 6 7 8 9 10; do
    newmachine F
    env SUIT_FAULT=rename:$n,lstat:1 "$SUIT" clone wd "file://$RT/R.fossil" >"$T/out" 2>"$T/err"; rc=$?
    [ $rc -lt 99 ] || bad "clone-fault-rename-$n-and-lstat" "exit $rc"
done
pass clone-rollback-survives-lstat-failures

# ---- repeated sync failures ---------------------------------------------------------
newremote; mach A
CNT=$RT/A/wd.syncfail; ATT=$RT/A/attention
"$SUIT" remote wd http://127.0.0.1:1/r
check failed-sync-1 17 "" -- "$SUIT" tend wd
[ "$(cat "$CNT")" = 1 ] && [ ! -e "$ATT" ] && pass first-failure-is-counted-not-reported || bad first-failure-is-counted-not-reported "$(cat "$CNT") $(cat "$ATT" 2>&1)"
check failed-sync-2 17 "" -- "$SUIT" tend wd
[ "$(cat "$CNT")" = 2 ] && [ ! -e "$ATT" ] && pass second-failure-is-counted-not-reported || bad second-failure-is-counted-not-reported
check failed-sync-3 17 "" -- "$SUIT" tend wd
[ "$(cat "$ATT")" = "sync wd: failing since 3 tries: 127.0.0.1:1" ] && pass third-failure-reaches-the-attention-file || bad third-failure-reaches-the-attention-file "$(cat "$ATT" 2>&1)"
check failed-sync-4 17 "" -- "$SUIT" tend wd
[ "$(cat "$ATT")" = "sync wd: failing since 4 tries: 127.0.0.1:1" ] && [ "$(cat "$CNT")" = 4 ] && pass later-failures-update-the-line || bad later-failures-update-the-line "$(cat "$ATT" 2>&1)"
# other kinds of item stay
printf 'lint other\n  x:1: y\n' >> "$ATT"
"$SUIT" tend wd >/dev/null 2>&1
grep -q '^lint other' "$ATT" && grep -q 'failing since 5 tries' "$ATT" && pass failing-line-keeps-other-items || bad failing-line-keeps-other-items "$(cat "$ATT")"
# a sync that reaches the remote clears the count and the line
"$SUIT" remote wd "file://$RT/R.fossil"
check success-after-failures 0 "" -- "$SUIT" tend wd
[ ! -e "$CNT" ] && ! grep -q '^sync wd' "$ATT" && grep -q '^lint other' "$ATT" && pass success-clears-the-count-and-the-line || bad success-clears-the-count-and-the-line "$(cat "$ATT" 2>&1)"
check success-again-is-quiet 0 "" -- "$SUIT" tend wd
[ ! -e "$CNT" ] && pass nothing-to-clear-writes-nothing || bad nothing-to-clear-writes-nothing
# an https remote counts too
"$SUIT" remote wd https://example.invalid/r
check https-failure-is-counted 18 "" -- "$SUIT" tend wd
[ "$(cat "$CNT")" = 1 ] && pass https-failure-counts || bad https-failure-counts "$(cat "$CNT")"
# a sync that stops at local changes reached the remote
"$SUIT" remote wd "file://$RT/R.fossil"
check count-cleared-by-a-reachable-remote 0 "" -- "$SUIT" tend wd
[ ! -e "$CNT" ] && pass reachable-remote-clears-the-count || bad reachable-remote-clears-the-count
# the count stops at its limit
printf '999999\n' > "$CNT"; "$SUIT" remote wd http://127.0.0.1:1/r
check count-stops-at-the-limit 17 "" -- "$SUIT" tend wd
[ "$(cat "$CNT")" = 999999 ] && grep -q 'failing since 999999 tries' "$ATT" && pass count-saturates || bad count-saturates "$(cat "$CNT")"
# a count file that is not a count
"$SUIT" remote wd "file://$RT/R.fossil"
for val in '0' '' '1234567' 'x' '3' '01
' '1x
' '12
3
'; do
    printf '%s' "$val" > "$CNT"
    "$SUIT" tend wd >"$T/out" 2>"$T/err"; rc=$?
    [ $rc = 1 ] && grep -q "$CNT: not a count of failed syncs" "$T/err" && pass "bad-count-file-$(printf '%s' "$val" | tr -c 'a-z0-9' _)" || bad "bad-count-file" "exit $rc $(cat "$T/err")"
done
rm -f "$CNT"

hunt() { # hunt NAME WANT_RC WANT_MSG FAULT SETUP COMMAND...: the first call of FAULT's kind that gives both
    hn=$1; hrc=$2; hmsg=$3; hf=$4; hsetup=$5; shift 5; k=1
    while [ $k -le 80 ]; do
        eval "$hsetup"
        env SUIT_FAULT=$hf:$k "$@" >"$T/out" 2>"$T/err"; r=$?
        if [ "$r" = "$hrc" ] && grep -qF -- "$hmsg" "$T/err"; then pass "$hn"; return; fi
        k=$((k + 1))
    done
    bad "$hn" "never saw exit $hrc with '$hmsg'"
}
hunt count-file-unreadable 1 "$CNT: cannot read: $EIO" read 'printf "2\n" > "$CNT"' "$SUIT" tend wd
"$SUIT" remote wd http://127.0.0.1:1/r
hunt count-file-unwritable 17 "cannot write $CNT: $EIO" rename 'rm -f "$CNT"' "$SUIT" tend wd
"$SUIT" remote wd http://127.0.0.1:1/r
hunt remotes-unreadable-after-the-failure 17 "remotes:0: cannot read: $EIO" open 'printf "2\n" > "$CNT"' "$SUIT" tend wd
"$SUIT" remote wd "file://$RT/R.fossil"
hunt count-file-unremovable 1 "cannot remove $CNT: $EIO" unlink 'printf "2\n" > "$CNT"' "$SUIT" tend wd
rm -f "$CNT"
fi # end sync

# ---- upstreams ------------------------------------------------------------------------
# An upstream's files are taken from a folder onto the branch upstream-NAME of the
# wardrobe whose suit.conf defines it, and accepted into trunk (docs/upstreams.md).

UP=$T/upsrc
rm -rf "$UP"; mkdir -p "$UP"
INITIAL=65ea0738cc  # the fixture's first check-in, the empty one

outis() { # outis NAME WANT: stdout of the last check is exactly WANT
    if [ "$(cat "$T/out")" = "$2" ]; then pass "$1"; else bad "$1" "got: $(cat "$T/out")"; fi
}
errhas() { grep -qF -- "$2" "$T/err" && pass "$1" || bad "$1" "want '$2' in: $(cat "$T/err")"; }
outhas() { grep -qF -- "$2" "$T/out" && pass "$1" || bad "$1" "want '$2' in: $(cat "$T/out")"; }
rsum() { # what the wardrobe's repository holds (not its bytes: opening it rewrites some)
    if have_fossil; then
        fossil sql -R "$T/home/wardrobes/${1:-wd}.fossil" "SELECT (SELECT count(*) FROM blob), (SELECT max(rid) FROM blob), (SELECT count(*) FROM event), (SELECT count(*) FROM unsent), (SELECT count(*) FROM tagxref)"
    else echo na; fi
}
upatt() { cat "$T/home/attention" 2>/dev/null; }
recis() { # recis NAME PIN TESTNAME: upstreams/NAME holds a full hash, a space and PIN
    if grep -Eq "^[0-9a-f]{40,64} $2\$" "$store/wd/upstreams/$1" 2>/dev/null; then pass "$3"; else bad "$3" "$(cat "$store/wd/upstreams/$1" 2>&1)"; fi
}
upconf() { # upconf TEXT: the wardrobe's suit.conf, checked in
    printf '%s\n' "$1" > "$store/wd/suit.conf"
    "$SUIT" commit wd -m conf >/dev/null 2>&1
}
upfresh() { # upfresh NAME [EXTRA]: a home with the fixture as wd, its store open, and the upstream NAME at pin v1 into vendor
    fresh wd
    "$SUIT" store open wd >/dev/null 2>&1
    upconf "[outfit o]
[upstream $1]
pin = v1
into = vendor${2:+
$2}"
}
skill() { # skill DIR NAME [LINE2]: a skill folder with a five-line SKILL.md
    mkdir -p "$1/$2"
    printf -- '---\nname: %s\nline1\n%s\nline3\nline4\nline5\n' "$2" "${3:-line2}" > "$1/$2/SKILL.md"
}
settle_pin() { # settle_pin PIN: the config's pin
    sed "s/^pin = .*/pin = $1/" "$store/wd/suit.conf" > "$store/wd/suit.conf.new" && mv "$store/wd/suit.conf.new" "$store/wd/suit.conf"
    "$SUIT" commit wd -m "pin $1" >/dev/null 2>&1
}

# -- the proof: a local fix survives an update, a conflicting update waits for review
upfresh up
skill "$UP/v1" s1
printf 'two\n' > "$UP/v1/s2.txt"
check upstreams-before-a-take 0 "" -- "$SUIT" upstreams
outis upstreams-never-taken 'up: never taken (config v1)'
printf 'my edit\n' >> "$store/wd/run.sh"
printf 'mine\n' > "$store/wd/untracked.txt"
tree "$store/wd" > "$T/up-before"; rbefore=$(rsum)
check take-v1 0 "" -- "$SUIT" upstream up take "$UP/v1"
if grep -q '^upstream up at v1: checked in [0-9a-f]\{12\}$' "$T/out" && grep -qx 'upstream up: update waiting for review' "$T/out"; then pass take-says-what-it-did; else bad take-says-what-it-did "$(cat "$T/out")"; fi
if have_fossil; then [ "$(rsum)" != "$rbefore" ] && pass take-changes-the-wardrobe-repository || bad take-changes-the-wardrobe-repository; fi
tree "$store/wd" > "$T/up-after"
cmp -s "$T/up-before" "$T/up-after" && pass take-leaves-the-working-copy-and-its-edits-alone || bad take-leaves-the-working-copy-and-its-edits-alone "$(diff "$T/up-before" "$T/up-after")"
check status-after-take 0 "" -- "$SUIT" store status wd
if [ "$(sort "$T/out" | tr '\n' ' ')" = "added untracked.txt edited run.sh " ]; then pass take-keeps-local-changes-as-they-were; else bad take-keeps-local-changes-as-they-were "$(cat "$T/out")"; fi
[ "$(upatt)" = 'upstream up: update waiting for review' ] && pass take-leaves-one-attention-item || bad take-leaves-one-attention-item "$(upatt)"
check upstreams-after-take 0 "" -- "$SUIT" upstreams
outis upstreams-waiting 'up: waiting for review (taken v1, config v1)'
rm "$store/wd/untracked.txt"
check diff-with-local-changes 12 "local changes: run suit commit or wait for suit tend" -- "$SUIT" upstream up diff
check accept-with-local-changes 12 "local changes: run suit commit or wait for suit tend" -- "$SUIT" upstream up accept
[ "$(upatt)" = 'upstream up: update waiting for review' ] && pass accept-with-local-changes-leaves-the-item || bad accept-with-local-changes-leaves-the-item "$(upatt)"
"$SUIT" commit wd -m "my run.sh" >/dev/null 2>&1
check diff-v1-clean 0 "" -- "$SUIT" upstream up diff
outis diff-lists-the-adds 'add vendor/s1/SKILL.md
add vendor/s2.txt'
tree "$store/wd" > "$T/up-before"; rbefore=$(rsum)
check diff-changes-nothing 0 "" -- "$SUIT" upstream up diff
[ "$(rsum)" = "$rbefore" ] && [ "$(tree "$store/wd")" = "$(cat "$T/up-before")" ] && pass diff-changes-nothing-at-all || bad diff-changes-nothing-at-all
check accept-v1 0 "" -- "$SUIT" upstream up accept
recis up v1 record-after-v1
if grep -q '^upstream up: merged, checked in [0-9a-f]\{12\}$' "$T/out"; then pass accept-says-it-merged; else bad accept-says-it-merged "$(cat "$T/out")"; fi
[ -f "$store/wd/vendor/s1/SKILL.md" ] && [ "$(cat "$store/wd/vendor/s2.txt")" = two ] && pass accept-puts-the-files-in-the-working-copy || bad accept-puts-the-files-in-the-working-copy
[ ! -e "$T/home/attention" ] && pass accept-clears-the-attention-item || bad accept-clears-the-attention-item "$(upatt)"
check status-after-accept 0 "" -- "$SUIT" store status wd
[ ! -s "$T/out" ] && pass accept-leaves-the-working-copy-clean || bad accept-leaves-the-working-copy-clean "$(cat "$T/out")"
check upstreams-current 0 "" -- "$SUIT" upstreams
outis upstreams-says-current 'up: current (taken v1, config v1)'
check accept-again 0 "" -- "$SUIT" upstream up accept
outis accept-again-has-nothing 'upstream up: nothing to accept'
check diff-after-accept 0 "" -- "$SUIT" upstream up diff
outis diff-after-accept-says-nothing-to-accept 'upstream up: nothing to accept'

# a local edit to a taken file, then an update that changes another line of it
sed 's/^line2$/line2 LOCAL/' "$store/wd/vendor/s1/SKILL.md" > "$T/x" && cat "$T/x" > "$store/wd/vendor/s1/SKILL.md"
"$SUIT" commit wd -m "local fix" >/dev/null 2>&1
skill "$UP/v2" s1; sed 's/^line4$/line4 UP/' "$UP/v1/s1/SKILL.md" > "$UP/v2/s1/SKILL.md"
printf 'two\n' > "$UP/v2/s2.txt"
settle_pin v2
check take-v2 0 "" -- "$SUIT" upstream up take "$UP/v2"
check upstreams-v2 0 "" -- "$SUIT" upstreams
outis upstreams-waiting-again 'up: waiting for review (taken v2, config v2)'
check diff-v2 0 "" -- "$SUIT" upstream up diff
outis diff-lists-the-change 'change vendor/s1/SKILL.md'
check accept-v2 0 "" -- "$SUIT" upstream up accept
recis up v2 record-after-v2
if [ "$(cat "$store/wd/vendor/s1/SKILL.md")" = "$(printf -- '---\nname: s1\nline1\nline2 LOCAL\nline3\nline4 UP\nline5')" ]; then pass local-edit-and-upstream-change-are-both-there; else bad local-edit-and-upstream-change-are-both-there "$(cat "$store/wd/vendor/s1/SKILL.md")"; fi

# an update that rewrites the edited line waits for review
skill "$UP/v3" s1 'line2 THEIRS'; printf 'new\n' > "$UP/v3/s3.txt"; printf 'two\n' > "$UP/v3/s2.txt"
settle_pin v3
check take-v3 0 "" -- "$SUIT" upstream up take "$UP/v3"
tree "$store/wd" > "$T/up-before"; rbefore=$(rsum); abefore=$(upatt)
check accept-v3-conflicts 13 "" -- "$SUIT" upstream up accept
recis up v2 record-is-unchanged-by-a-conflict
outis accept-lists-the-conflict 'conflict vendor/s1/SKILL.md'
[ "$(tree "$store/wd")" = "$(cat "$T/up-before")" ] && pass conflict-leaves-trunks-files-byte-identical || bad conflict-leaves-trunks-files-byte-identical
[ "$(rsum)" = "$rbefore" ] && pass conflict-checks-nothing-in || bad conflict-checks-nothing-in
if grep -rq '^<<<<<<<\|^>>>>>>>\|^=======$' "$store/wd" --exclude=.fslckout; then bad conflict-writes-no-marker; else pass conflict-writes-no-marker; fi
[ "$(upatt)" = 'upstream up: 1 files conflict' ] && pass conflict-leaves-the-attention-item || bad conflict-leaves-the-attention-item "$(upatt)"
check status-after-conflict 0 "" -- "$SUIT" store status wd
[ ! -s "$T/out" ] && pass conflict-leaves-the-working-copy-clean || bad conflict-leaves-the-working-copy-clean "$(cat "$T/out")"
check upstreams-conflict 0 "" -- "$SUIT" upstreams
outis upstreams-says-conflict 'up: conflict (taken v3, config v3)'
check diff-v3 0 "" -- "$SUIT" upstream up diff
outis diff-lists-conflict-and-add-in-byte-order-of-path 'conflict vendor/s1/SKILL.md
add vendor/s3.txt'

# --mine and --theirs each settle it
cp -R "$T/home" "$T/home-conflict"
check accept-mine 0 "" -- "$SUIT" upstream up accept --mine vendor/s1/SKILL.md
if [ "$(cat "$store/wd/vendor/s1/SKILL.md")" = "$(printf -- '---\nname: s1\nline1\nline2 LOCAL\nline3\nline4 UP\nline5')" ] && [ "$(cat "$store/wd/vendor/s3.txt")" = new ]; then pass mine-keeps-trunks-file-and-merges-the-rest; else bad mine-keeps-trunks-file-and-merges-the-rest; fi
[ ! -e "$T/home/attention" ] && pass mine-clears-the-item || bad mine-clears-the-item "$(upatt)"
rm -rf "$T/home"; cp -R "$T/home-conflict" "$T/home"
check accept-theirs 0 "" -- "$SUIT" upstream up accept --theirs vendor/s1/SKILL.md
recis up v3 record-after-theirs
if [ "$(cat "$store/wd/vendor/s1/SKILL.md")" = "$(printf -- '---\nname: s1\nline1\nline2 THEIRS\nline3\nline4\nline5')" ] && [ "$(cat "$store/wd/vendor/s3.txt")" = new ]; then pass theirs-takes-the-upstreams-file-and-merges-the-rest; else bad theirs-takes-the-upstreams-file-and-merges-the-rest "$(cat "$store/wd/vendor/s1/SKILL.md")"; fi
check status-after-theirs 0 "" -- "$SUIT" store status wd
[ ! -s "$T/out" ] && pass theirs-leaves-the-working-copy-clean || bad theirs-leaves-the-working-copy-clean "$(cat "$T/out")"
check upstreams-after-theirs 0 "" -- "$SUIT" upstreams
outis upstreams-current-after-theirs 'up: current (taken v3, config v3)'

# -- every rule of a take
upfresh up
mkdir -p "$UP/dots/.git" "$UP/dots/.hidden-dir" "$UP/dots/s1/.cache"
skill "$UP/dots" s1
printf x > "$UP/dots/.git/config"; printf x > "$UP/dots/.env"; printf x > "$UP/dots/s1/.cache/x"; printf x > "$UP/dots/s1/.DS_Store"
ln -s /nonexistent "$UP/dots/.dotlink"
check take-skips-entries-that-start-with-a-dot 0 "" -- "$SUIT" upstream up take "$UP/dots"
"$SUIT" upstream up diff > "$T/out" 2>&1
outis dot-entries-at-any-depth-are-not-taken 'add vendor/s1/SKILL.md'

upfresh up
skill "$UP/link" s1; ln -s s1 "$UP/link/alias"
rb=$(rsum)
check take-refuses-a-symlink 1 "$UP/link/alias is a symlink; symlinks are not taken" -- "$SUIT" upstream up take "$UP/link"
[ "$(rsum)" = "$rb" ] && [ ! -e "$T/home/attention" ] && pass refused-symlink-changes-nothing || bad refused-symlink-changes-nothing
upfresh up
skill "$UP/link2" s1; ln -s ../x "$UP/link2/s1/deep"
check take-refuses-a-symlink-in-a-folder 1 "$UP/link2/s1/deep is a symlink" -- "$SUIT" upstream up take "$UP/link2"
upfresh up
skill "$UP/fifo" s1; mkfifo "$UP/fifo/pipe"
check take-refuses-what-is-not-a-file-or-a-folder 1 "$UP/fifo/pipe is neither a file nor a folder" -- "$SUIT" upstream up take "$UP/fifo"

# limits
upfresh up
mkdir -p "$UP/many"; i=0
while [ $i -lt 4097 ]; do : > "$UP/many/f$i"; i=$((i + 1)); done
rb=$(rsum)
check take-refuses-4097-files 1 "more than 4096 files; nothing is taken" -- "$SUIT" upstream up take "$UP/many"
[ "$(rsum)" = "$rb" ] && pass over-the-file-limit-checks-nothing-in || bad over-the-file-limit-checks-nothing-in
rm "$UP/many/f4096"
check take-4096-files 0 "" -- "$SUIT" upstream up take "$UP/many"
check diff-4096-files 0 "" -- "$SUIT" upstream up diff
[ "$(wc -l < "$T/out" | tr -d ' ')" = 4096 ] && pass diff-of-4096-files-lists-them-all || bad diff-of-4096-files-lists-them-all
check accept-4096-files 0 "" -- "$SUIT" upstream up accept
[ "$(find "$store/wd/vendor" -type f | wc -l | tr -d ' ')" = 4096 ] && pass accept-puts-4096-files-in-place || bad accept-puts-4096-files-in-place
upfresh up
mkdir -p "$UP/big"
for n in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16; do dd if=/dev/null of="$UP/big/f$n" bs=4194304 seek=1 count=0 2>/dev/null; done
check take-exactly-64-mib 0 "" -- "$SUIT" upstream up take "$UP/big"
upfresh up
printf x > "$UP/big/one-more"
rb=$(rsum)
check take-refuses-more-than-64-mib 1 "more than 64 MiB in all; nothing is taken" -- "$SUIT" upstream up take "$UP/big"
[ "$(rsum)" = "$rb" ] && pass over-the-size-limit-checks-nothing-in || bad over-the-size-limit-checks-nothing-in
rm -rf "$UP/big" "$UP/many"

# the lint
upfresh up
skill "$UP/lint" s1; printf 'token = abcdefghijklmnopqrstuvwxyz0123\n' >> "$UP/lint/s1/SKILL.md"
printf 'ghp_abcdefghij0123456789\n' > "$UP/lint/other.txt"
rb=$(rsum)
check take-lint-finding 3 "vendor/other.txt:1: token-shaped value" -- "$SUIT" upstream up take "$UP/lint"
errhas take-lists-every-finding "vendor/s1/SKILL.md:8: token-shaped value"
[ "$(rsum)" = "$rb" ] && [ ! -e "$T/home/attention" ] && pass lint-finding-checks-nothing-in || bad lint-finding-checks-nothing-in
upfresh up "trust = review"
printf 'allow vendor/other.txt\n' > "$store/wd/suit.lint"; "$SUIT" commit wd -m lint >/dev/null 2>&1
check take-suit-lint-allow-applies 3 "vendor/s1/SKILL.md:8" -- "$SUIT" upstream up take "$UP/lint"
if grep -q other.txt "$T/err"; then bad take-honours-allow-in-suit-lint "$(cat "$T/err")"; else pass take-honours-allow-in-suit-lint; fi
upfresh up
printf 'forbid zork\n' > "$store/wd/suit.lint"; "$SUIT" commit wd -m lint >/dev/null 2>&1
skill "$UP/forbid" s1 'a ZORK here'
check take-honours-forbid-in-suit-lint 3 "vendor/s1/SKILL.md:4: " -- "$SUIT" upstream up take "$UP/forbid"
upfresh up
printf 'bogus line\n' > "$store/wd/suit.lint"; "$SUIT" commit wd -m lint >/dev/null 2>&1
check take-reports-a-bad-suit-lint 3 "suit.lint:1: " -- "$SUIT" upstream up take "$UP/v1"
upfresh up
printf x > "$T/x"; dd if=/dev/null of="$UP/lint2" bs=5242880 seek=1 count=0 2>/dev/null
mkdir -p "$UP/lint3"; cp "$UP/lint2" "$UP/lint3/huge"
check take-refuses-a-file-over-4-mib 3 "vendor/huge: larger than 4 MiB, not scanned" -- "$SUIT" upstream up take "$UP/lint3"
# the skill rules apply wherever the files land under skills/
upfresh up "into = skills"
upconf "[upstream up]
pin = v1"
mkdir -p "$UP/sk/nomd" "$UP/sk/nohead" "$UP/sk/good"
printf 'text\n' > "$UP/sk/nomd/readme.txt"
printf 'not a header\n' > "$UP/sk/nohead/SKILL.md"
printf -- '---\nok\n' > "$UP/sk/good/SKILL.md"; printf 'x\n' > "$UP/sk/good/extra.md"; printf 'x\n' > "$UP/sk/plain.md"
mkdir -p "$UP/sk/zzzz"; printf -- '---\nok\n' > "$UP/sk/zzzz/SKILL.md"
check take-applies-the-skill-rules 3 "skills/nohead/SKILL.md:1: no header" -- "$SUIT" upstream up take "$UP/sk"
errhas take-reports-a-skill-without-skill-md "skills/nomd: no SKILL.md"
if grep -q 'skills/good\|skills/plain\|skills/zzzz' "$T/err"; then bad take-skill-rule-leaves-good-skills-alone "$(cat "$T/err")"; else pass take-skill-rule-leaves-good-skills-alone; fi
mkdir -p "$UP/sk2/last"; printf 'text\n' > "$UP/sk2/last/readme.txt"
check take-reports-the-last-skill-without-skill-md 3 "skills/last: no SKILL.md" -- "$SUIT" upstream up take "$UP/sk2"

# a file of your own at a path the take would write
upfresh up
mkdir -p "$store/wd/vendor/s1"; printf 'mine\n' > "$store/wd/vendor/s1/SKILL.md"; "$SUIT" commit wd -m mine >/dev/null 2>&1
tree "$store/wd" > "$T/up-before"; rb=$(rsum)
check take-refuses-a-clash-with-your-own-file 1 "vendor/s1/SKILL.md is a file of your own; the take would write over it" -- "$SUIT" upstream up take "$UP/v1"
if [ "$(rsum)" = "$rb" ] && [ ! -e "$T/home/attention" ] && [ "$(tree "$store/wd")" = "$(cat "$T/up-before")" ]; then pass clash-changes-nothing; else bad clash-changes-nothing; fi
if grep -q 's2.txt' "$T/err"; then bad clash-names-only-the-clashing-files "$(cat "$T/err")"; else pass clash-names-only-the-clashing-files; fi
# a file this upstream supplied and you edited is not a clash
upfresh up
"$SUIT" upstream up take "$UP/v1" >/dev/null 2>&1; "$SUIT" upstream up accept >/dev/null 2>&1
printf 'more\n' >> "$store/wd/vendor/s2.txt"; "$SUIT" commit wd -m edit >/dev/null 2>&1
settle_pin v2
check take-over-files-you-edited-is-no-clash 0 "" -- "$SUIT" upstream up take "$UP/v2"
# after an accept, a file of your own the accepted take did not have is still a clash
printf 'mine\n' > "$store/wd/vendor/mine.txt"; "$SUIT" commit wd -m mine >/dev/null 2>&1
rm -rf "$UP/v2mine"; cp -R "$UP/v2" "$UP/v2mine"; printf 'theirs\n' > "$UP/v2mine/mine.txt"
check take-refuses-a-clash-after-an-accept 1 "vendor/mine.txt is a file of your own; the take would write over it" -- "$SUIT" upstream up take "$UP/v2mine"
# two upstreams may not supply the same path
upfresh up "
[upstream up2]
pin = v1
into = vendor"
"$SUIT" upstream up take "$UP/v1" >/dev/null 2>&1
rb=$(rsum); ab=$(upatt)
check take-refuses-a-path-another-upstream-supplies 1 "vendor/s1/SKILL.md is also taken by upstream up" -- "$SUIT" upstream up2 take "$UP/v1"
if [ "$(rsum)" = "$rb" ] && [ "$(upatt)" = "$ab" ]; then pass two-upstreams-clash-changes-nothing; else bad two-upstreams-clash-changes-nothing; fi
if [ "$(grep -c 'vendor/' "$T/err")" = 2 ]; then pass two-upstreams-clash-names-each-file-once; else bad two-upstreams-clash-names-each-file-once "$(cat "$T/err")"; fi
"$SUIT" upstream up accept >/dev/null 2>&1
check take-refuses-it-once-the-other-is-in-trunk 1 "vendor/s1/SKILL.md is also taken by upstream up" -- "$SUIT" upstream up2 take "$UP/v1"
mkdir -p "$UP/other"; printf 'o\n' > "$UP/other/o.txt"
check take-of-another-path-is-fine 0 "" -- "$SUIT" upstream up2 take "$UP/other"
check upstreams-lists-both-by-name 0 "" -- "$SUIT" upstreams
outis upstreams-in-byte-order 'up: current (taken v1, config v1)
up2: waiting for review (taken v1, config v1)'
[ "$(upatt)" = 'upstream up2: update waiting for review' ] && pass items-are-kept-one-per-upstream || bad items-are-kept-one-per-upstream "$(upatt)"

# no change
upfresh up
"$SUIT" upstream up take "$UP/v1" >/dev/null 2>&1
rb=$(rsum); ab=$(upatt)
check take-again-is-no-change 0 "" -- "$SUIT" upstream up take "$UP/v1"
outis no-change-says-so 'upstream up: no change'
if [ "$(rsum)" = "$rb" ] && [ "$(upatt)" = "$ab" ]; then pass no-change-checks-nothing-in; else bad no-change-checks-nothing-in; fi
"$SUIT" upstream up accept >/dev/null 2>&1
check take-again-after-accept-is-no-change 0 "" -- "$SUIT" upstream up take "$UP/v1"
outis no-change-after-accept 'upstream up: no change'
[ ! -e "$T/home/attention" ] && pass no-change-leaves-no-item || bad no-change-leaves-no-item "$(upatt)"
# the executable bit is part of the tree
mkdir -p "$UP/x1"; printf '#!/bin/sh\n' > "$UP/x1/run.sh"; chmod +x "$UP/x1/run.sh"; printf 'p\n' > "$UP/x1/plain"
upfresh up
check take-an-executable 0 "" -- "$SUIT" upstream up take "$UP/x1"
"$SUIT" upstream up accept >/dev/null 2>&1
if [ -x "$store/wd/vendor/run.sh" ] && [ ! -x "$store/wd/vendor/plain" ]; then pass the-executable-bit-is-kept; else bad the-executable-bit-is-kept; fi
chmod -x "$UP/x1/run.sh"
check take-after-losing-the-bit-is-a-change 0 "" -- "$SUIT" upstream up take "$UP/x1"
outhas losing-the-bit-checks-in "checked in"
chmod +x "$UP/x1/plain"
check take-after-gaining-the-bit-is-a-change 0 "" -- "$SUIT" upstream up take "$UP/x1"
outhas gaining-the-bit-checks-in "checked in"
# a binary file
mkdir -p "$UP/bin"; printf 'a\000b\001\002\377' > "$UP/bin/blob.dat"
upfresh up
check take-a-binary-file 0 "" -- "$SUIT" upstream up take "$UP/bin"
"$SUIT" upstream up accept >/dev/null 2>&1
if [ "$(cksum < "$store/wd/vendor/blob.dat")" = "$(cksum < "$UP/bin/blob.dat")" ]; then pass a-binary-file-arrives-byte-for-byte; else bad a-binary-file-arrives-byte-for-byte; fi
# files the upstream no longer has are removed on the branch
upfresh up
"$SUIT" upstream up take "$UP/v1" >/dev/null 2>&1; "$SUIT" upstream up accept >/dev/null 2>&1
rm -rf "$UP/v1b"; mkdir -p "$UP/v1b"; skill "$UP/v1b" s1
settle_pin v2
check take-without-a-file 0 "" -- "$SUIT" upstream up take "$UP/v1b"
check diff-lists-the-removal 0 "" -- "$SUIT" upstream up diff
outis diff-says-remove 'remove vendor/s2.txt'
check accept-removes-the-file 0 "" -- "$SUIT" upstream up accept
[ ! -e "$store/wd/vendor/s2.txt" ] && [ -f "$store/wd/vendor/s1/SKILL.md" ] && pass the-removed-file-is-gone-from-the-working-copy || bad the-removed-file-is-gone-from-the-working-copy
if have_fossil; then
    [ "$(fossil ls -r upstream-up -R "$T/home/wardrobes/wd.fossil")" = "vendor/s1/SKILL.md" ] && pass the-branch-holds-only-the-upstreams-files || bad the-branch-holds-only-the-upstreams-files "$(fossil ls -r upstream-up -R "$T/home/wardrobes/wd.fossil")"
    first=$(fossil sql -R "$T/home/wardrobes/wd.fossil" "SELECT substr(uuid,1,10) FROM blob WHERE rid=(SELECT pid FROM plink WHERE cid=(SELECT pid FROM plink WHERE cid=(SELECT rid FROM tagxref WHERE tagid=(SELECT tagid FROM tag WHERE tagname='branch') AND value='upstream-up' ORDER BY mtime DESC LIMIT 1) LIMIT 1) LIMIT 1)")
    [ "$first" = "$INITIAL" ] && pass the-branch-starts-at-trunks-first-check-in || bad the-branch-starts-at-trunks-first-check-in "$first"
    [ "$(fossil timeline -n 0 -R "$T/home/wardrobes/wd.fossil" | grep -c '] upstream up at v')" = 2 ] && pass each-take-is-one-check-in || bad each-take-is-one-check-in
    fossil test-integrity -R "$T/home/wardrobes/wd.fossil" 2>&1 | grep -q ' 0 errors' && pass the-repository-passes-fossils-integrity-check || bad the-repository-passes-fossils-integrity-check
fi

# path: only that folder of the upstream is read
upfresh up "path = pkg/skills"
mkdir -p "$UP/pk/pkg/skills" "$UP/pk/docs"; skill "$UP/pk/pkg/skills" s1; printf 'd\n' > "$UP/pk/docs/readme.md"; printf 'top\n' > "$UP/pk/top.txt"
check take-reads-only-path 0 "" -- "$SUIT" upstream up take "$UP/pk"
"$SUIT" upstream up diff > "$T/out" 2>&1
outis path-entries-land-in-into 'add vendor/s1/SKILL.md'
upfresh up "path = a/.x"
mkdir -p "$UP/dp/a/.x"; skill "$UP/dp/a/.x" s1
check take-path-may-name-a-dot-folder 0 "" -- "$SUIT" upstream up take "$UP/dp"
upfresh up "path = nothing/there"
check take-path-missing 1 "cannot read $UP/pk/nothing/there: " -- "$SUIT" upstream up take "$UP/pk"
upfresh up "path = pkg/skills/s1/SKILL.md"
check take-path-is-not-a-folder 1 "pkg/skills/s1/SKILL.md is not a folder" -- "$SUIT" upstream up take "$UP/pk"
upfresh up "path = ../escape"
check take-path-with-dotdot 2 "path must be relative with no .. part, not ../escape" -- "$SUIT" upstream up take "$UP/pk"
upfresh up "path = /etc"
check take-absolute-path 2 "path must be relative with no .. part, not /etc" -- "$SUIT" upstream up take "$UP/pk"
upfresh up "path = ~/x"
check take-tilde-path 2 "path must be relative" -- "$SUIT" upstream up take "$UP/pk"
# into: nested, and the default
upfresh up "into = vendor/deep/er"
upconf "[upstream up]
pin = v1
into = vendor/deep/er"
"$SUIT" upstream up take "$UP/v1" >/dev/null 2>&1; "$SUIT" upstream up accept >/dev/null 2>&1
[ -f "$store/wd/vendor/deep/er/s1/SKILL.md" ] && pass into-can-be-a-nested-folder || bad into-can-be-a-nested-folder
upfresh up
upconf "[upstream up]
pin = v1"
"$SUIT" upstream up take "$UP/v1" >/dev/null 2>&1; "$SUIT" upstream up accept >/dev/null 2>&1
if [ -f "$store/wd/skills/s1/SKILL.md" ] && [ -f "$store/wd/skills/s2.txt" ] && [ -f "$store/wd/skills/alpha/SKILL.md" ]; then pass into-defaults-to-skills; else bad into-defaults-to-skills; fi
# the config
upfresh up
upconf "[upstream up]
into = vendor"
check take-needs-a-pin 2 "upstream up: the config has no pin; add pin = WORD to [upstream up]" -- "$SUIT" upstream up take "$UP/v1"
upconf "[upstream up]
into = vendor"
check upstreams-without-a-pin 0 "" -- "$SUIT" upstreams
outis upstreams-says-none-for-a-missing-pin 'up: never taken (config none)'
long=$(awk 'BEGIN { for (i = 0; i < 300; i++) printf "p"; print "" }')
upconf "[upstream up]
pin = $long
into = vendor"
check take-refuses-a-pin-over-256-bytes 2 "the pin is longer than 256 bytes" -- "$SUIT" upstream up take "$UP/v1"
upconf "[upstream up]
pin = v1
into = vendor"
check take-unknown-upstream 2 "no upstream nope in the config of any wardrobe" -- "$SUIT" upstream nope take "$UP/v1"
check accept-unknown-upstream 2 "no upstream nope in the config" -- "$SUIT" upstream nope accept
check diff-unknown-upstream 2 "no upstream nope in the config" -- "$SUIT" upstream nope diff
check take-folder-missing 1 "upstream up: cannot read $UP/nothing: " -- "$SUIT" upstream up take "$UP/nothing"
printf 'f\n' > "$UP/afile"
check take-folder-is-a-file 1 "$UP/afile is not a folder" -- "$SUIT" upstream up take "$UP/afile"
mkdir -p "$UP/empty"
check take-empty-folder 1 "$UP/empty holds no files to take" -- "$SUIT" upstream up take "$UP/empty"
mkdir -p "$UP/onlydots/.git"; printf x > "$UP/onlydots/.git/x"; printf x > "$UP/onlydots/.env"
check take-folder-of-only-dot-entries 1 "holds no files to take" -- "$SUIT" upstream up take "$UP/onlydots"
mkdir -p "$UP/noread"; printf 'x\n' > "$UP/noread/f"; mkdir "$UP/noread/sub"; printf 'x\n' > "$UP/noread/sub/g"
if [ "$(id -u)" != 0 ]; then
    chmod 000 "$UP/noread/sub"
    check take-folder-cannot-be-read 1 "cannot read $UP/noread/sub: " -- "$SUIT" upstream up take "$UP/noread"
    chmod 755 "$UP/noread/sub"
fi
longname=$(awk 'BEGIN { for (i = 0; i < 200; i++) printf "n"; print "" }')
mkdir -p "$UP/lp/$longname/$longname/$longname"; printf x > "$UP/lp/$longname/$longname/$longname/f"
check take-refuses-a-path-over-512-bytes 1 "a path is longer than 512 bytes" -- "$SUIT" upstream up take "$UP/lp"
deep=$UP/deep; mkdir -p "$deep"; d=$deep; i=0
while [ $i -lt 33 ]; do d=$d/d; mkdir "$d"; i=$((i + 1)); done
printf x > "$d/f"
check take-refuses-folders-nested-over-32-deep 1 "folders are nested more than 32 deep" -- "$SUIT" upstream up take "$deep"
d=$deep; i=0; while [ $i -lt 31 ]; do d=$d/d; i=$((i + 1)); done
rm -rf "$deep/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d"
printf x > "$deep/d/f"; rm -rf "$deep/d/d"
check take-folders-nested-32-deep-are-fine 0 "" -- "$SUIT" upstream up take "$deep"
verylong=$(awk 'BEGIN { for (i = 0; i < 5000; i++) printf "x"; print "" }')
check take-refuses-a-folder-path-over-4095-bytes 1 "the folder's path is longer than 4095 bytes" -- "$SUIT" upstream up take "$verylong"
# the journal, the wardrobe, the user
printf 'from x\nto y\n' > "$T/home/wd.journal"
check take-with-an-unfinished-update 15 "has an unfinished update" -- "$SUIT" upstream up take "$UP/v1"
check accept-with-an-unfinished-update 15 "has an unfinished update" -- "$SUIT" upstream up accept
check diff-with-an-unfinished-update 15 "has an unfinished update" -- "$SUIT" upstream up diff
check upstreams-with-an-unfinished-update 15 "has an unfinished update" -- "$SUIT" upstreams
rm "$T/home/wd.journal"
check take-without-a-user 1 "cannot tell who you are" -- env -u USER -u LOGNAME "$SUIT" upstream up take "$UP/v1"
mv "$T/home/wardrobes/wd.fossil" "$T/wd.fossil.keep"
check take-with-no-repository 1 "no wardrobe at $T/home/wardrobes/wd.fossil" -- "$SUIT" upstream up take "$UP/v1"
mv "$T/wd.fossil.keep" "$T/home/wardrobes/wd.fossil"
# usage
check upstream-usage-no-verb 2 "suit upstream NAME take FOLDER" -- "$SUIT" upstream up
check upstream-usage-bad-verb 2 "usage: suit upstream NAME take FOLDER" -- "$SUIT" upstream up bogus
check upstream-usage-take-without-a-folder 2 "usage" -- "$SUIT" upstream up take
check upstream-usage-take-with-two-folders 2 "usage" -- "$SUIT" upstream up take a b
check upstream-usage-diff-with-an-argument 2 "usage" -- "$SUIT" upstream up diff x
check upstream-usage-accept-odd-arguments 2 "usage" -- "$SUIT" upstream up accept --mine
check upstream-usage-accept-bad-option 2 "usage" -- "$SUIT" upstream up accept --bogus x
check upstream-usage-accept-bare-path 2 "usage" -- "$SUIT" upstream up accept x y
check upstreams-usage 2 "usage" -- "$SUIT" upstreams x
check upstream-both-theirs-and-mine 2 "p is named by both --theirs and --mine" -- "$SUIT" upstream up accept --theirs p --mine p
n=0; args=""
while [ $n -lt 65 ]; do args="$args --mine p$n"; n=$((n + 1)); done
# shellcheck disable=SC2086
check upstream-too-many-settle-paths 2 "more than 64 paths for --mine" -- "$SUIT" upstream up accept $args
# the home and the config
check upstream-no-home 1 "neither SUIT_HOME nor HOME is set" -- env -u SUIT_HOME -u HOME "$SUIT" upstreams
check upstream-long-home 1 "SUIT_HOME is longer than" -- env SUIT_HOME="$(awk 'BEGIN { for (i = 0; i < 4000; i++) printf "h"; print "" }')" "$SUIT" upstreams
mkdir -p "$T/nohome"
check upstreams-no-wardrobe 2 "no wardrobe with a suit.conf" -- env SUIT_HOME="$T/nohome" "$SUIT" upstreams
check upstream-no-wardrobe 2 "no wardrobe with a suit.conf" -- env SUIT_HOME="$T/nohome" "$SUIT" upstream up diff
printf '[bogus]\n' > "$store/wd/suit.conf"
check upstreams-bad-config 2 "suit.conf:1: unknown section kind" -- "$SUIT" upstreams
check upstream-bad-config 2 "suit.conf:1: unknown section kind" -- "$SUIT" upstream up accept
printf 'only a harness\n' > /dev/null
printf '[outfit o]\n' > "$store/wd/suit.conf"
check upstreams-with-none 0 "" -- "$SUIT" upstreams
[ ! -s "$T/out" ] && pass upstreams-with-none-prints-nothing || bad upstreams-with-none-prints-nothing "$(cat "$T/out")"

# -- trust = auto
upfresh up "trust = auto"
check take-auto-goes-on-to-accept 0 "" -- "$SUIT" upstream up take "$UP/v1"
outhas auto-says-it-took "upstream up at v1: checked in"
outhas auto-says-it-merged "upstream up: merged, checked in"
if grep -q 'waiting for review' "$T/out"; then bad auto-does-not-say-waiting "$(cat "$T/out")"; else pass auto-does-not-say-waiting; fi
[ -f "$store/wd/vendor/s1/SKILL.md" ] && [ ! -e "$T/home/attention" ] && pass auto-leaves-the-files-and-no-item || bad auto-leaves-the-files-and-no-item "$(upatt)"
check take-auto-again-is-no-change 0 "" -- "$SUIT" upstream up take "$UP/v1"
outis auto-no-change-does-not-accept 'upstream up: no change'
sed 's/^line2$/line2 LOCAL/' "$store/wd/vendor/s1/SKILL.md" > "$T/x" && cat "$T/x" > "$store/wd/vendor/s1/SKILL.md"
"$SUIT" commit wd -m local >/dev/null 2>&1
settle_pin v3
tree "$store/wd" > "$T/up-before"
check take-auto-with-a-conflict 13 "" -- "$SUIT" upstream up take "$UP/v3"
outhas auto-conflict-lists-it "conflict vendor/s1/SKILL.md"
[ "$(upatt)" = 'upstream up: 1 files conflict' ] && [ "$(tree "$store/wd")" = "$(cat "$T/up-before")" ] && pass auto-conflict-waits-for-review || bad auto-conflict-waits-for-review "$(upatt)"
upfresh up "trust = auto"
printf 'dirty\n' >> "$store/wd/run.sh"
check take-auto-with-local-changes 12 "local changes: run suit commit or wait for suit tend" -- "$SUIT" upstream up take "$UP/v1"
[ "$(upatt)" = 'upstream up: update waiting for review' ] && pass auto-with-local-changes-leaves-the-item || bad auto-with-local-changes-leaves-the-item "$(upatt)"

# -- accept and diff when there is nothing to take, or the working copy is behind
upfresh up
check accept-before-a-take 1 "upstream up: nothing has been taken yet; run suit upstream up take FOLDER" -- "$SUIT" upstream up accept
check diff-before-a-take 1 "nothing has been taken yet" -- "$SUIT" upstream up diff
printf 'upstream up: update waiting for review' > "$T/home/attention"
"$SUIT" upstream up take "$UP/v1" >/dev/null 2>&1
check upstreams-reads-an-attention-file-without-a-final-newline 0 "" -- "$SUIT" upstreams
outis upstreams-waiting-from-a-bare-last-line 'up: waiting for review (taken v1, config v1)'
printf 'upstream up: 2 files conflict' > "$T/home/attention"
"$SUIT" upstreams > "$T/out" 2>&1
outis upstreams-conflict-from-a-bare-last-line 'up: conflict (taken v1, config v1)'
printf 'lint other\n  a detail\nupstream up: update waiting for review\n' > "$T/home/attention"
"$SUIT" upstreams > "$T/out" 2>&1
outis upstreams-skips-the-detail-lines-of-other-items 'up: waiting for review (taken v1, config v1)'
printf 'lint other\nupstream up: stale\n  detail\nsync up: x\n' > "$T/home/attention"
"$SUIT" upstream up accept >/dev/null 2>&1
[ "$(upatt)" = "$(printf 'lint other\nsync up: x')" ] && pass accept-removes-only-its-own-item || bad accept-removes-only-its-own-item "$(upatt)"
printf 'upstream up: update waiting for review\nlint other\n' > "$T/home/attention"
check accept-after-accept-drops-a-stale-item 0 "" -- "$SUIT" upstream up accept
[ "$(upatt)" = 'lint other' ] && pass nothing-to-accept-drops-a-stale-item || bad nothing-to-accept-drops-a-stale-item "$(upatt)"
# the working copy is behind trunk's tip
upfresh up
"$SUIT" upstream up take "$UP/v1" >/dev/null 2>&1
rm -rf "$T/ahead"; mkdir -p "$T/ahead/wardrobes"
cp "$T/home/wardrobes/wd.fossil" "$T/ahead/wardrobes/wd.fossil"
SUIT_HOME="$T/ahead" "$SUIT" store open wd >/dev/null 2>&1
printf 'ahead\n' > "$T/ahead/store/wd/ahead.txt"
SUIT_HOME="$T/ahead" "$SUIT" commit wd -m ahead >/dev/null 2>&1
cp "$T/ahead/wardrobes/wd.fossil" "$T/home/wardrobes/wd.fossil"
check accept-behind-trunk 1 "the working copy of wd is not at trunk's tip; run suit store update wd first" -- "$SUIT" upstream up accept
check diff-behind-trunk 1 "not at trunk's tip" -- "$SUIT" upstream up diff
check upstreams-behind-trunk 0 "" -- "$SUIT" upstreams
outis upstreams-behind-trunk-still-waiting 'up: waiting for review (taken v1, config v1)'
"$SUIT" store update wd >/dev/null 2>&1
check accept-after-update 0 "" -- "$SUIT" upstream up accept

# -- suit back after an accept: libfossil cannot undo a merge once it is checked in, as after any check-in
upfresh up
"$SUIT" upstream up take "$UP/v1" >/dev/null 2>&1; "$SUIT" upstream up accept >/dev/null 2>&1
tree "$store/wd" > "$T/up-before"
check back-after-an-accept 14 "cannot go back: the store has changed since the update" -- "$SUIT" back wd
[ "$(tree "$store/wd")" = "$(cat "$T/up-before")" ] && pass back-after-an-accept-changes-nothing || bad back-after-an-accept-changes-nothing
check upstreams-after-back 0 "" -- "$SUIT" upstreams
outis upstreams-after-back-is-still-current 'up: current (taken v1, config v1)'

# -- conflicts of other kinds
mkbin() { printf '%s' "$2" > "$1"; }
upfresh up
mkdir -p "$UP/k1"; skill "$UP/k1" s1; mkbin "$UP/k1/b.bin" 'a\0b1'; printf 'gone\nsoon\n' > "$UP/k1/d.txt"; printf 'ee\nff\n' > "$UP/k1/e.txt"; printf 'k\n' > "$UP/k1/k.txt"
"$SUIT" upstream up take "$UP/k1" >/dev/null 2>&1; "$SUIT" upstream up accept >/dev/null 2>&1
printf 'a\000b2\377' > "$store/wd/vendor/b.bin"; printf 'gone\nsoon\nlocal\n' > "$store/wd/vendor/d.txt"; rm "$store/wd/vendor/e.txt"
"$SUIT" commit wd -m local >/dev/null 2>&1
mkdir -p "$UP/k2"; skill "$UP/k2" s1; printf 'a\000b3\377' > "$UP/k2/b.bin"; printf 'k\n' > "$UP/k2/k.txt"; printf 'ee\nff\nup\n' > "$UP/k2/e.txt"
printf 'brand new\n' > "$UP/k2/n.txt"; printf 'extra\n' > "$UP/k2/extra.txt"
# k2 has no d.txt: the upstream deleted it; local edited it. k2 edits e.txt; local deleted it. b.bin differs on both sides.
settle_pin v2
check take-k2 0 "" -- "$SUIT" upstream up take "$UP/k2"
printf 'untracked\n' > "$store/wd/vendor/n.txt"
check diff-every-kind 0 "" -- "$SUIT" upstream up diff
outis diff-lists-add-change-remove-and-conflicts 'conflict vendor/b.bin
conflict vendor/d.txt
conflict vendor/e.txt
add vendor/extra.txt
conflict vendor/n.txt'
tree "$store/wd" > "$T/up-before"
check accept-every-kind-conflicts 13 "" -- "$SUIT" upstream up accept
outis accept-lists-all-five 'conflict vendor/b.bin
conflict vendor/d.txt
conflict vendor/e.txt
conflict vendor/n.txt'
[ "$(upatt)" = 'upstream up: 4 files conflict' ] && pass the-item-counts-the-conflicts || bad the-item-counts-the-conflicts "$(upatt)"
[ "$(tree "$store/wd")" = "$(cat "$T/up-before")" ] && [ "$(cat "$store/wd/vendor/n.txt")" = untracked ] && pass nothing-changes-including-the-untracked-file || bad nothing-changes-including-the-untracked-file
check settle-a-file-added-over-an-untracked-file 2 "vendor/n.txt is not a conflict that --theirs or --mine can settle" -- "$SUIT" upstream up accept --theirs vendor/n.txt
check settle-a-file-that-is-no-conflict 2 "vendor/k.txt is not a conflict that --theirs or --mine can settle" -- "$SUIT" upstream up accept --mine vendor/k.txt
check settle-some-leaves-the-rest 13 "" -- "$SUIT" upstream up accept --mine vendor/b.bin --theirs vendor/d.txt
outis settle-some-lists-only-what-is-left 'conflict vendor/e.txt
conflict vendor/n.txt'
[ "$(upatt)" = 'upstream up: 2 files conflict' ] && pass the-item-counts-what-is-left || bad the-item-counts-what-is-left "$(upatt)"
rm "$store/wd/vendor/n.txt"
cp -R "$T/home" "$T/home-kinds"
check settle-all-four 0 "" -- "$SUIT" upstream up accept --theirs vendor/b.bin --theirs vendor/d.txt --mine vendor/e.txt
[ "$(printf 'a\000b3\377' | cksum)" = "$(cksum < "$store/wd/vendor/b.bin")" ] && pass theirs-takes-the-upstreams-binary || bad theirs-takes-the-upstreams-binary
[ ! -e "$store/wd/vendor/d.txt" ] && pass theirs-takes-the-upstreams-deletion || bad theirs-takes-the-upstreams-deletion
[ ! -e "$store/wd/vendor/e.txt" ] && pass mine-keeps-trunks-deletion || bad mine-keeps-trunks-deletion
[ "$(cat "$store/wd/vendor/n.txt")" = 'brand new' ] && [ "$(cat "$store/wd/vendor/extra.txt")" = extra ] && pass the-rest-is-merged || bad the-rest-is-merged
check status-after-settling-all 0 "" -- "$SUIT" store status wd
[ ! -s "$T/out" ] && pass settling-leaves-the-working-copy-clean || bad settling-leaves-the-working-copy-clean "$(cat "$T/out")"
rm -rf "$T/home"; cp -R "$T/home-kinds" "$T/home"
check settle-the-other-way 0 "" -- "$SUIT" upstream up accept --mine vendor/b.bin --mine vendor/d.txt --theirs vendor/e.txt
[ "$(printf 'a\000b2\377' | cksum)" = "$(cksum < "$store/wd/vendor/b.bin")" ] && pass mine-keeps-trunks-binary || bad mine-keeps-trunks-binary
[ "$(cat "$store/wd/vendor/d.txt")" = 'gone
soon
local' ] && pass mine-keeps-trunks-edit-of-a-file-the-upstream-deleted || bad mine-keeps-trunks-edit-of-a-file-the-upstream-deleted "$(cat "$store/wd/vendor/d.txt")"
[ "$(cat "$store/wd/vendor/e.txt")" = 'ee
ff
up' ] && pass theirs-brings-back-a-file-trunk-deleted || bad theirs-brings-back-a-file-trunk-deleted "$(cat "$store/wd/vendor/e.txt")"
check status-after-settling-the-other-way 0 "" -- "$SUIT" store status wd
[ ! -s "$T/out" ] && pass settling-the-other-way-leaves-it-clean || bad settling-the-other-way-leaves-it-clean "$(cat "$T/out")"
rm -rf "$T/home-kinds" "$T/home-conflict"
# settling with an executable file keeps its bit
upfresh up
mkdir -p "$UP/e1" "$UP/e2"; printf '#!/bin/sh\necho a\necho b\n' > "$UP/e1/x.sh"; chmod +x "$UP/e1/x.sh"
printf '#!/bin/sh\necho UP\necho b\n' > "$UP/e2/x.sh"; chmod +x "$UP/e2/x.sh"
"$SUIT" upstream up take "$UP/e1" >/dev/null 2>&1; "$SUIT" upstream up accept >/dev/null 2>&1
printf '#!/bin/sh\necho LOCAL\necho b\n' > "$store/wd/vendor/x.sh"; "$SUIT" commit wd -m local >/dev/null 2>&1
"$SUIT" upstream up take "$UP/e2" >/dev/null 2>&1
check settle-an-executable 0 "" -- "$SUIT" upstream up accept --theirs vendor/x.sh
if [ -x "$store/wd/vendor/x.sh" ] && grep -q UP "$store/wd/vendor/x.sh"; then pass settling-keeps-the-executable-bit; else bad settling-keeps-the-executable-bit; fi

# -- an accept always records itself in upstreams/NAME, so a merge that changes no file still checks in
upfresh up
mkdir -p "$UP/same"; printf 'two\n' > "$UP/same/s2.txt"
"$SUIT" upstream up take "$UP/same" >/dev/null 2>&1
mkdir -p "$store/wd/vendor"; printf 'two\n' > "$store/wd/vendor/s2.txt"; "$SUIT" commit wd -m same >/dev/null 2>&1
check accept-a-merge-that-changes-no-file 0 "" -- "$SUIT" upstream up accept
outhas the-merge-that-changes-no-file-checks-in "upstream up: merged, checked in"
[ ! -e "$T/home/attention" ] && [ ! -e "$T/home/wd.journal" ] && pass the-record-clears-the-item-and-leaves-no-journal || bad the-record-clears-the-item-and-leaves-no-journal "$(upatt)"
check upstreams-after-a-merge-that-changes-no-file 0 "" -- "$SUIT" upstreams
outis that-merge-ends-current 'up: current (taken v1, config v1)'
rec=$store/wd/upstreams/up
if grep -Eq '^[0-9a-f]{40,64} v1$' "$rec" && [ "$(wc -l < "$rec" | tr -d ' ')" = 1 ]; then pass the-record-is-the-hash-a-space-and-the-pin; else bad the-record-is-the-hash-a-space-and-the-pin "$(cat "$rec")"; fi
check status-after-the-record 0 "" -- "$SUIT" store status wd
[ ! -s "$T/out" ] && pass the-record-is-checked-in || bad the-record-is-checked-in "$(cat "$T/out")"
# --mine on the only conflict ends current
upfresh up
"$SUIT" upstream up take "$UP/v1" >/dev/null 2>&1; "$SUIT" upstream up accept >/dev/null 2>&1
r1=$(cat "$store/wd/upstreams/up")
sed 's/^line2$/line2 LOCAL/' "$store/wd/vendor/s1/SKILL.md" > "$T/x" && cat "$T/x" > "$store/wd/vendor/s1/SKILL.md"; "$SUIT" commit wd -m local >/dev/null 2>&1
rm -rf "$UP/v4"; skill "$UP/v4" s1 'line2 THEIRS'; printf 'two\n' > "$UP/v4/s2.txt"
settle_pin v4
"$SUIT" upstream up take "$UP/v4" >/dev/null 2>&1
check accept-fails-on-the-conflict-and-keeps-the-record 13 "" -- "$SUIT" upstream up accept
[ "$(cat "$store/wd/upstreams/up")" = "$r1" ] && pass a-conflict-leaves-the-record-alone || bad a-conflict-leaves-the-record-alone
check accept-mine-on-the-only-conflict 0 "" -- "$SUIT" upstream up accept --mine vendor/s1/SKILL.md
check upstreams-after-mine-on-the-only-conflict 0 "" -- "$SUIT" upstreams
outis mine-on-the-only-conflict-ends-current 'up: current (taken v4, config v4)'
[ ! -e "$T/home/attention" ] && pass mine-on-the-only-conflict-clears-the-item || bad mine-on-the-only-conflict-clears-the-item "$(upatt)"
r4=$(cat "$store/wd/upstreams/up")
if [ "$r4" != "$r1" ] && printf '%s\n' "$r4" | grep -Eq '^[0-9a-f]{40,64} v4$'; then pass the-record-follows-each-accept; else bad the-record-follows-each-accept "$r1 / $r4"; fi
# a malformed record means never accepted, and the next accept rewrites it
printf '%sX\n' "${r4%% *}" > "$store/wd/upstreams/up"; "$SUIT" commit wd -m "hash without the space" >/dev/null 2>&1
check upstreams-with-a-record-lacking-the-space 0 "" -- "$SUIT" upstreams
outis a-hash-without-a-space-is-malformed 'up: waiting for review (taken v4, config v4)'
printf 'garbage' > "$store/wd/upstreams/up"; "$SUIT" commit wd -m garbage >/dev/null 2>&1
check upstreams-with-a-malformed-record 0 "" -- "$SUIT" upstreams
outis a-malformed-record-means-never-accepted 'up: waiting for review (taken v4, config v4)'
rm -rf "$UP/v5"; skill "$UP/v5" s1; printf 'two\n' > "$UP/v5/s2.txt"; printf 'n\n' > "$UP/v5/n.txt"
settle_pin v5
"$SUIT" upstream up take "$UP/v5" >/dev/null 2>&1
check accept-rewrites-a-malformed-record 0 "" -- "$SUIT" upstream up accept
printf '%s\n' "$(cat "$store/wd/upstreams/up")" | grep -Eq '^[0-9a-f]{40,64} v5$' && pass the-malformed-record-is-rewritten || bad the-malformed-record-is-rewritten "$(cat "$store/wd/upstreams/up")"
# a failed write of the record leaves the wardrobe as it was
upfresh up
"$SUIT" upstream up take "$UP/v1" >/dev/null 2>&1
tree "$store/wd" > "$T/up-before"
hunt accept-record-write-fails 1 "cannot write $store/wd/upstreams/up" rename 'rm -rf "$store/wd/upstreams"' "$SUIT" upstream up accept

# -- two wardrobes, each with an upstream
upfresh up
mkdir -p "$T/home/wardrobes"; cp "$FIXTURE" "$T/home/wardrobes/other.fossil"
"$SUIT" store open other >/dev/null 2>&1
printf '[upstream op]\npin = o1\ninto = vendor2\n' > "$store/other/suit.conf"; "$SUIT" commit other -m conf >/dev/null 2>&1
mkdir -p "$UP/o1"; printf 'o\n' > "$UP/o1/o.txt"
check upstreams-lists-the-other-wardrobes-upstream 0 "" -- "$SUIT" upstreams
outis upstreams-from-two-wardrobes 'op: never taken (config o1)
up: never taken (config v1)'
check take-into-the-other-wardrobe 0 "" -- "$SUIT" upstream op take "$UP/o1"
"$SUIT" upstream up take "$UP/v1" >/dev/null 2>&1
"$SUIT" upstreams > "$T/out" 2>&1
outis each-upstream-has-its-own-state 'op: waiting for review (taken o1, config o1)
up: waiting for review (taken v1, config v1)'
check accept-in-the-other-wardrobe 0 "" -- "$SUIT" upstream op accept
[ -f "$store/other/vendor2/o.txt" ] && [ ! -e "$store/wd/vendor2" ] && [ ! -e "$store/wd/vendor" ] && pass the-files-land-in-the-defining-wardrobe || bad the-files-land-in-the-defining-wardrobe
"$SUIT" upstreams > "$T/out" 2>&1
outis one-accepted-one-waiting 'op: current (taken o1, config o1)
up: waiting for review (taken v1, config v1)'
if have_fossil; then
    if fossil branch ls -R "$T/home/wardrobes/other.fossil" | grep -q upstream-op && ! fossil branch ls -R "$T/home/wardrobes/other.fossil" | grep -q upstream-up && fossil branch ls -R "$T/home/wardrobes/wd.fossil" | grep -q upstream-up && ! fossil branch ls -R "$T/home/wardrobes/wd.fossil" | grep -q upstream-op; then pass each-branch-lives-in-the-wardrobe-that-defines-it; else bad each-branch-lives-in-the-wardrobe-that-defines-it; fi
fi
[ "$(upatt)" = 'upstream up: update waiting for review' ] && pass the-other-wardrobes-item-is-cleared-and-ours-kept || bad the-other-wardrobes-item-is-cleared-and-ours-kept "$(upatt)"

# -- an upstream and a wardrobe that share a name keep separate attention items
upfresh wd
"$SUIT" upstream wd take "$UP/v1" >/dev/null 2>&1
[ "$(upatt)" = 'upstream wd: update waiting for review' ] && pass same-name-take-leaves-the-item || bad same-name-take-leaves-the-item "$(upatt)"
check tend-of-the-same-name-wardrobe 0 "" -- "$SUIT" tend wd
[ "$(upatt)" = 'upstream wd: update waiting for review' ] && pass tend-keeps-the-upstream-item-of-its-name || bad tend-keeps-the-upstream-item-of-its-name "$(upatt)"
printf 'AKIAABCDEFGHIJKLMNOP\n' > "$store/wd/a.txt"
check tend-problem-of-the-same-name-wardrobe 3 "a.txt:1: token-shaped value" -- "$SUIT" tend wd
[ "$(upatt)" = "upstream wd: update waiting for review
lint wd
  a.txt:1: token-shaped value" ] && pass the-problem-item-and-the-upstream-item-coexist || bad the-problem-item-and-the-upstream-item-coexist "$(upatt)"
rm "$store/wd/a.txt"
check tend-clears-only-the-wardrobes-items 0 "" -- "$SUIT" tend wd
[ "$(upatt)" = 'upstream wd: update waiting for review' ] && pass tend-clears-the-problem-and-keeps-the-upstream-item || bad tend-clears-the-problem-and-keeps-the-upstream-item "$(upatt)"
printf 'conflict wd: 1 files changed both here and on the remote\n' >> "$T/home/attention"
check tend-clears-a-conflict-item-of-the-same-length-as-upstream 0 "" -- "$SUIT" tend wd
[ "$(upatt)" = 'upstream wd: update waiting for review' ] && pass tend-clears-a-conflict-item-and-keeps-the-upstream-item || bad tend-clears-a-conflict-item-and-keeps-the-upstream-item "$(upatt)"
printf 'lint wd\n  x\nheld wd: 1 of 9 files deleted\n' >> "$T/home/attention"
check accept-of-the-same-name-upstream 0 "" -- "$SUIT" upstream wd accept
[ "$(upatt)" = "lint wd
  x
held wd: 1 of 9 files deleted" ] && pass accept-removes-only-the-upstream-item || bad accept-removes-only-the-upstream-item "$(upatt)"
# a file written before the kinds were kept apart holds the same lines: read, and replaced and not repeated
upfresh up
printf 'upstream other: update waiting for review\nlint up\n  d\nupstream up: stale\n  old detail\n' > "$T/home/attention"
check take-reads-an-old-attention-file 0 "" -- "$SUIT" upstream up take "$UP/v1"
[ "$(upatt)" = "upstream other: update waiting for review
lint up
  d
upstream up: update waiting for review" ] && pass an-old-item-is-replaced-not-repeated || bad an-old-item-is-replaced-not-repeated "$(upatt)"
check upstreams-reads-the-old-attention-file 0 "" -- "$SUIT" upstreams
outis upstreams-from-an-old-attention-file 'up: waiting for review (taken v1, config v1)'
check accept-after-an-old-item 0 "" -- "$SUIT" upstream up accept
[ "$(upatt)" = "upstream other: update waiting for review
lint up
  d" ] && pass accept-replaces-the-old-item-too || bad accept-replaces-the-old-item-too "$(upatt)"

# -- the branch travels with the wardrobe: a take on one machine is seen on another
if have_fossil; then
unewremote() { # the remote's repository: the fixture, with fossil's own background process off
    cp "$FIXTURE" "$RT/R.fossil"
    fossil settings backoffice-disable 1 -R "$RT/R.fossil" >/dev/null 2>&1
}
umach() { # umach NAME: a machine with its own home, the fixture wardrobe as wd, its store open
    SUIT_HOME=$RT/$1; export SUIT_HOME; S=$SUIT_HOME/store/wd
    rm -rf "$SUIT_HOME"; mkdir -p "$SUIT_HOME/wardrobes"
    cp "$FIXTURE" "$SUIT_HOME/wardrobes/wd.fossil"
    "$SUIT" store open wd >/dev/null 2>&1
    "$SUIT" remote wd "file://$RT/R.fossil"
}
uon() { SUIT_HOME=$RT/$1; export SUIT_HOME; S=$SUIT_HOME/store/wd; }
RT=$T/upnet; rm -rf "$RT"; mkdir -p "$RT"
unewremote; umach A; umach B
uon A
printf '[upstream up]\npin = v1\ninto = vendor\n' > "$S/suit.conf"
"$SUIT" tend wd >/dev/null 2>&1
uon B; "$SUIT" sync wd >/dev/null 2>&1
uon A; check take-on-one-machine 0 "" -- "$SUIT" upstream up take "$UP/v1"
check sync-pushes-the-upstream-branch 0 "" -- "$SUIT" sync wd
[ "$(fossil branch ls -R "$RT/R.fossil" | grep -c upstream-up)" = 1 ] && pass the-remote-has-the-branch || bad the-remote-has-the-branch "$(fossil branch ls -R "$RT/R.fossil")"
fossil test-integrity -R "$RT/R.fossil" 2>&1 | grep -q ' 0 errors' && pass the-remote-passes-fossils-integrity-check || bad the-remote-passes-fossils-integrity-check
SUIT_HOME=$RT/C; export SUIT_HOME; rm -rf "$SUIT_HOME"
check clone-after-a-take 0 "" -- "$SUIT" clone wd "file://$RT/R.fossil"
check upstreams-after-a-clone 0 "" -- "$SUIT" upstreams
outis clone-carries-the-upstream-branch 'up: waiting for review (taken v1, config v1)'
uon B; tree "$S" > "$T/up-before"
check sync-after-a-take-on-another-machine 0 "" -- "$SUIT" sync wd
[ "$(tree "$S")" = "$(cat "$T/up-before")" ] && [ ! -e "$S/vendor" ] && pass an-upstream-branch-is-not-a-fork-of-trunk || bad an-upstream-branch-is-not-a-fork-of-trunk
[ "$(fossil timeline -n 0 -R "$RT/R.fossil" | grep -c 'Merge edits')" = 0 ] && [ ! -e "$RT/B/attention" ] && pass sync-merged-nothing-and-noted-nothing || bad sync-merged-nothing-and-noted-nothing
check upstreams-on-another-machine 0 "" -- "$SUIT" upstreams
outis a-take-is-seen-on-another-machine 'up: waiting for review (taken v1, config v1)'
check diff-on-another-machine 0 "" -- "$SUIT" upstream up diff
outis diff-on-another-machine-lists-the-adds 'add vendor/s1/SKILL.md
add vendor/s2.txt'
check accept-on-another-machine 0 "" -- "$SUIT" upstream up accept
check sync-pushes-the-accept 0 "" -- "$SUIT" sync wd
uon A
check sync-brings-the-accept-back 0 "" -- "$SUIT" sync wd
[ "$(tree "$RT/A/store/wd")" = "$(tree "$RT/B/store/wd")" ] && [ -f "$S/vendor/s1/SKILL.md" ] && pass the-accepted-files-reach-the-first-machine || bad the-accepted-files-reach-the-first-machine
[ ! -e "$RT/A/attention" ] && pass sync-drops-the-stale-item-of-an-accepted-upstream || bad sync-drops-the-stale-item-of-an-accepted-upstream "$(cat "$RT/A/attention")"
check upstreams-after-the-accept-arrives 0 "" -- "$SUIT" upstreams
outis the-first-machine-sees-it-current 'up: current (taken v1, config v1)'
check accept-on-the-first-machine-has-nothing-to-do 0 "" -- "$SUIT" upstream up accept
outis nothing-to-accept-on-the-first-machine 'upstream up: nothing to accept'
[ ! -e "$RT/A/attention" ] && pass its-stale-item-goes || bad its-stale-item-goes "$(cat "$RT/A/attention")"
# a real fork on trunk is still found when an upstream branch is the newest leaf
unewremote; umach A; umach B
uon A
printf '[upstream up]\npin = v1\ninto = vendor\n' > "$S/suit.conf"
"$SUIT" tend wd >/dev/null 2>&1
uon B; "$SUIT" sync wd >/dev/null 2>&1
uon A; printf 'a\n' > "$S/a.txt"; "$SUIT" tend wd >/dev/null 2>&1
"$SUIT" upstream up take "$UP/v1" >/dev/null 2>&1; "$SUIT" sync wd >/dev/null 2>&1
uon B; printf 'b\n' > "$S/b.txt"
check tend-merges-the-real-fork-and-not-the-branch 0 "" -- "$SUIT" tend wd
if [ -f "$S/a.txt" ] && [ -f "$S/b.txt" ] && [ ! -e "$S/vendor" ] && fossil timeline -n 0 -R "$RT/B/wardrobes/wd.fossil" | grep -q 'Merge edits'; then pass the-fork-rule-ignores-upstream-branches-but-keeps-real-forks; else bad the-fork-rule-ignores-upstream-branches-but-keeps-real-forks; fi
check upstreams-after-a-merged-fork 0 "" -- "$SUIT" upstreams
outis upstream-still-waiting-after-a-merged-fork 'up: waiting for review (taken v1, config v1)'
# two machines, two upstreams: the accept of one is synced, the other still waits
unewremote; umach A; umach B
uon A
printf '[upstream up]\npin = v1\ninto = vendor\n[upstream up2]\npin = v1\ninto = vendor2\n' > "$S/suit.conf"
"$SUIT" tend wd >/dev/null 2>&1
"$SUIT" upstream up take "$UP/v1" >/dev/null 2>&1; "$SUIT" upstream up2 take "$UP/v1" >/dev/null 2>&1
"$SUIT" sync wd >/dev/null 2>&1
uon B; "$SUIT" sync wd >/dev/null 2>&1
"$SUIT" upstream up accept >/dev/null 2>&1; "$SUIT" sync wd >/dev/null 2>&1
uon A
[ "$(cat "$RT/A/attention")" = "upstream up: update waiting for review
upstream up2: update waiting for review" ] && pass both-items-wait-before-the-sync || bad both-items-wait-before-the-sync "$(cat "$RT/A/attention")"
rm -rf "$RT/A.snap"; cp -R "$RT/A" "$RT/A.snap"
check sync-after-an-accept-elsewhere 0 "" -- "$SUIT" sync wd
[ "$(cat "$RT/A/attention")" = 'upstream up2: update waiting for review' ] && pass sync-drops-the-accepted-item-and-keeps-the-waiting-one || bad sync-drops-the-accepted-item-and-keeps-the-waiting-one "$(cat "$RT/A/attention")"
check upstreams-after-the-sync 0 "" -- "$SUIT" upstreams
outis one-current-one-waiting-after-the-sync 'up: current (taken v1, config v1)
up2: waiting for review (taken v1, config v1)'
# the record cannot be read, or the attention file cannot be read or written, while the item is dropped
ursnap() { rm -rf "$RT/A"; cp -R "$RT/A.snap" "$RT/A"; }
hunt reconcile-record-unreadable 1 "cannot read $RT/A/store/wd/upstreams/up" read ursnap "$SUIT" sync wd
hunt reconcile-attention-unreadable 1 "cannot open $RT/A/attention" open ursnap "$SUIT" sync wd
hunt reconcile-attention-unwritable 1 "cannot write $RT/A/attention" rename ursnap "$SUIT" sync wd
ursnap
rm -rf "$RT/A.snap"
fi

# -- undo: a new check-in on trunk that restores what the newest accept changed
UQ=$T/undosrc
rm -rf "$UQ"; mkdir -p "$UQ"
skill "$UQ/u1" s1; printf 'two\n' > "$UQ/u1/s2.txt"; printf 'gone\n' > "$UQ/u1/g.txt"; printf 'same\n' > "$UQ/u1/m.sh"
printf '#!/bin/sh\necho 1\n' > "$UQ/u1/x.sh"; chmod +x "$UQ/u1/x.sh"
skill "$UQ/u2" s1 'line2 NEW'; printf 'two\n' > "$UQ/u2/s2.txt"; printf 'three\n' > "$UQ/u2/s3.txt"; printf 'same\n' > "$UQ/u2/m.sh"; chmod +x "$UQ/u2/m.sh"
printf '#!/bin/sh\necho 2\n' > "$UQ/u2/x.sh"; chmod +x "$UQ/u2/x.sh"
notconf() { grep -v '^\./suit\.conf ' "$1"; }
utake() { "$SUIT" upstream up take "$1" >/dev/null 2>&1; }
uaccept() { "$SUIT" upstream up accept >/dev/null 2>&1; }

# the story: v1 taken and accepted, v2 taken and accepted, then undone twice
upfresh up
tree "$store/wd" > "$T/u-s0"
utake "$UQ/u1"; uaccept
rec1=$(cat "$store/wd/upstreams/up")
settle_pin v2
tree "$store/wd" > "$T/u-s1"
utake "$UQ/u2"; uaccept
tree "$store/wd" > "$T/u-s2"
rec2=$(cat "$store/wd/upstreams/up")
[ "$rec2" != "$rec1" ] && [ -x "$store/wd/vendor/x.sh" ] && [ -x "$store/wd/vendor/m.sh" ] && [ ! -e "$store/wd/vendor/g.txt" ] && pass the-second-accept-added-changed-and-removed-files || bad the-second-accept-added-changed-and-removed-files
check undo-the-second-accept 0 "" -- "$SUIT" upstream up undo
if grep -q '^upstream up: undone, checked in [0-9a-f]\{12\}$' "$T/out" && grep -qx 'upstream up: update waiting for review' "$T/out"; then pass undo-says-what-it-did; else bad undo-says-what-it-did "$(cat "$T/out")"; fi
[ "$(tree "$store/wd")" = "$(cat "$T/u-s1")" ] && pass undo-restores-the-files-of-the-first-accept-byte-for-byte || bad undo-restores-the-files-of-the-first-accept-byte-for-byte "$(tree "$store/wd" | diff - "$T/u-s1")"
[ ! -x "$store/wd/vendor/m.sh" ] && [ -x "$store/wd/vendor/x.sh" ] && [ "$(cat "$store/wd/vendor/g.txt")" = gone ] && [ ! -e "$store/wd/vendor/s3.txt" ] && pass undo-brings-back-a-removed-file-and-a-mode || bad undo-brings-back-a-removed-file-and-a-mode
[ "$(cat "$store/wd/upstreams/up")" = "$rec1" ] && pass undo-puts-the-record-back-to-the-first-accept || bad undo-puts-the-record-back-to-the-first-accept "$(cat "$store/wd/upstreams/up")"
recis up v1 the-record-names-the-first-tip-and-pin
check status-after-undo 0 "" -- "$SUIT" store status wd
[ ! -s "$T/out" ] && pass undo-leaves-the-working-copy-clean || bad undo-leaves-the-working-copy-clean "$(cat "$T/out")"
check upstreams-after-undo 0 "" -- "$SUIT" upstreams
outis undo-leaves-the-upstream-waiting 'up: waiting for review (taken v2, config v2)'
[ "$(upatt)" = 'upstream up: update waiting for review' ] && pass undo-leaves-the-item-of-a-take || bad undo-leaves-the-item-of-a-take "$(upatt)"
[ ! -e "$T/home/wd.journal" ] && pass undo-leaves-no-journal || bad undo-leaves-no-journal
if have_fossil; then
    fossil timeline -n 3 -R "$T/home/wardrobes/wd.fossil" > "$T/tl"
    grep -q 'Undo upstream up at v2' "$T/tl" && pass undo-is-checked-in-as-undo-upstream-at-the-pin || bad undo-is-checked-in-as-undo-upstream-at-the-pin "$(cat "$T/tl")"
    [ "$(fossil sql -R "$T/home/wardrobes/wd.fossil" "SELECT count(*) FROM plink WHERE cid=(SELECT objid FROM event ORDER BY mtime DESC LIMIT 1)")" = 1 ] && pass undo-has-one-parent || bad undo-has-one-parent
    [ "$(fossil branch ls -R "$T/home/wardrobes/wd.fossil" | grep -c trunk)" = 1 ] && pass undo-stays-on-trunk || bad undo-stays-on-trunk
fi
# diff lists what accepting the undone update again would change, against the check-in the record names
tree "$store/wd" > "$T/u-b"; rbefore=$(rsum)
check diff-after-undo 0 "" -- "$SUIT" upstream up diff
outis diff-after-undo-lists-the-undone-changes 'remove vendor/g.txt
change vendor/s1/SKILL.md
add vendor/s3.txt
change vendor/x.sh'
[ ! -s "$T/err" ] && pass diff-after-undo-says-nothing-else || bad diff-after-undo-says-nothing-else "$(cat "$T/err")"
[ "$(tree "$store/wd")" = "$(cat "$T/u-b")" ] && [ "$(rsum)" = "$rbefore" ] && [ "$(upatt)" = 'upstream up: update waiting for review' ] && pass diff-after-undo-changes-nothing || bad diff-after-undo-changes-nothing
check undo-again 0 "" -- "$SUIT" upstream up undo
[ "$(notconf "$T/u-s0")" = "$(tree "$store/wd" | grep -v '^\./suit\.conf ')" ] && pass undo-twice-restores-the-state-before-any-accept || bad undo-twice-restores-the-state-before-any-accept "$(tree "$store/wd" | diff - "$T/u-s0")"
[ ! -e "$store/wd/upstreams/up" ] && [ ! -e "$store/wd/vendor" ] && pass undo-twice-removes-the-record-file || bad undo-twice-removes-the-record-file
check upstreams-after-two-undos 0 "" -- "$SUIT" upstreams
outis two-undos-leave-the-upstream-waiting 'up: waiting for review (taken v2, config v2)'
check undo-a-third-time 0 "" -- "$SUIT" upstream up undo
outis a-third-undo-has-nothing-to-undo 'upstream up: nothing to undo'
check status-after-a-third-undo 0 "" -- "$SUIT" store status wd
[ ! -s "$T/out" ] && pass a-third-undo-changes-nothing || bad a-third-undo-changes-nothing "$(cat "$T/out")"

# a file changed since the accept is a conflict: nothing changes; one the accept did not touch does not block
upfresh up
utake "$UQ/u1"; uaccept; settle_pin v2; utake "$UQ/u2"; uaccept
printf 'edit\n' >> "$store/wd/vendor/s3.txt"; printf 'back\n' > "$store/wd/vendor/g.txt"
sed 's/^line2 NEW$/line2 MINE/' "$store/wd/vendor/s1/SKILL.md" > "$T/x" && cat "$T/x" > "$store/wd/vendor/s1/SKILL.md"
printf 'mine\n' >> "$store/wd/vendor/s2.txt"
"$SUIT" commit wd -m local >/dev/null 2>&1
tree "$store/wd" > "$T/u-b"; rbefore=$(rsum)
check undo-conflicts 13 "suit: upstream up: 3 files conflict; undo changed nothing" -- "$SUIT" upstream up undo
outis undo-lists-the-conflicts-in-byte-order 'conflict vendor/g.txt
conflict vendor/s1/SKILL.md
conflict vendor/s3.txt'
[ "$(tree "$store/wd")" = "$(cat "$T/u-b")" ] && [ "$(rsum)" = "$rbefore" ] && [ ! -e "$T/home/attention" ] && [ ! -e "$T/home/wd.journal" ] && pass a-conflicting-undo-changes-nothing || bad a-conflicting-undo-changes-nothing
check upstreams-after-a-conflicting-undo 0 "" -- "$SUIT" upstreams
outis a-conflicting-undo-leaves-the-upstream-current 'up: current (taken v2, config v2)'
upfresh up
utake "$UQ/u1"; uaccept; settle_pin v2; utake "$UQ/u2"; uaccept
printf 'mine\n' >> "$store/wd/vendor/s2.txt"; printf 'other\n' > "$store/wd/own.txt"
"$SUIT" commit wd -m local >/dev/null 2>&1
check undo-with-an-edit-the-accept-did-not-touch 0 "" -- "$SUIT" upstream up undo
[ "$(cat "$store/wd/vendor/s2.txt")" = "$(printf 'two\nmine')" ] && [ "$(cat "$store/wd/own.txt")" = other ] && [ "$(cat "$store/wd/vendor/g.txt")" = gone ] && pass an-edit-to-an-untouched-file-survives-the-undo || bad an-edit-to-an-untouched-file-survives-the-undo "$(cat "$store/wd/vendor/s2.txt")"
check status-after-an-undo-with-an-edit 0 "" -- "$SUIT" store status wd
[ ! -s "$T/out" ] && pass that-undo-leaves-the-working-copy-clean || bad that-undo-leaves-the-working-copy-clean "$(cat "$T/out")"
# the record changed by hand is a conflict too, a whole one that names no check-in as well
upfresh up
utake "$UQ/u1"; uaccept
printf '%s v9\n' "$(printf 'f%.0s' $(seq 1 40))" > "$store/wd/upstreams/up"; "$SUIT" commit wd -m "record by hand" >/dev/null 2>&1
check undo-with-a-record-changed-by-hand 13 "1 files conflict" -- "$SUIT" upstream up undo
outis a-record-changed-by-hand-conflicts 'conflict upstreams/up'
settle_pin v2; mkdir -p "$UQ/u9"; skill "$UQ/u9" s1 'line2 NINE'; utake "$UQ/u9"
check accept-with-a-whole-record-that-names-nothing 0 "" -- "$SUIT" upstream up accept
recis up v2 that-accept-writes-the-record-again
# a record longer than any whole one: a take and an accept read it as no record of a check-in
upfresh up
utake "$UQ/u1"; uaccept
printf '%s v9\n' "$(printf 'f%.0s' $(seq 1 600))" > "$store/wd/upstreams/up"; "$SUIT" commit wd -m "long record by hand" >/dev/null 2>&1
settle_pin v2
check take-with-a-long-record 0 "" -- "$SUIT" upstream up take "$UQ/u2"
check accept-with-a-long-record 0 "" -- "$SUIT" upstream up accept
recis up v2 that-accept-writes-a-whole-record

# an undo of an accept settled with --mine or --theirs
for how in --mine --theirs; do
    upfresh up
    utake "$UQ/u1"; uaccept
    sed 's/^line2$/line2 LOCAL/' "$store/wd/vendor/s1/SKILL.md" > "$T/x" && cat "$T/x" > "$store/wd/vendor/s1/SKILL.md"
    "$SUIT" commit wd -m local >/dev/null 2>&1
    settle_pin v2
    rm -rf "$UQ/u3"; skill "$UQ/u3" s1 'line2 THEIRS'
    tree "$store/wd" > "$T/u-pre"
    utake "$UQ/u3"
    "$SUIT" upstream up accept >/dev/null 2>&1
    check "accept$how-before-the-undo" 0 "" -- "$SUIT" upstream up accept $how vendor/s1/SKILL.md
    check "undo-after-accept$how" 0 "" -- "$SUIT" upstream up undo
    [ "$(tree "$store/wd")" = "$(cat "$T/u-pre")" ] && pass "undo-after-accept$how-restores-trunk-as-it-was" || bad "undo-after-accept$how-restores-trunk-as-it-was" "$(tree "$store/wd" | diff - "$T/u-pre")"
    recis up v1 "undo-after-accept$how-puts-the-record-back"
done

# -- accept again after an undo: the merge's base is the check-in the record names, not the common ancestor
# two accepts, the second undone, then accepted again: as after the second accept
upfresh up
utake "$UQ/u1"; uaccept; settle_pin v2
tree "$store/wd" > "$T/u-s1"
utake "$UQ/u2"; uaccept
tree "$store/wd" > "$T/u-s2"; rec2=$(cat "$store/wd/upstreams/up")
"$SUIT" upstream up undo >/dev/null 2>&1
check accept-again-after-undo 0 "" -- "$SUIT" upstream up accept
outhas accept-again-after-undo-merges "upstream up: merged, checked in"
[ "$(tree "$store/wd")" = "$(cat "$T/u-s2")" ] && pass accept-again-after-undo-gives-the-files-of-the-second-accept-byte-for-byte || bad accept-again-after-undo-gives-the-files-of-the-second-accept-byte-for-byte "$(tree "$store/wd" | diff - "$T/u-s2")"
[ "$(cat "$store/wd/upstreams/up")" = "$rec2" ] && pass accept-again-after-undo-records-the-second-tip || bad accept-again-after-undo-records-the-second-tip "$(cat "$store/wd/upstreams/up")"
check upstreams-after-accept-again 0 "" -- "$SUIT" upstreams
outis accept-again-after-undo-is-current 'up: current (taken v2, config v2)'
[ ! -e "$T/home/attention" ] && pass accept-again-after-undo-clears-the-item || bad accept-again-after-undo-clears-the-item "$(upatt)"
if have_fossil; then
    [ "$(fossil sql -R "$T/home/wardrobes/wd.fossil" "SELECT count(*) FROM plink WHERE cid=(SELECT objid FROM event WHERE type='ci' ORDER BY mtime DESC LIMIT 1)")" = 2 ] && pass accept-again-has-the-tip-as-merge-parent || bad accept-again-has-the-tip-as-merge-parent
fi
check undo-the-accept-made-again 0 "" -- "$SUIT" upstream up undo
[ "$(tree "$store/wd")" = "$(cat "$T/u-s1")" ] && pass undo-the-accept-made-again-restores-the-first-accept || bad undo-the-accept-made-again-restores-the-first-accept "$(tree "$store/wd" | diff - "$T/u-s1")"
# one accept, undone (the record is gone), then accepted again: as after the first accept
upfresh up
utake "$UQ/u1"; uaccept
tree "$store/wd" > "$T/u-a1"; rec1=$(cat "$store/wd/upstreams/up")
"$SUIT" upstream up undo >/dev/null 2>&1
[ ! -e "$store/wd/upstreams/up" ] && pass the-undo-of-the-only-accept-removes-the-record || bad the-undo-of-the-only-accept-removes-the-record
check accept-again-after-undoing-the-only-accept 0 "" -- "$SUIT" upstream up accept
[ "$(tree "$store/wd")" = "$(cat "$T/u-a1")" ] && [ "$(cat "$store/wd/upstreams/up")" = "$rec1" ] && pass accept-again-gives-the-files-of-the-only-accept || bad accept-again-gives-the-files-of-the-only-accept "$(tree "$store/wd" | diff - "$T/u-a1")"
# a newer take after an undo brings all of its changes over the first accept's
# files, not only those since the undone take; edits of yours to other lines stay
skill "$UQ/u4" s1 'line2 V3'; printf 'two\nthree\n' > "$UQ/u4/s2.txt"; printf 'gone\n' > "$UQ/u4/g.txt"; printf 'same\n' > "$UQ/u4/m.sh"
printf '#!/bin/sh\necho 1\n' > "$UQ/u4/x.sh"; chmod +x "$UQ/u4/x.sh"; printf 'four\n' > "$UQ/u4/s4.txt"
upfresh up
utake "$UQ/u1"; uaccept
sed 's/^line5$/line5 LOCAL/' "$store/wd/vendor/s1/SKILL.md" > "$T/x" && cat "$T/x" > "$store/wd/vendor/s1/SKILL.md"
printf 'other\n' > "$store/wd/own.txt"
"$SUIT" commit wd -m local >/dev/null 2>&1
settle_pin v2; utake "$UQ/u2"; uaccept
"$SUIT" upstream up undo >/dev/null 2>&1
settle_pin v3
check take-after-undo-of-a-file-the-undo-brought-back 0 "" -- "$SUIT" upstream up take "$UQ/u4"
check diff-of-a-newer-take-after-undo 0 "" -- "$SUIT" upstream up diff
outis diff-of-a-newer-take-lists-every-change-since-the-first-accept 'change vendor/s1/SKILL.md
change vendor/s2.txt
add vendor/s4.txt'
check accept-a-newer-take-after-undo 0 "" -- "$SUIT" upstream up accept
[ "$(cat "$store/wd/vendor/s1/SKILL.md")" = "$(printf -- '---\nname: s1\nline1\nline2 V3\nline3\nline4\nline5 LOCAL')" ] && pass a-newer-take-after-undo-merges-into-the-first-accepts-file || bad a-newer-take-after-undo-merges-into-the-first-accepts-file "$(cat "$store/wd/vendor/s1/SKILL.md")"
for f in s2.txt g.txt m.sh x.sh s4.txt; do cmp -s "$UQ/u4/$f" "$store/wd/vendor/$f" || break; done
[ "$f" = s4.txt ] && cmp -s "$UQ/u4/s4.txt" "$store/wd/vendor/s4.txt" && [ ! -e "$store/wd/vendor/s3.txt" ] && [ -x "$store/wd/vendor/x.sh" ] && [ ! -x "$store/wd/vendor/m.sh" ] && pass a-newer-take-after-undo-brings-all-its-files || bad a-newer-take-after-undo-brings-all-its-files "$f"
[ "$(cat "$store/wd/own.txt")" = other ] && pass a-newer-take-after-undo-keeps-your-other-files || bad a-newer-take-after-undo-keeps-your-other-files
recis up v3 a-newer-take-after-undo-is-recorded
check upstreams-after-a-newer-take-after-undo 0 "" -- "$SUIT" upstreams
outis a-newer-take-after-undo-is-current 'up: current (taken v3, config v3)'

# -- after --mine or --theirs, the next take is merged against the settled take:
# a change to other lines merges, and only a new change to the settled lines conflicts
printf -- '---\nname: s1\nline1\nline2 THEIRS\nline3\nline4 NEXT\nline5\n' > "$T/u5.md"
printf -- '---\nname: s1\nline1\nline2 AGAIN\nline3\nline4 NEXT\nline5\n' > "$T/u6.md"
rm -rf "$UQ/u3" "$UQ/u5" "$UQ/u6"; skill "$UQ/u3" s1 'line2 THEIRS'
mkdir -p "$UQ/u5/s1" "$UQ/u6/s1"; cp "$T/u5.md" "$UQ/u5/s1/SKILL.md"; cp "$T/u6.md" "$UQ/u6/s1/SKILL.md"
for how in --mine --theirs; do
    upfresh up
    utake "$UQ/u1"; uaccept
    sed 's/^line2$/line2 LOCAL/' "$store/wd/vendor/s1/SKILL.md" > "$T/x" && cat "$T/x" > "$store/wd/vendor/s1/SKILL.md"
    "$SUIT" commit wd -m local >/dev/null 2>&1
    settle_pin v2; utake "$UQ/u3"
    "$SUIT" upstream up accept $how vendor/s1/SKILL.md >/dev/null 2>&1
    settle_pin v3; utake "$UQ/u5"
    check "a-take-after-accept$how-merges-cleanly" 0 "" -- "$SUIT" upstream up accept
    if [ "$how" = --mine ]; then want=$(sed 's/^line2 THEIRS$/line2 LOCAL/' "$T/u5.md"); else want=$(cat "$T/u5.md"); fi
    [ "$(cat "$store/wd/vendor/s1/SKILL.md")" = "$want" ] && pass "a-take-after-accept$how-keeps-the-settled-lines" || bad "a-take-after-accept$how-keeps-the-settled-lines" "$(cat "$store/wd/vendor/s1/SKILL.md")"
    recis up v3 "a-take-after-accept$how-is-recorded"
    settle_pin v4; utake "$UQ/u6"
    tree "$store/wd" > "$T/u-b"
    if [ "$how" = --mine ]; then
        check "a-new-change-to-the-lines-settled$how-conflicts" 13 "" -- "$SUIT" upstream up accept
        outis "that-conflict$how-names-the-file" 'conflict vendor/s1/SKILL.md'
        [ "$(tree "$store/wd")" = "$(cat "$T/u-b")" ] && pass "that-conflict$how-changes-nothing" || bad "that-conflict$how-changes-nothing"
    else
        check "a-new-change-to-the-lines-settled$how-merges" 0 "" -- "$SUIT" upstream up accept
        cmp -s "$T/u6.md" "$store/wd/vendor/s1/SKILL.md" && pass "that-merge$how-takes-the-new-lines" || bad "that-merge$how-takes-the-new-lines" "$(cat "$store/wd/vendor/s1/SKILL.md")"
    fi
done

# the preconditions, each with its own message and no change
upfresh up
check undo-before-a-take 0 "" -- "$SUIT" upstream up undo
outis undo-before-a-take-has-nothing-to-undo 'upstream up: nothing to undo'
utake "$UQ/u1"
tree "$store/wd" > "$T/u-b"; rbefore=$(rsum)
check undo-before-an-accept 0 "" -- "$SUIT" upstream up undo
outis undo-before-an-accept-has-nothing-to-undo 'upstream up: nothing to undo'
[ "$(tree "$store/wd")" = "$(cat "$T/u-b")" ] && [ "$(rsum)" = "$rbefore" ] && [ "$(upatt)" = 'upstream up: update waiting for review' ] && pass nothing-to-undo-changes-nothing || bad nothing-to-undo-changes-nothing
uaccept
printf 'dirty\n' >> "$store/wd/run.sh"
tree "$store/wd" > "$T/u-b"; rbefore=$(rsum)
check undo-with-local-changes 12 "local changes: run suit commit or wait for suit tend" -- "$SUIT" upstream up undo
[ "$(tree "$store/wd")" = "$(cat "$T/u-b")" ] && [ "$(rsum)" = "$rbefore" ] && pass undo-with-local-changes-changes-nothing || bad undo-with-local-changes-changes-nothing
"$SUIT" commit wd -m local >/dev/null 2>&1
check undo-unknown-upstream 2 "no upstream nope in the config" -- "$SUIT" upstream nope undo
printf 'x\n' > "$T/home/wd.journal"
check undo-with-an-unfinished-update 15 "has an unfinished update" -- "$SUIT" upstream up undo
rm "$T/home/wd.journal"
rm -rf "$T/ahead"; mkdir -p "$T/ahead/wardrobes"
cp "$T/home/wardrobes/wd.fossil" "$T/ahead/wardrobes/wd.fossil"
SUIT_HOME="$T/ahead" "$SUIT" store open wd >/dev/null 2>&1
printf 'ahead\n' > "$T/ahead/store/wd/ahead.txt"
SUIT_HOME="$T/ahead" "$SUIT" commit wd -m ahead >/dev/null 2>&1
cp "$T/ahead/wardrobes/wd.fossil" "$T/home/wardrobes/wd.fossil"
tree "$store/wd" > "$T/u-b"
check undo-behind-trunk 1 "the working copy of wd is not at trunk's tip; run suit store update wd first" -- "$SUIT" upstream up undo
[ "$(tree "$store/wd")" = "$(cat "$T/u-b")" ] && pass undo-behind-trunk-changes-nothing || bad undo-behind-trunk-changes-nothing
"$SUIT" store update wd >/dev/null 2>&1
check undo-after-update 0 "" -- "$SUIT" upstream up undo
outhas undo-after-update-undoes-the-accept "upstream up: undone, checked in"
# a file the undo would bring back, where an untracked file of the user's already is
upfresh up
utake "$UQ/u1"; uaccept; settle_pin v2; utake "$UQ/u2"; uaccept
printf 'mine\n' > "$store/wd/vendor/g.txt"
tree "$store/wd" > "$T/u-b"
check undo-over-an-untracked-file 13 "1 files conflict" -- "$SUIT" upstream up undo
outis undo-over-an-untracked-file-names-it 'conflict vendor/g.txt'
[ "$(tree "$store/wd")" = "$(cat "$T/u-b")" ] && pass undo-keeps-the-untracked-file || bad undo-keeps-the-untracked-file
usnap() { rm -rf "$T/undo.snap"; cp -R "$T/home" "$T/undo.snap"; }
urest() { rm -rf "$T/home"; cp -R "$T/undo.snap" "$T/home"; }
rm "$store/wd/vendor/g.txt"; usnap
hunt undo-lstat-fails 1 "cannot read $store/wd/vendor/g.txt: $EIO" lstat urest "$SUIT" upstream up undo
hunt undo-unlink-fails 1 "cannot remove $store/wd/vendor/s3.txt: $EIO" unlink urest "$SUIT" upstream up undo
hunt undo-write-fails 1 "cannot write $store/wd/vendor/g.txt: $EIO" rename urest "$SUIT" upstream up undo
hunt undo-record-unreadable 1 "cannot read $store/wd/upstreams/up: $EIO" read urest "$SUIT" upstream up undo
# a whole record with no accept behind it means nothing to undo
upfresh up
printf '%s v1\n' "$(printf 'f%.0s' $(seq 1 40))" > "$store/wd/upstreams.new"; mkdir -p "$store/wd/upstreams"; mv "$store/wd/upstreams.new" "$store/wd/upstreams/up"
"$SUIT" commit wd -m "a record by hand" >/dev/null 2>&1
check undo-with-a-whole-record-and-no-accept 0 "" -- "$SUIT" upstream up undo
outis a-whole-record-with-no-accept-has-nothing-to-undo 'upstream up: nothing to undo'
# a record that is not whole means nothing to undo
upfresh up
utake "$UQ/u1"; uaccept
hash=$(cut -d' ' -f1 "$store/wd/upstreams/up")
tree "$store/wd" > "$T/u-b"
for variant in garbage nospace emptypin nonewline trailing short long; do
    case $variant in
    garbage) printf 'garbage' ;;
    nospace) printf '%sX\n' "$hash" ;;
    emptypin) printf '%s \n' "$hash" ;;
    nonewline) printf '%s v1' "$hash" ;;
    trailing) printf '%s v1\nmore\n' "$hash" ;;
    short) printf '%s v1\n' "$(printf '%.39s' "$hash")" ;;
    long) printf '%sa v1\n' "$hash" ;;
    esac > "$store/wd/upstreams/up"
    "$SUIT" commit wd -m "record $variant" >/dev/null 2>&1
    check "undo-with-a-$variant-record" 0 "" -- "$SUIT" upstream up undo
    outis "a-$variant-record-has-nothing-to-undo" 'upstream up: nothing to undo'
done
[ -e "$store/wd/vendor/s1/SKILL.md" ] && pass a-record-that-is-not-whole-undoes-nothing || bad a-record-that-is-not-whole-undoes-nothing

# two wardrobes
upfresh up
mkdir -p "$T/home/wardrobes"; cp "$FIXTURE" "$T/home/wardrobes/other.fossil"
"$SUIT" store open other >/dev/null 2>&1
printf '[upstream op]\npin = o1\ninto = vendor2\n' > "$store/other/suit.conf"; "$SUIT" commit other -m conf >/dev/null 2>&1
mkdir -p "$UQ/o1" "$UQ/o2"; printf 'o\n' > "$UQ/o1/o.txt"; printf 'o2\n' > "$UQ/o2/o.txt"; printf 'p\n' > "$UQ/o2/p.txt"
"$SUIT" upstream op take "$UQ/o1" >/dev/null 2>&1; "$SUIT" upstream op accept >/dev/null 2>&1
printf '[upstream op]\npin = o2\ninto = vendor2\n' > "$store/other/suit.conf"; "$SUIT" commit other -m conf >/dev/null 2>&1
"$SUIT" upstream op take "$UQ/o2" >/dev/null 2>&1; "$SUIT" upstream op accept >/dev/null 2>&1
utake "$UQ/u1"
check undo-in-the-other-wardrobe 0 "" -- "$SUIT" upstream op undo
[ "$(cat "$store/other/vendor2/o.txt")" = o ] && [ ! -e "$store/other/vendor2/p.txt" ] && [ ! -e "$store/wd/vendor2" ] && pass the-undo-lands-in-the-defining-wardrobe || bad the-undo-lands-in-the-defining-wardrobe
check upstreams-after-an-undo-in-the-other-wardrobe 0 "" -- "$SUIT" upstreams
outis only-the-undone-upstream-waits 'op: waiting for review (taken o2, config o2)
up: waiting for review (taken v1, config v1)'
check undo-in-the-wardrobe-that-has-no-accept 0 "" -- "$SUIT" upstream up undo
outis the-other-upstream-has-nothing-to-undo 'upstream up: nothing to undo'

# trust = auto: an undo is never followed by an automatic accept
upfresh up "trust = auto"
utake "$UQ/u1"; settle_pin v2; utake "$UQ/u2"
[ -f "$store/wd/vendor/s3.txt" ] && [ ! -e "$T/home/attention" ] && pass auto-accepted-both-takes || bad auto-accepted-both-takes
check undo-with-trust-auto 0 "" -- "$SUIT" upstream up undo
check upstreams-after-an-undo-with-trust-auto 0 "" -- "$SUIT" upstreams
outis trust-auto-stays-waiting-after-an-undo 'up: waiting for review (taken v2, config v2)'
[ "$(upatt)" = 'upstream up: update waiting for review' ] && [ ! -e "$store/wd/vendor/s3.txt" ] && pass trust-auto-leaves-the-item-and-the-files-undone || bad trust-auto-leaves-the-item-and-the-files-undone "$(upatt)"
tree "$store/wd" > "$T/u-b"
check take-again-after-an-undo-with-trust-auto 0 "" -- "$SUIT" upstream up take "$UQ/u2"
outis that-take-is-no-change 'upstream up: no change'
[ "$(tree "$store/wd")" = "$(cat "$T/u-b")" ] && pass no-automatic-accept-after-the-undo || bad no-automatic-accept-after-the-undo
check take-a-newer-update-with-trust-auto-after-an-undo 0 "" -- "$SUIT" upstream up take "$UQ/u9"
cmp -s "$UQ/u9/s1/SKILL.md" "$store/wd/vendor/s1/SKILL.md" && [ ! -e "$store/wd/vendor/s2.txt" ] && [ ! -e "$T/home/attention" ] && pass a-newer-take-with-trust-auto-is-accepted-after-an-undo || bad a-newer-take-with-trust-auto-is-accepted-after-an-undo "$(upatt)"
recis up v2 that-automatic-accept-is-recorded

# usage
check upstream-usage-undo-with-an-argument 2 "usage" -- "$SUIT" upstream up undo x
check upstream-usage-names-undo 2 "suit upstream NAME undo" -- "$SUIT" upstream up bogus

# two machines: undo on one, sync, and both agree
if have_fossil; then
unewremote; umach A; umach B
uon A
printf '[upstream up]\npin = v1\ninto = vendor\n' > "$S/suit.conf"
"$SUIT" tend wd >/dev/null 2>&1
uon B; "$SUIT" sync wd >/dev/null 2>&1
uon A; "$SUIT" upstream up take "$UQ/u1" >/dev/null 2>&1; "$SUIT" upstream up accept >/dev/null 2>&1; "$SUIT" sync wd >/dev/null 2>&1
uon B; "$SUIT" sync wd >/dev/null 2>&1
[ -f "$S/vendor/s1/SKILL.md" ] && pass the-accept-reached-the-second-machine || bad the-accept-reached-the-second-machine
check undo-on-the-second-machine 0 "" -- "$SUIT" upstream up undo
check sync-pushes-the-undo 0 "" -- "$SUIT" sync wd
uon A
check sync-brings-the-undo-back 0 "" -- "$SUIT" sync wd
[ "$(tree "$RT/A/store/wd")" = "$(tree "$RT/B/store/wd")" ] && [ ! -e "$S/vendor/s1/SKILL.md" ] && [ ! -e "$S/upstreams/up" ] && pass the-files-agree-after-the-undo || bad the-files-agree-after-the-undo
check upstreams-on-the-first-machine-after-the-undo 0 "" -- "$SUIT" upstreams
outis the-first-machine-sees-it-waiting 'up: waiting for review (taken v1, config v1)'
uon B
check upstreams-on-the-machine-that-undid 0 "" -- "$SUIT" upstreams
outis the-second-machine-sees-it-waiting 'up: waiting for review (taken v1, config v1)'
[ "$(cat "$RT/B/attention")" = 'upstream up: update waiting for review' ] && [ ! -e "$RT/A/attention" ] && pass the-item-stays-with-the-machine-that-undid || bad the-item-stays-with-the-machine-that-undid "$(cat "$RT/B/attention" 2>&1) / $(cat "$RT/A/attention" 2>&1)"
uon A
check undo-on-the-first-machine-has-nothing-to-undo 0 "" -- "$SUIT" upstream up undo
outis nothing-to-undo-after-the-sync 'upstream up: nothing to undo'
check accept-on-the-first-machine-after-the-undo 0 "" -- "$SUIT" upstream up accept
tree "$S" > "$T/u-ma"
uon B; "$SUIT" upstream up accept >/dev/null 2>&1
[ "$(tree "$S")" = "$(cat "$T/u-ma")" ] && [ -f "$S/vendor/s1/SKILL.md" ] && pass accepting-after-the-undo-gives-the-same-files-on-either-machine || bad accepting-after-the-undo-gives-the-same-files-on-either-machine "$(tree "$S" | diff - "$T/u-ma")"
fi

# -- every failed system call during take, accept, diff and upstreams leaves the
# repository, the working copy and the attention file as they were (or as the
# command would have left them), never half way
if have_fossil; then
usw_fresh() { # a home at $1 with the fixture as wd, its store open and the upstream up at pin v1 into vendor
    SUIT_HOME=$1; export SUIT_HOME; store=$SUIT_HOME/store
    rm -rf "$SUIT_HOME"; mkdir -p "$SUIT_HOME/wardrobes"
    cp "$FIXTURE" "$SUIT_HOME/wardrobes/wd.fossil"
    "$SUIT" store open wd >/dev/null 2>&1
    printf '[outfit o]\n[upstream up]\npin = v1\ninto = vendor\n' > "$store/wd/suit.conf"
    "$SUIT" commit wd -m conf >/dev/null 2>&1
}
usw_state() { # the repository, the working copy and the journals of $SUIT_HOME, as text
    fossil sql -R "$SUIT_HOME/wardrobes/wd.fossil" "SELECT (SELECT count(*) FROM blob), (SELECT max(rid) FROM blob), (SELECT count(*) FROM event), (SELECT count(*) FROM tagxref)"
    tree "$SUIT_HOME/store/wd"
    ls "$SUIT_HOME"/*.journal 2>/dev/null
}
usw_att() { cat "$SUIT_HOME/attention" 2>/dev/null; echo end; }
usw_setup() { # usw_setup SCEN DIR: the scenario's home at DIR, and in uswcmd what to run
    usw_fresh "$2"
    case $1 in
    take1) uswcmd="upstream up take $UP/v1" ;;
    take2)
        "$SUIT" upstream up take "$UP/v1" >/dev/null 2>&1; "$SUIT" upstream up accept >/dev/null 2>&1
        skill "$UD/v2sw" s1 'line2 NEW'; printf '#!/bin/sh\n' > "$UD/v2sw/x.sh"; chmod +x "$UD/v2sw/x.sh"
        uswcmd="upstream up take $UD/v2sw" ;;
    accept) "$SUIT" upstream up take "$UP/v1" >/dev/null 2>&1; uswcmd="upstream up accept" ;;
    settle|conflict|stale|diff)
        "$SUIT" upstream up take "$UP/v1" >/dev/null 2>&1; "$SUIT" upstream up accept >/dev/null 2>&1
        sed 's/^line2$/line2 LOCAL/' "$store/wd/vendor/s1/SKILL.md" > "$SUIT_HOME/x" && cat "$SUIT_HOME/x" > "$store/wd/vendor/s1/SKILL.md"; rm "$SUIT_HOME/x"
        "$SUIT" commit wd -m local >/dev/null 2>&1
        "$SUIT" upstream up take "$UP/v3" >/dev/null 2>&1
        case $1 in
        settle) uswcmd="upstream up accept --theirs vendor/s1/SKILL.md" ;;
        conflict) uswcmd="upstream up accept" ;;
        diff) uswcmd="upstream up diff" ;;
        stale) "$SUIT" upstream up accept --theirs vendor/s1/SKILL.md >/dev/null 2>&1
               printf 'upstream up: update waiting for review\n' > "$SUIT_HOME/attention"; uswcmd="upstream up accept" ;;
        esac ;;
    undo)
        "$SUIT" upstream up take "$UP/v1" >/dev/null 2>&1; "$SUIT" upstream up accept >/dev/null 2>&1
        skill "$UD/v2sw" s1 'line2 NEW'; printf '#!/bin/sh\n' > "$UD/v2sw/x.sh"; chmod +x "$UD/v2sw/x.sh"
        "$SUIT" upstream up take "$UD/v2sw" >/dev/null 2>&1; "$SUIT" upstream up accept >/dev/null 2>&1
        uswcmd="upstream up undo" ;;
    states) "$SUIT" upstream up take "$UP/v1" >/dev/null 2>&1; uswcmd="upstreams" ;;
    esac
}
usw_worker() { # usw_worker SCEN:FAULT: calls 1, 2, ... of FAULT fail in turn; prints "HITS BAD..."
    uws=${1%%:*}; uwf=${1#*:}; UD=$T/usw-$uws-$uwf; rm -rf "$UD"; mkdir -p "$UD"
    usw_setup "$uws" "$UD/h"
    cp -R "$UD/h" "$UD/snap"
    ubc=$(usw_state); uba=$(usw_att)
    # shellcheck disable=SC2086
    "$SUIT" $uswcmd >/dev/null 2>&1; uwant=$?; uac=$(usw_state); uaa=$(usw_att)
    ubad=""; uhits=0; un=1; uquiet=0
    while [ $un -le 400 ] && [ $uquiet -lt 3 ]; do
        rm -rf "$UD/h"; cp -R "$UD/snap" "$UD/h"
        # shellcheck disable=SC2086
        SUIT_FAULT=$uwf:$un "$SUIT" $uswcmd >/dev/null 2>&1; urc=$?
        if [ "$urc" != "$uwant" ]; then
            uquiet=0; uhits=$((uhits + 1))
            if [ -e "$UD/h/wd.journal" ]; then "$SUIT" store repair wd >/dev/null 2>&1 || ubad="$ubad repair-$uwf-$un"; fi
            unc=$(usw_state); una=$(usw_att)
            # whole before, whole after, or whole after with the item as it was (the item is removed last)
            { { [ "$unc" = "$ubc" ] && [ "$una" = "$uba" ]; } || { [ "$unc" = "$uac" ] && { [ "$una" = "$uba" ] || [ "$una" = "$uaa" ]; }; }; } || ubad="$ubad mixed-$uwf-$un"
            [ -z "$("$SUIT" store status wd 2>&1)" ] || ubad="$ubad dirty-$uwf-$un"
        else uquiet=$((uquiet + 1)); fi
        un=$((un + 1))
    done
    rm -rf "$UD"
    echo "$uhits $ubad"
}
usw_kinds() { case $1 in states) echo open read ;; *) echo open read write rename unlink mkdir fsync stat lstat listdir fchmod ;; esac; }
usw_sweep() { # usw_sweep SCEN...: each scenario against every kind of failing call, one worker for each
    uw_list=""
    for uw_s in "$@"; do
        for uw_f in $(usw_kinds "$uw_s"); do uw_list="$uw_list $uw_s:$uw_f"; done
    done
    # shellcheck disable=SC2086
    fan usw_worker $uw_list
    for uw_s in "$@"; do
        ubad=""; uhits=0
        for uw_f in $(usw_kinds "$uw_s"); do
            if read -r uh ub <"$T/fan/usw_worker.$uw_s:$uw_f" && [ -n "$uh" ]; then uhits=$((uhits + uh)); ubad="$ubad${ub:+ $ub}"
            else ubad="$ubad worker-$uw_f-gave-no-result"; fi
        done
        [ -z "$ubad" ] && [ "$uhits" -gt 0 ] && pass "sweep-upstream-$uw_s-leaves-things-whole ($uhits failures)" || bad "sweep-upstream-$uw_s" "hits $uhits:$ubad"
    done
}
skill "$UP/v1" s1; printf 'two\n' > "$UP/v1/s2.txt"
rm -rf "$UP/v3"; skill "$UP/v3" s1 'line2 THEIRS'; printf 'new\n' > "$UP/v3/s3.txt"; printf 'two\n' > "$UP/v3/s2.txt"
usw_sweep take1 take2 accept settle conflict stale states undo
fi

echo "store.sh: $total cases, $failed failed"
[ "$failed" -eq 0 ]