#!/usr/bin/env bash
# Minimal JSONL utility retained for live library consumers.
set -euo pipefail

usage() { printf 'usage: journal.sh append <file> <json> | state <file> <task>\n' >&2; exit 2; }

case "${1:-}" in
  append)
    [[ $# -eq 3 ]] || usage
    file=$2 record=$3
    jq -e 'type == "object" and ((.formatVersion // 1) <= 1)' >/dev/null <<<"$record" || exit 3
    mkdir -p "$(dirname "$file")"
    printf '%s\n' "$record" >>"$file"
    ;;
  state)
    [[ $# -eq 3 && -f $2 ]] || usage
    jq -r --arg task "$3" 'select(.task == $task and .state != null) | .state' "$2" | tail -n1
    ;;
  *) usage ;;
esac
