From 818eb8cded579c0210459059cead9516b46bfbc4 Mon Sep 17 00:00:00 2001 From: goanscryca Date: Fri, 18 Sep 2026 06:36:15 +0300 Subject: [PATCH] fix(collector): safely handle malformed previous overview and allow self-healing When reading previous state from -output, an invalid or truncated JSON document (e.g. from an interrupted write or trailing bytes) caused jq to fail or emit multiple values, breaking --argjson previous and aborting subsequent collector runs indefinitely. Now gitwork validates that the previous file is a single JSON object. If it is invalid or empty, gitwork logs a warning to stderr, falls back to null (empty state) and replaces the corrupt file with a valid overview on the current run. Resolves #1 --- bin/gitwork | 6 +++++- tests/collector-test.sh | 7 +++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/bin/gitwork b/bin/gitwork index a957e12..e39c849 100755 --- a/bin/gitwork +++ b/bin/gitwork @@ -786,7 +786,11 @@ fi previous='null' if [[ -n $output && -r $output ]]; then - previous=$(jq -c . "$output" 2>/dev/null || echo 'null') + if prev_val=$(jq -c -s 'if length == 1 and (.[0] | type == "object") then .[0] else empty end' "$output" 2>/dev/null) && [[ -n $prev_val ]]; then + previous="$prev_val" + elif [[ -s $output ]]; then + echo "gitwork: warning: previous overview at $output is invalid JSON; ignoring" >&2 + fi fi document=$(jqm -n \ diff --git a/tests/collector-test.sh b/tests/collector-test.sh index ed59368..0d15f68 100755 --- a/tests/collector-test.sh +++ b/tests/collector-test.sh @@ -136,6 +136,13 @@ run_dead -output "$out" >/dev/null assert_eq "0" "$(jq -e . "$out" >/dev/null 2>&1; echo $?)" "a repeat run leaves valid JSON" assert_eq "3" "$(jq -r .schemaVersion "$out")" "a repeat run keeps the schema version" +# A corrupt previous document does not abort the run and self-heals +printf '{"schemaVersion": 3, "updatedAt": "2026-01-01T00:00:00Z", "providers": []}}\n' >"$out" +run_dead -output "$out" >/dev/null +assert_eq "0" "$(jq -e . "$out" >/dev/null 2>&1; echo $?)" "a corrupt previous file is replaced with valid JSON" +assert_eq "3" "$(jq -r .schemaVersion "$out")" "self-healed run keeps the schema version" +assert_contains "$(cat "$work/stderr")" "gitwork: warning" "a corrupt previous file emits a warning" + # --- formatting ------------------------------------------------------------ assert_eq "1" "$(run_dead -pretty false | wc -l)" "compact output is one line"