#!/bin/sh
# Tool contracts: each case runs one scripted tool call and compares the
# journaled result exactly (Pi's messages, limits and notices). --no-faults
# skips the crash cases (the release build has no crash hooks).
set -eu
PIC=${PIC:?set PIC to the pic binary}
FAULTS=yes
[ "${1:-}" = --no-faults ] && FAULTS=no
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-tools.XXXXXX")
# pic keeps user state under HOME: never the real one.
export HOME="$T/home"
mkdir -p "$HOME"
trap 'rm -rf -- "$T"' EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
n=0

# call NAME JSON: a fresh journal and workspace (WS), one call to tool NAME
# with input JSON, then an answer. The result lands in $T/result.
setup() { n=$((n + 1)); DB="$T/$n.sqlite"; WS="$T/ws$n"; mkdir "$WS"; }
k=0
call() {
    k=$((k + 1)); DB="$T/$n.$k.sqlite" # a journal per call; several calls may share one workspace
    printf 'tool raw %s %s\ntext done\n' "$1" "$2" > "$T/script"
    "$PIC" --db "$DB" --workspace "$WS" submit job 'go' > /dev/null
    # shellcheck disable=SC2086
    "$PIC" ${TOOLFLAGS:-} --db "$DB" --workspace "$WS" run --script "$T/script" 2> "$T/stderr" || fail "run: $(cat "$T/stderr")"
    "$PIC" --db "$DB" result 1 > "$T/result"
}
expect() { # expect LABEL ERROR_FLAG: the result must equal stdin exactly
    { printf 'error=%s\n' "$2"; cat; } > "$T/want"
    cmp -s "$T/want" "$T/result" || { diff "$T/want" "$T/result" >&2 || true; fail "$1"; }
    printf 'PASS: %s\n' "$1"
}
contains() { # contains LABEL TEXT
    grep -qF -- "$2" "$T/result" || { cat "$T/result" >&2; fail "$1"; }
    printf 'PASS: %s\n' "$1"
}

# ---- read
setup; printf 'a\nb\nc\n' > "$WS/f.txt"
call read '{"path":"f.txt"}'
printf 'a\nb\nc\n\n' | expect 'read: whole small file' 0
setup; printf 'a\nb\nc\n' > "$WS/f.txt"
call read '{"path":"f.txt","offset":2,"limit":1}'
printf 'b\n\n[2 more lines in file. Use offset=3 to continue.]\n' | expect 'read: offset and limit' 0
setup; printf 'a\nb\nc\n' > "$WS/f.txt"
call read '{"path":"f.txt","offset":10}'
printf 'Offset 10 is beyond end of file (4 lines total)\n' | expect 'read: offset past the end' 1
setup; seq 1 2500 > "$WS/f.txt"
call read '{"path":"f.txt"}'
contains 'read: 2000-line limit' '[Showing lines 1-2000 of 2501. Use offset=2001 to continue.]'
setup; awk 'BEGIN { for (i = 0; i < 100; i++) { s = ""; for (j = 0; j < 1000; j++) s = s "x"; print s } }' > "$WS/f.txt"
call read '{"path":"f.txt"}'
contains 'read: 50KB limit' '[Showing lines 1-51 of 101 (50KB limit). Use offset=52 to continue.]'
setup; awk 'BEGIN { s = ""; for (j = 0; j < 60000; j++) s = s "y"; print s }' > "$WS/f.txt"
call read '{"path":"f.txt"}'
printf "[Line 1 is 58.6KB, exceeds 50KB limit. Use bash: sed -n '1p' f.txt | head -c 51200]\n" | expect 'read: first line over the limit' 0
setup
call read '{"path":"missing.txt"}'
contains 'read: missing file' 'ENOENT'

# ---- write
setup
call write '{"path":"a/b/c.txt","content":"x\ny"}'
printf 'Successfully wrote to a/b/c.txt\n' | expect 'write: creates parent directories' 0
[ "$(cat "$WS/a/b/c.txt")" = "$(printf 'x\ny')" ] || fail 'write: content'
# The flush that makes a write durable: F_FULLFSYNC on macOS (plain fsync there leaves it in the
# drive's cache), fsync on Linux, where fsync does flush the cache. strace shows it on Linux; macOS
# has no unprivileged tracer (dtruss needs root), so there the call is only built.
if [ "$(uname -s)" = Linux ] && command -v strace > /dev/null 2>&1 && strace -o /dev/null true 2> /dev/null; then
    setup
    call write '{"path":"a/d.txt","content":"z"}' # the journal and files exist, so only this run is traced
    printf 'tool raw write {"path":"a/d.txt","content":"zz"}\ntext done\n' > "$T/script"
    "$PIC" --db "$DB" --workspace "$WS" submit job2 'again' > /dev/null
    strace -f -y -o "$T/strace" -e trace=fsync,fdatasync "$PIC" --db "$DB" --workspace "$WS" run --script "$T/script" 2> "$T/stderr" ||
        fail "write: traced run: $(cat "$T/stderr")"
    R=$(cd "$WS" && pwd -P) J=$(cd "$(dirname "$DB")" && pwd -P)/$(basename "$DB") # strace names real paths
    grep -q "fsync([0-9]*<$R/a/d.txt.pic-tmp>)" "$T/strace" || fail "write: the new file was not fsynced: $(cat "$T/strace")"
    grep -q "fsync([0-9]*<$R/a>)" "$T/strace" || fail "write: its directory was not fsynced: $(cat "$T/strace")"
    grep -qE "f(data)?sync\([0-9]*<$J(-wal|-journal)?>\)" "$T/strace" || fail "write: the journal was not synced: $(cat "$T/strace")"
    printf 'PASS: write: on Linux the file, its directory and the journal reach fsync\n'
else
    printf 'SKIP: write: the fsync check needs Linux and a working strace (this is %s)\n' "$(uname -s)"
fi
setup
call write '{"path":"f.txt"}'
printf 'write needs string inputs path and content\n' | expect 'write: missing content' 1

# ---- edit
setup; printf 'alpha\nbeta\ngamma\n' > "$WS/f.txt"
call edit '{"path":"f.txt","edits":[{"oldText":"beta","newText":"BETA"},{"oldText":"gamma","newText":"GAMMA"}]}'
printf 'Successfully replaced 2 block(s) in f.txt.\n' | expect 'edit: two disjoint edits' 0
[ "$(cat "$WS/f.txt")" = "$(printf 'alpha\nBETA\nGAMMA')" ] || fail 'edit: content'
setup; printf 'alpha\n' > "$WS/f.txt"
call edit '{"path":"f.txt","edits":[{"oldText":"zeta","newText":"x"}]}'
printf 'Could not find the exact text in f.txt. The old text must match exactly including all whitespace and newlines.\n' |
    expect 'edit: not found' 1
setup; printf 'x x\n' > "$WS/f.txt"
call edit '{"path":"f.txt","edits":[{"oldText":"x","newText":"y"}]}'
printf 'Found 2 occurrences of the text in f.txt. The text must be unique. Please provide more context to make it unique.\n' |
    expect 'edit: not unique' 1
setup; printf 'abcdef\n' > "$WS/f.txt"
call edit '{"path":"f.txt","edits":[{"oldText":"abcd","newText":"1"},{"oldText":"cdef","newText":"2"}]}'
printf 'edits[0] and edits[1] overlap in f.txt. Merge them into one edit or target disjoint regions.\n' |
    expect 'edit: overlapping edits' 1
setup; printf 'one\r\ntwo\r\n' > "$WS/f.txt"
call edit '{"path":"f.txt","edits":[{"oldText":"one\ntwo","newText":"uno\ndos"}]}'
[ "$(od -An -c "$WS/f.txt" | tr -s ' ')" = "$(printf 'uno\r\ndos\r\n' | od -An -c | tr -s ' ')" ] ||
    fail 'edit: CRLF line endings not kept'
printf 'PASS: edit: CRLF matched as LF and kept\n'
setup; printf '\357\273\277hello\n' > "$WS/f.txt"
call edit '{"path":"f.txt","edits":[{"oldText":"hello","newText":"bye"}]}'
[ "$(od -An -tx1 "$WS/f.txt" | tr -d ' \n')" = efbbbf6279650a ] || fail 'edit: BOM not kept'
printf 'PASS: edit: byte-order mark kept\n'
setup; printf 'same\n' > "$WS/f.txt"
call edit '{"path":"f.txt","edits":[{"oldText":"same","newText":"same"}]}'
printf 'No changes made to f.txt. The replacement produced identical content.\n' | expect 'edit: no change' 1
setup
call edit '{"path":"nope.txt","edits":[{"oldText":"a","newText":"b"}]}'
printf 'Could not edit file: nope.txt. Error code: ENOENT.\n' | expect 'edit: missing file' 1
setup; printf 'old\n' > "$WS/f.txt"
call edit '{"path":"f.txt","oldText":"old","newText":"new"}'
[ "$(cat "$WS/f.txt")" = new ] || fail 'edit: legacy top-level oldText/newText'
setup; printf 'old\n' > "$WS/f.txt"
call edit '{"path":"f.txt","edits":"[{\"oldText\":\"old\",\"newText\":\"new\"}]"}'
[ "$(cat "$WS/f.txt")" = new ] || fail 'edit: edits given as a JSON string'
printf 'PASS: edit: accepts the input forms Pi accepts\n'
setup; printf 'a\n' > "$WS/f.txt"
call edit '{"path":"f.txt","edits":[]}'
printf 'Edit tool input is invalid. edits must contain at least one replacement.\n' | expect 'edit: no edits' 1

# ---- bash
setup
call bash '{"command":"echo hi; exit 3"}'
printf 'hi\n\nCommand exited with code 3\n' | expect 'bash: exit status' 1
setup
call bash '{"command":"true"}'
printf '(no output)\n' | expect 'bash: no output' 0
# A cut result keeps the full output in the journal, named pic:output/N; no
# temp file is made, and read opens the name like a file.
setup
mkdir "$T/tmp$n"
TMPDIR="$T/tmp$n" call bash '{"command":"seq 1 3000"}'
contains 'bash: keeps the last 2000 lines' '[Showing lines 1001-3000 of 3000. Full output: pic:output/1 (read it with the read tool'
[ -z "$(ls -A "$T/tmp$n")" ] || fail "bash: temp files made: $(ls "$T/tmp$n")"
printf 'tool raw read {"path":"pic:output/1","offset":2998,"limit":2}\ntool raw read {"path":"pic:output/9"}\ntext done\n' > "$T/script"
"$PIC" --db "$DB" --workspace "$WS" submit job2 'go' > /dev/null
"$PIC" --db "$DB" --workspace "$WS" run --script "$T/script" 2> "$T/stderr" || fail "run: $(cat "$T/stderr")"
"$PIC" --db "$DB" result 2 > "$T/result"
printf 'error=0\n2998\n2999\n\n[2 more lines in file. Use offset=3000 to continue.]\n' | cmp -s - "$T/result" || { cat "$T/result" >&2; fail 'bash: read of the output slice'; }
"$PIC" --db "$DB" result 3 > "$T/result"
contains 'bash: missing output id' 'ENOENT: No such file or directory, read '"'"'pic:output/9'"'"
printf 'PASS: bash: full output journaled when cut\n'
row=$(sqlite3 "$DB" 'SELECT sz, length(data) FROM pic_output')
sz=${row%%|*}; stored=${row##*|}
[ "$sz" = 13893 ] && [ "$stored" -lt "$sz" ] || fail "bash: output not stored compressed ($row)"
printf 'PASS: bash: output stored compressed\n'
setup
start=$(date +%s)
call bash '{"command":"sleep 30","timeout":1}'
[ $(( $(date +%s) - start )) -lt 10 ] || fail 'bash: timeout not applied'
printf '(no output)\n\nCommand timed out after 1 seconds\n' | expect 'bash: timeout input' 1
setup
call bash '{"command":"true","timeout":-1}'
printf 'Invalid timeout: must be a finite number of seconds\n' | expect 'bash: invalid timeout' 1

# ---- grep, find, ls (opt-in: Pi's --tools names them)
TOOLFLAGS='--tools read,bash,edit,write,grep,find,ls'
setup; printf 'one\ntwo\n' > "$WS/f.txt"
TOOLFLAGS=
call grep '{"pattern":"one"}'
printf 'Tool grep not found\n' | expect 'grep: not in play by default' 1
setup
call find '{"pattern":"*"}'
printf 'Tool find not found\n' | expect 'find: not in play by default' 1
setup
call ls '{}'
printf 'Tool ls not found\n' | expect 'ls: not in play by default' 1
TOOLFLAGS='--tools read,bash,edit,write,grep,find,ls'

setup; mkdir "$WS/sub" "$WS/skip" "$WS/.git"
printf 'hello World\nfoo\nhello again\nbar\n' > "$WS/a.txt"
printf 'x hello\n' > "$WS/sub/b.ts"
printf 'hello\n' > "$WS/sub/c.md"
printf 'hello\n' > "$WS/skip/d.txt"
printf 'hello\n' > "$WS/.git/e"
printf 'hello\n' > "$WS/.hidden"
printf 'a\0b hello\n' > "$WS/bin.dat"
printf 'skip/\n' > "$WS/.gitignore"
call grep '{"pattern":"hello"}'
printf '.hidden:1: hello\na.txt:1: hello World\na.txt:3: hello again\nskip/d.txt:1: hello\nsub/b.ts:1: x hello\nsub/c.md:1: hello\n' |
    expect 'grep: sorted, relative, dotfiles and ignored files in, .git and binary files out' 0
call grep '{"pattern":"nomatch"}'
printf 'No matches found\n' | expect 'grep: no match' 0
call grep '{"pattern":"hello","path":"a.txt"}'
printf 'a.txt:1: hello World\na.txt:3: hello again\n' | expect 'grep: one file shows its base name' 0
call grep '{"pattern":"hello","path":"sub","glob":"*.ts"}'
printf 'b.ts:1: x hello\n' | expect 'grep: glob without a slash matches names at any depth' 0
call grep '{"pattern":"hello","glob":"sub/*.md"}'
printf 'sub/c.md:1: hello\n' | expect 'grep: glob with a slash is relative to the path' 0
call grep '{"pattern":"hello","glob":"**/*.{ts,md}"}'
printf 'sub/b.ts:1: x hello\nsub/c.md:1: hello\n' | expect 'grep: ** and braces in a glob' 0
call grep '{"pattern":"hello","glob":"!*.txt"}'
printf '.hidden:1: hello\nsub/b.ts:1: x hello\nsub/c.md:1: hello\n' | expect 'grep: a negated glob' 0
call grep '{"pattern":"HELLO","ignoreCase":true,"path":"a.txt"}'
printf 'a.txt:1: hello World\na.txt:3: hello again\n' | expect 'grep: ignoreCase' 0
call grep '{"pattern":"HELLO","path":"a.txt"}'
printf 'No matches found\n' | expect 'grep: case sensitive by default' 0
call grep '{"pattern":"hello","path":"nope"}'
contains 'grep: missing path' "Path not found: $(printf '%s' "$WS/nope" | tr -s /)"
call grep '{"pattern":"(","path":"a.txt"}'
contains 'grep: invalid regex' 'regex parse error:'
call grep '{}'
printf 'grep needs a string input pattern\n' | expect 'grep: missing pattern' 1

setup; printf 'a.c\nabc\nA.C\nx9y\nfoo  bar\n' > "$WS/r.txt"
call grep '{"pattern":"a.c","literal":true}'
printf 'r.txt:1: a.c\n' | expect 'grep: literal' 0
call grep '{"pattern":"a.c"}'
printf 'r.txt:1: a.c\nr.txt:2: abc\n' | expect 'grep: regex' 0
call grep '{"pattern":"a.c","literal":true,"ignoreCase":true}'
printf 'r.txt:1: a.c\nr.txt:3: A.C\n' | expect 'grep: literal with ignoreCase' 0
call grep '{"pattern":"x\\d+y"}'
printf 'r.txt:4: x9y\n' | expect 'grep: \d' 0
call grep '{"pattern":"foo\\s+bar"}'
printf 'r.txt:5: foo  bar\n' | expect 'grep: \s' 0
call grep '{"pattern":"(?i)A\\.C"}'
printf 'r.txt:1: a.c\nr.txt:3: A.C\n' | expect 'grep: leading (?i)' 0
call grep '{"pattern":"(?:a|x)\\w*?9"}'
printf 'r.txt:4: x9y\n' | expect 'grep: (?: and lazy quantifiers' 0

setup; printf 'm1\nl2\nl3\nl4\nm5\nl6\nl7\nl8\nl9\nm10\nl11\n' > "$WS/c.txt"
call grep '{"pattern":"^m","context":1}'
printf 'c.txt:1: m1\nc.txt-2- l2\nc.txt-4- l4\nc.txt:5: m5\nc.txt-6- l6\nc.txt-9- l9\nc.txt:10: m10\nc.txt-11- l11\n' |
    expect 'grep: context lines, "-" after the name, no group separators' 0
call grep '{"pattern":"^m","limit":2}'
printf 'c.txt:1: m1\nc.txt:5: m5\n\n[2 matches limit reached. Use limit=4 for more, or refine pattern]\n' |
    expect 'grep: match limit notice' 0
call grep '{"pattern":"^m","limit":3}'
printf 'c.txt:1: m1\nc.txt:5: m5\nc.txt:10: m10\n' | expect 'grep: exactly the limit is no notice' 0
call grep '{"pattern":"^m","limit":1,"context":1}'
printf 'c.txt:1: m1\nc.txt-2- l2\n\n[1 matches limit reached. Use limit=2 for more, or refine pattern]\n' |
    expect 'grep: the limit match keeps its trailing context' 0

setup; awk 'BEGIN { s = ""; for (j = 0; j < 600; j++) s = s "x"; print s }' > "$WS/long.txt"
call grep '{"pattern":"x"}'
{ printf 'long.txt:1: '; awk 'BEGIN { s = ""; for (j = 0; j < 500; j++) s = s "x"; printf "%s", s }'
  printf '... [truncated]\n\n[Some lines truncated to 500 chars. Use read tool to see full lines]\n'; } | expect 'grep: a long line is cut at 500 characters' 0
setup; awk 'BEGIN { s = ""; for (j = 0; j < 400; j++) s = s "y"; for (i = 0; i < 200; i++) print s }' > "$WS/big.txt"
call grep '{"pattern":"y","limit":1000}'
contains 'grep: 50KB cap' '[50.0KB limit reached]'
[ "$(wc -c < "$T/result")" -lt 52000 ] || fail 'grep: result over the cap'

# ---- find
setup; mkdir -p "$WS/src/deep" "$WS/node_modules/p" "$WS/.git"
: > "$WS/src/a.ts"; : > "$WS/src/deep/b.ts"; : > "$WS/top.ts"; : > "$WS/README.md"; : > "$WS/readme.txt"
: > "$WS/node_modules/p/i.ts"; : > "$WS/.git/h.ts"; : > "$WS/.dot.ts"
printf 'node_modules\n' > "$WS/.gitignore"
call find '{"pattern":"*.ts"}'
printf '.dot.ts\nnode_modules/p/i.ts\nsrc/a.ts\nsrc/deep/b.ts\ntop.ts\n' | expect 'find: a name pattern matches at any depth; ignored folders in, .git out' 0
call find '{"pattern":"src/**/*.ts"}'
printf 'src/a.ts\nsrc/deep/b.ts\n' | expect 'find: a path pattern is relative to the search folder' 0
call find '{"pattern":"*.ts","path":"src"}'
printf 'a.ts\ndeep/b.ts\n' | expect 'find: results are relative to path' 0
call find '{"pattern":"deep"}'
printf 'src/deep/\n' | expect 'find: folders carry a trailing slash' 0
call find '{"pattern":"readme*"}'
printf 'README.md\nreadme.txt\n' | expect 'find: an all-lowercase pattern ignores case' 0
call find '{"pattern":"README*"}'
printf 'README.md\n' | expect 'find: a pattern with a capital is case sensitive' 0
call find '{"pattern":"./*.txt"}'
printf 'readme.txt\n' | expect 'find: a leading ./ is dropped' 0
call find '{"pattern":"*.zzz"}'
printf 'No files found matching pattern\n' | expect 'find: no match' 0
call find '{"pattern":"*.ts","limit":2}'
printf '.dot.ts\nnode_modules/p/i.ts\n\n[2 results limit reached. Use limit=4 for more, or refine pattern]\n' | expect 'find: limit notice' 0
call find '{"pattern":"*.ts","path":"nope"}'
contains 'find: missing path' "Path not found: $(printf '%s' "$WS/nope" | tr -s /)"
call find '{}'
printf 'find needs a string input pattern\n' | expect 'find: missing pattern' 1
printf 'src/\n' > "$WS/.fdignore"
call find '{"pattern":"*.ts"}'
printf '.dot.ts\nnode_modules/p/i.ts\nsrc/a.ts\nsrc/deep/b.ts\ntop.ts\n' | expect 'find: .fdignore leaves nothing out' 0
setup; : > "$WS/keep.log"; : > "$WS/drop.log"; printf 'drop.log\n' > "$WS/.ignore"
call find '{"pattern":"*.log"}'
printf 'drop.log\nkeep.log\n' | expect 'find: .ignore leaves nothing out' 0
setup; : > "$WS/keep.log"; : > "$WS/drop.log"; printf 'keep.log\n' > "$WS/.fslignore"
call find '{"pattern":"*.log"}'
printf 'drop.log\nkeep.log\n' | expect 'find: .fslignore leaves nothing out' 0
# every kind of ignore file, and the settings lists, leave nothing out; version-control folders stay out
setup; mkdir -p "$WS/.git" "$WS/.zit" "$WS/.fossil-settings"
for f in a.log b.log c.log d.log; do printf 'needle\n' > "$WS/$f"; done
printf 'needle\n' > "$WS/.git/g.log"; printf 'needle\n' > "$WS/.zit/z.log"
printf 'a.log\n' > "$WS/.gitignore"; printf 'b.log\n' > "$WS/.zitignore"; printf 'c.log\n' > "$WS/.fslignore"
printf 'd.log\n' > "$WS/.fossil-settings/ignore-glob"
call find '{"pattern":"*.log"}'
printf 'a.log\nb.log\nc.log\nd.log\n' | expect 'find: .gitignore, .zitignore, .fslignore and ignore-glob leave nothing out; .git and .zit stay out' 0
call grep '{"pattern":"needle"}'
printf 'a.log:1: needle\nb.log:1: needle\nc.log:1: needle\nd.log:1: needle\n' | expect 'grep: every ignore file leaves nothing out; .git and .zit stay out' 0

# .picignore alone excludes: gitignore syntax, scoped to its folder; a .gitignore entry is found
setup; mkdir -p "$WS/sub/inner" "$WS/other"
for f in keep.txt agent.txt git.txt sub/agent.txt sub/keep.txt sub/inner/deep.txt sub/inner/keep.txt other/deep.txt; do printf 'needle\n' > "$WS/$f"; done
printf 'agent.txt\n' > "$WS/.picignore"; printf 'git.txt\n' > "$WS/.gitignore"; printf 'inner/\n' > "$WS/sub/.picignore"
call find '{"pattern":"*.txt"}'
printf 'git.txt\nkeep.txt\nother/deep.txt\nsub/keep.txt\n' | expect 'find: .picignore excludes (nested, scoped to its folder), .gitignore does not' 0
call grep '{"pattern":"needle"}'
printf 'git.txt:1: needle\nkeep.txt:1: needle\nother/deep.txt:1: needle\nsub/keep.txt:1: needle\n' | expect 'grep: .picignore excludes, .gitignore does not' 0

# ---- ls
setup; mkdir "$WS/Zdir" "$WS/adir"; : > "$WS/b.txt"; : > "$WS/.dot"; : > "$WS/A.txt"
call ls '{}'
printf '.dot\nA.txt\nadir/\nb.txt\nZdir/\n' | expect 'ls: case-insensitive order, "/" on folders, dotfiles in' 0
call ls '{"path":"adir"}'
printf '(empty directory)\n' | expect 'ls: empty folder' 0
call ls '{"limit":2}'
printf '.dot\nA.txt\n\n[2 entries limit reached. Use limit=4 for more]\n' | expect 'ls: limit notice' 0
call ls '{"path":"b.txt"}'
contains 'ls: not a folder' "Not a directory: $(printf '%s' "$WS/b.txt" | tr -s /)"
call ls '{"path":"nope"}'
contains 'ls: missing folder' "Path not found: $(printf '%s' "$WS/nope" | tr -s /)"
setup; i=0; while [ "$i" -lt 600 ]; do : > "$WS/f$(printf '%04d' "$i").txt"; i=$((i + 1)); done
call ls '{}'
contains 'ls: 500-entry default limit' '[500 entries limit reached. Use limit=1000 for more]'

# ---- other
setup
call nope '{}'
printf 'Tool nope not found\n' | expect 'unknown tool' 1

[ "$FAULTS" = yes ] || exit 0

# Cancelling a submission whose tool call never ran skips the call with a
# result saying so; the journal stays consistent and nothing runs later.
setup
printf 'tool bash touch ran\ntext done\n' > "$T/script"
"$PIC" --db "$DB" --workspace "$WS" submit job 'go' > /dev/null
if env PIC_CRASH_AT=after-assistant:1 "$PIC" --db "$DB" --workspace "$WS" run --script "$T/script" 2>/dev/null; then
    fail 'cancel: no crash'
fi
[ "$("$PIC" --db "$DB" --workspace "$WS" cancel job)" = cancelled ] || fail 'cancel: refused'
"$PIC" --db "$DB" --workspace "$WS" run --script "$T/script"
"$PIC" --db "$DB" check > /dev/null || fail 'cancel: integrity'
"$PIC" --db "$DB" dump | grep -q '^submission 1 job failed .* error=cancelled$' || fail 'cancel: status'
"$PIC" --db "$DB" dump | grep -q '^effect 1 2\.0 bash skipped' || fail 'cancel: call not skipped'
[ ! -e "$WS/ran" ] || fail 'cancel: the call ran'
if "$PIC" --db "$DB" --workspace "$WS" cancel job 2>/dev/null; then fail 'cancel: cancelled twice'; fi
printf 'PASS: cancel skips calls that have not run\n'

# An edit interrupted after it wrote the file but before its result was
# recorded is replayed from its journaled plan: same bytes, a success.
for point in after-started:1 after-exec:1; do
    setup; printf 'alpha\nbeta\n' > "$WS/f.txt"
    printf 'tool raw edit {"path":"f.txt","edits":[{"oldText":"beta","newText":"BETA"}]}\ntext done\n' > "$T/script"
    "$PIC" --db "$DB" --workspace "$WS" submit job 'go' > /dev/null
    if env PIC_CRASH_AT="$point" "$PIC" --db "$DB" --workspace "$WS" run --script "$T/script" 2>/dev/null; then
        fail "edit $point: no crash"
    fi
    "$PIC" --db "$DB" --workspace "$WS" run --script "$T/script"
    "$PIC" --db "$DB" check > /dev/null || fail "edit $point: integrity"
    "$PIC" --db "$DB" result 1 > "$T/result"
    printf 'Successfully replaced 1 block(s) in f.txt.\n' | expect "edit replayed from its plan after a crash at $point" 0
    [ "$(cat "$WS/f.txt")" = "$(printf 'alpha\nBETA')" ] || fail "edit $point: content"
done

# A relative --workspace: the file key is built from a relative path, which
# must not grow past its buffer (ASan in the dev build catches it if it does).
setup; mkdir "$T/rel"
printf 'tool raw write {"path":"sub/../r.txt","content":"rel\\n"}\ntext done\n' > "$T/script"
( cd "$T" && "$PIC" --db "$DB" --workspace rel submit job 'go' > /dev/null &&
  "$PIC" --db "$DB" --workspace rel run --script "$T/script" 2> "$T/stderr" ) || fail "relative workspace: $(cat "$T/stderr")"
[ "$(cat "$T/rel/r.txt")" = rel ] || fail "relative workspace: content"
printf 'PASS: a relative --workspace writes through its normalized path\n'
