Skip to content

save-session.sh's two cooldown markers reach $(( )) unvalidated — one skipped cooldown per corruption, and a digits-only guard still lets octal through #322

Closed

Description

@jmossie82

Important

The mechanism, settled — this supersedes both the original "Impact" section below and my first correction comment.

Bash abandons the entire if … then … fi body at the failing arithmetic and resumes after fi. Measured on /bin/bash 3.2.57 and 5.2.37. Three consequences, all of which I got wrong earlier:

  1. Nothing dies. Not in save-session.sh, and not in 50-git-backup.sh either — its $ELAPSED sits inside the abandoned body, so set -u never sees an unbound variable. Against the real hook: rc=0, backup proceeds, commit lands. My earlier "Cooldown and lock robustness in 50-git-backup.sh: a corrupt marker bypasses the throttle, and the marker is only written on success #258's death mode" framing was wrong.
  2. There is exactly one diagnostic, not two. [ "$ELAPSED" -lt … ] is never reached, so integer expression expected is never emitted.
  3. Both markers self-heal. save-session.sh:158 rewrites the save marker after fi, and :585 rewrites the NDC marker on precisely the path a corrupt one allows. So one corruption costs one skipped cooldown and one stderr line, then repairs itself — not a throttle stuck off.

The unguarded reads are still real, and the case guard is still the right fix — but the severity is modest, and I withdraw the "17 occurrences" observation from the body below as evidence: with both gates self-healing, that count needs an external re-corrupting writer I never identified.

Still standing and independently verified: 08/09 pass a digits-only guard and then fail as octal (so 10# is needed alongside case), and ShellCheck does not detect this class even with -o all.


Summary

#258 hardened the cooldown marker read in 50-git-backup.sh, and the CHANGELOG describes the guard as "A numeric guard now falls back to 0, which self-heals, because the run it allows is the run that rewrites the marker."

The identical unguarded pattern is still present in scripts/save-session.sh, reading the NDC cooldown marker tmp/last-ndc.ts. It bit me on 0.15.0 — 17 times in one project, and a second project on this machine still had a corrupt marker waiting to trigger it.

The code (0.15.0, scripts/save-session.sh:564-568)

if [ "$RUN_NDC" = true ] && [ -f "$NDC_MARKER" ]; then
    NDC_MOD=$(cat "$NDC_MARKER" 2>/dev/null || echo 0)
    NDC_COOLDOWN=$(config ".cooldowns.ndc_seconds" 3600)
    [ $(( $(date +%s) - NDC_MOD )) -lt "$NDC_COOLDOWN" ] && RUN_NDC=false   # line 567
fi

NDC_MOD goes into $(( )) bare, so bash evaluates its value as an arithmetic expression. A stray character is therefore a syntax error, not a bad number.

Observed

.remember/logs/hook-errors.log, 17 lines, all identical in shape:

/Users/…/remember/0.15.0/scripts/save-session.sh: line 567: 1786158837;: syntax error: invalid arithmetic operator (error token is ";")

The marker held 1786158837; — a valid epoch with a trailing ;.

Reproduction

$ NDC_MOD="1786158837;"; echo $(( $(date +%s) - NDC_MOD ))
bash: 1786158837;: syntax error: invalid arithmetic operator (error token is ";")

Impact — worse than the throttle being bypassed

The intuitive reading is that the [ ... ] test fails, so RUN_NDC stays true and compression merely runs too often. That is backwards, exactly as #258 itself notes for the git-backup case.

An arithmetic syntax error is fatal to the shell, so the script dies at line 567. Verified on /bin/bash 3.2.57, with and without set -e — the statement after the gate never runs, exit 1:

$ /bin/bash -c 'set -e; BAD="1;"; [ $(( 10 - BAD )) -lt 5 ] && F=false; echo "AFTER_GATE_RAN"'
/bin/bash: 1;: syntax error: invalid arithmetic operator (error token is ";")
$ echo $?
1

(#258's note about the shape differing between bash 3.2 and bash 5 concerned set -u in 50-git-backup.sh. save-session.sh sets -e at line 56, and here the abort is at the line itself. I only have bash 3.2.57 available, so I have not confirmed the bash 5 shape.)

So on every affected save:

  • NDC compression never runs at all — the gate is inside Step 8, and the entire if [ "$RUN_NDC" = true ] body below it is skipped.
  • The "remove empty autonomous logs" housekeeping at the foot of the file is skipped too.

Why it is effectively invisible

  • The gate sits in Step 8 of 14. Step 7 has already appended the entry and saved the position, so the save genuinely succeeds.
  • scripts/doctor.sh therefore reports VERDICT: capture is working with a recent successful save — which is true, and hides that the back half of the script has not executed for weeks.
  • trap cleanup EXIT (line 102) still releases the lock, so nothing jams and no subsequent save is blocked.

The only trace anywhere is hook-errors.log, which doctor surfaces as a generic WARN … is non-empty. Same class as #258: "Memory destroyed, log reads clean."

It is not a one-off

Scanning every .remember/tmp/last-ndc.ts on this machine found two corrupt markers across seven projects — a second project's marker held 1777939222; and had been sitting there since May, guaranteed to abort its next save.

Because the marker is only rewritten after the gate is passed, a corrupt value is permanent — the same "stayed corrupt because it is only written on success" property #258 identified.

Provenance: unknown

I could not determine how the ; got written. Nothing in 0.15.0 or 0.5.0 can produce it — both write the marker with a bare date +%s > "$NDC_MARKER".

I did test #258's "partially synced file" hypothesis on this machine and ruled it out: macOS Desktop & Documents iCloud sync is off (FXICloudDriveDesktop = 0) and ~/Documents is a real local directory, not a redirect. A stray ; also is not a plausible truncation artifact of a digit stream.

Which is rather the point of the guard — the reader should not be load-bearing on the writer being perfect.

Suggested fix

The same shape as #258's, applied to this reader:

if [ "$RUN_NDC" = true ] && [ -f "$NDC_MARKER" ]; then
    # Braces so the redirect's own failure is silenced too, not just tr's: if the
    # marker is unlinked between the -f test and this read, the "No such file"
    # comes from the shell.
    NDC_MOD=$({ tr -cd '0-9' < "$NDC_MARKER"; } 2>/dev/null)
    [ -n "$NDC_MOD" ] || NDC_MOD=0
    NDC_COOLDOWN=$(config ".cooldowns.ndc_seconds" 3600)
    [ $(( $(date +%s) - NDC_MOD )) -lt "$NDC_COOLDOWN" ] && RUN_NDC=false
fi

Falling back to 0 self-heals for the reason #258 gives: the run it permits is the run that rewrites the marker. It also preserves existing behaviour — 0 is what the old || echo 0 already meant for an unreadable file.

Verified locally against the patched script: bash -n clean, and tests/test_ndc_day_boundary.py + tests/test_save_session_gates.py pass 31/31 (the 2**40 sentinel those tests use to suppress NDC still parses and still suppresses).

Possibly worth a sweep

#258 fixed one reader, this is a second. It may be worth grepping for any remaining bare variable inside $(( )) that originates from a file, rather than fixing them one report at a time.

Environment

  • plugin remember 0.15.0 (claude-plugins-official marketplace)
  • macOS 26.6, arm64
  • /bin/bash 3.2.57(1)-release — the shebang's interpreter

Activity

  1. jmossie82 commented on Aug 8, 2026

    @jmossie82
    ContributorAuthor

    I swept the whole plugin for the pattern rather than leaving it at one site, and it turned up a second unguarded reader in this same file — one that is worse than the NDC one. Also correcting the patch I suggested above.

    The sweep

    Every $(( )) / (( )) site across all 23 shell files in 0.15.0, with each operand traced to its origin. The result is a clean binary:

    Guarded — every file-sourced operand uses case "$X" in ''|*[!0-9]*) X=0 ;; esac:

    site operand
    hooks.d/after_save/50-git-backup.sh:172 LAST_MOD — #258's fix
    hooks.d/before_session_start/50-git-restore.sh:225,304 _s from FETCH_STATE_FILE
    scripts/post-tool-hook.sh:186 NOTICE_LAST
    scripts/post-tool-hook.sh:302 LAST_LINE from read-position
    scripts/post-tool-hook.sh:325 LAST_TS from tmp/last-save-ts
    scripts/run-consolidation.sh:213,218 staging_consumed (guarded at :197)
    scripts/lib-lock.sh:191,412 _mtime, _s/_f (plus 10# against octal)
    scripts/doctor.sh:261 _mtime
    scripts/save-session.sh:202,203,262,316,324,750,795 seven more, all guarded

    Everything else resolves to a counter, a literal, or wc/stat output.

    Unguarded — exactly two, both in scripts/save-session.sh:

    1. line 567 — NDC_MOD from tmp/last-ndc.ts. The one this issue is about.
    2. line 142 — LAST_MOD from tmp/last-save-ts. Not previously reported.

    The second one is the more serious

    # scripts/save-session.sh:141-143
    if [ -f "$COOLDOWN_MARKER" ] && [ "$DRY_RUN" != true ] && [ "$FORCE" != true ]; then
        LAST_MOD=$(cat "$COOLDOWN_MARKER" 2>/dev/null || echo 0)
        ELAPSED=$(( $(date +%s) - LAST_MOD ))

    Three things make it worse than the NDC site:

    • It is above Step 1. The NDC gate is in Step 8, so the entry has already been appended and the position saved by the time the script dies — the save succeeds and only compression is lost. This one is at line 143, before extraction. A corrupt marker means nothing is captured at all.
    • The repair write is below it. date +%s > "$COOLDOWN_MARKER" is at line 158, fifteen lines further down and unreachable once line 143 aborts. So the corruption is permanent, exactly the "stayed corrupt because it is only rewritten on success" property Cooldown and lock robustness in 50-git-backup.sh: a corrupt marker bypasses the throttle, and the marker is only written on success #258 identified — except here the marker is normally rewritten early in every run, so the property only bites in the one case where it matters.
    • post-tool-hook.sh reads the very same file and guards it. Line 315 sets COOLDOWN_MARKER="$REMEMBER_DIR/tmp/last-save-ts", and line 322 does case "$LAST_TS" in ''|*[!0-9]*) LAST_TS=0 ;; esac. So the hook tolerates the value that kills save-session.sh, decides no cooldown is in effect, and keeps forking saves that die instantly — every one of them logging a line nobody reads. doctor would report the PostToolUse marker as fresh throughout.

    Same fix:

    LAST_MOD=$(cat "$COOLDOWN_MARKER" 2>/dev/null || echo 0)
    case "$LAST_MOD" in
        ''|*[!0-9]*) LAST_MOD=0 ;;
    esac
    ELAPSED=$(( $(date +%s) - LAST_MOD ))

    I have not observed this one fire — all seven last-save-ts markers on this machine are currently clean. It is latent, and it is the same latency the NDC marker had until it wasn't.

    Correcting my suggested patch above

    I proposed NDC_MOD=$({ tr -cd '0-9' < "$NDC_MARKER"; } 2>/dev/null). Please prefer the case form for both sites instead — it is what #258 already established, what the other seven guards in this file use, and it differs from tr in a way that matters:

    tr -cd '0-9' salvages: 1786158837; becomes a valid-looking timestamp that is then trusted. case rejects: anything that failed to parse falls to 0, which forces a run, which rewrites the marker. The only thing genuinely known about a marker that did not parse is that it cannot be relied upon, so rejecting is the correct reading — and it keeps one idiom across the file.

    Verified locally with both sites guarded the case way: bash -n clean, tests/test_ndc_day_boundary.py + tests/test_save_session_gates.py 31/31.

    Suggestion

    Given this file alone already carries seven correct instances of the guard and missed two, a lint rule or a test asserting that no bare variable reaches $(( )) from a file read would be worth more than fixing the third one by hand later.

  2. jmossie82 commented on Aug 8, 2026

    @jmossie82
    ContributorAuthor

    Correction — I got the impact wrong in the issue body, and it matters

    The script does not die. My "everything below is skipped" claim above is wrong, and so is the same claim in my previous comment. Correcting it before anyone acts on it, along with two things it turned up.

    What actually happens

    Bash prints the diagnostic, abandons the rest of the current command list, and resumes at the next line with rc 0. Measured on /bin/bash 3.2.57 in a real script file with the gate's exact structure:

    t.sh: line 7: 1786158837;: syntax error: invalid arithmetic operator (error token is ";")
    REACHED_AFTER_IF  RUN_NDC=true
    NDC_BLOCK_RAN -> would rewrite the marker here
    END_OF_SCRIPT
       rc=0
    

    How I fooled myself: I tested with bash -c 'set -e; BAD="1;"; [ $((10 - BAD)) -lt 5 ] && F=false; echo AFTER'. That prints no AFTER and exits 1 — which reads as "the script dies." But the entire -c string is one command list, so abandoning the list consumes the echo too. Put the statements on separate lines and AFTER runs, rc 0. A true exit requires POSIX mode, /bin/sh, or dash — cf. Bash POSIX Mode item 32.

    So the real impact at both sites is the cooldown is silently disabled:

    • line 567 (NDC): && RUN_NDC=false never runs → RUN_NDC stays true → compression runs on every save, ignoring cooldowns.ndc_seconds.
    • line 142 (save): ELAPSED=$(( ... )) is abandoned → ELAPSED stays unset → the next line's [ "$ELAPSED" -lt "$SAVE_COOLDOWN" ] prints integer expression expected and is false → the save proceeds. Throttle disabled, two error lines per run.

    The production evidence backs this and I misread it the first time. The marker values in my 17 log lines increase on every run. That can only happen if execution continued past the gate and reached date +%s > "$NDC_MARKER". Had the script died, all 17 lines would carry the same stuck value. My original "the throttle is bypassed" reading was right; my correction to it was wrong.

    This also affects how #258 is described

    The CHANGELOG for #258 says the reporter's "bypasses the throttle" direction was backwards and that the hook dies. Both are true, but of different corrupt bytes, and the entry states it generally:

    • a syntax-error byte (;, punctuation) → list abandoned, execution continues, throttle bypassed — the reporter's original direction;
    • an identifier-shaped value (abc) under set -u → unbound variable → genuinely fatal, which is the 50-git-backup.sh case since it sets -u.

    save-session.sh sets -e but not -u, so the fatal path isn't available here at all. Worth a clause in that entry, since as written it generalises one byte class to all of them.

    The case guard is necessary but NOT sufficient — octal

    08 and 09 are all-digits, so they pass case "$X" in ''|*[!0-9]*), and are then read as octal:

    $ X=08; case "$X" in ''|*[!0-9]*) X=0 ;; esac; echo $(( 100 - X ))
    z.sh: line 6: 08: value too great for base (error token is "08")
    REACHED_END      <-- same abandonment, from a marker that looks clean
    

    A hole of exactly the original shape, and it survives the fix in 50-git-backup.sh today. The completion is 10#, after the guard (never instead of it — 10# on an empty string is itself an error on bash 5):

    case "$LAST_MOD" in ''|*[!0-9]*) LAST_MOD=0 ;; esac
    ELAPSED=$(( $(date +%s) - 10#$LAST_MOD ))

    Verified across 1786169541, 1786158837;, empty, abc, 08, 09, 010, 0x1f, " 12", -5 — all yield a sane number, no diagnostics, rc 0.

    Severity is higher than "robustness": this is an injection sink

    The marker contents reach an arithmetic evaluator, and bash arithmetic executes command substitutions. No array required, on 3.2.57:

    $ printf 'x[$(echo PAYLOAD_EXECUTED >&2)]\n' > marker
    $ LAST=$(cat marker); echo "elapsed=$(( 1786170000 - LAST ))"
    PAYLOAD_EXECUTED
    elapsed=1786170000
    

    The case guard blocks it. In practice the threat is bounded — writing that marker already implies local write access to .remember/tmp/ — so I am not claiming a privilege boundary is crossed. But it moves the class from "a crash" to "arbitrary command execution from file contents," which is worth knowing when deciding priority, and matters for any reader of state that could arrive from elsewhere. Note 50-git-backup.sh excludes tmp/ via $GIT_DIR/info/exclude, but the code at :482 shows stores created by older versions did track tmp/ — so a legacy store is a path by which marker bytes could originate off-machine.

    This is BashPitfalls #7, which endorses precisely the case idiom and frames it as command injection; also NCC Group, Shell Arithmetic Expansion and Evaluation Abuse, noting quoting does not help in arithmetic context.

    On my "add a lint rule" suggestion — ShellCheck will not do it

    Measured, ShellCheck 0.11.0 on the exact bug, including shellcheck -o all: zero findings. None of the 11 optional checks concerns arithmetic or external data. SC2004 is the nearby code and its advice actively steers toward the form in this bug (drop the $); SC2086 never fires inside $(( )) since arithmetic context does no word splitting. The open request is koalaman/shellcheck#2679, "Warn about the use of unvalidated input in arithmetic contexts" — open since 2023-02-01, no SC code assigned.

    So the guard has to be a repo-local test, not a linter adoption. Given this file already carries seven correct instances of the idiom and missed two, and that the correct form is now case plus 10#, a test asserting that every $(( )) operand traceable to a file read is guarded both ways would be worth more than fixing the third instance by hand later.

    Net

    The two unguarded sites are real and worth fixing; the 10# gap applies to the already-fixed 50-git-backup.sh too. Only my description of the consequence was wrong — it is a silently disabled throttle, not a dead script. Sorry for the churn; better here than in your changelog.

  3. changed the title [-]#258's numeric guard was not applied to save-session.sh's NDC marker — a corrupt tmp/last-ndc.ts kills the script at line 567, so NDC compression never runs[/-] [+]#258's numeric guard was not applied to save-session.sh's two marker reads — a corrupt marker silently disables the cooldown, and the guard itself misses octal[/+] on Aug 8, 2026
  4. changed the title [-]#258's numeric guard was not applied to save-session.sh's two marker reads — a corrupt marker silently disables the cooldown, and the guard itself misses octal[/-] [+]save-session.sh's two cooldown markers reach $(( )) unvalidated — one skipped cooldown per corruption, and a digits-only guard still lets octal through[/+] on Aug 8, 2026
  5. jmossie82 commented on Aug 8, 2026

    @jmossie82
    ContributorAuthor

    Mechanism, settled — supersedes the set -u framing in my previous comment.

    Bash abandons the entire if … then … fi body at the failing arithmetic and resumes after fi. Measured on /bin/bash 3.2.57 and 5.2.37:

    enter then-block
    t.sh: line 7: 08: value too great for base (error token is "08")
    AFTER_FI                     <-- the three statements between are all skipped
    

    That single fact corrects three things I said above:

    • Nothing dies, in either file. 50-git-backup.sh's $ELAPSED is inside the abandoned body, so set -u never sees an unbound variable. Against the real hook with a corrupt marker: rc=0, backup proceeds, commit lands. The -u contrast I drew was wrong — the consequence is the same in both files.
    • One diagnostic, not two. [ "$ELAPSED" -lt … ] is never reached, so integer expression expected cannot be emitted.
    • Both markers self-heal. save-session.sh:158 rewrites the save marker after fi; :585 rewrites the NDC marker on exactly the path a corrupt one allows. One corruption = one skipped cooldown + one stderr line, then repaired.

    So the honest severity is modest, and I'm withdrawing the "17 occurrences" observation as evidence — with both gates self-healing it requires an external re-corrupting writer, and I never identified one. It stays an unexplained observation on one machine, not support for any claim here.

    What survives verification and still seems worth fixing:

    1. Unvalidated file content reaching an arithmetic evaluator, which is the sink BashPitfalls #7 names and which case is already your chosen answer for in Cooldown and lock robustness in 50-git-backup.sh: a corrupt marker bypasses the throttle, and the marker is only written on success #258.
    2. 08/09 pass a digits-only guard and then fail as octal — so 10# is needed alongside case. Only reachable via a corrupt marker, which is this issue's whole premise.
    3. It removes an unexplained stderr line, which matters more since dispatch discards a dying hook's stderr and reports it as a nameless hook failed, so a fatal hook error reaches nobody #277 made hook stderr visible.

    One thing found while writing tests, unrelated to the fix and probably worth its own issue — say the word and I'll file it separately rather than bundle it: test_a_corrupt_cooldown_marker_does_not_kill_the_hook writes <store>/.last-git-backup-ts, but the hook reads <store>/.git/remember/last-git-backup-ts. The test has been feeding the script a decoy, so every corrupt value passes trivially and #258's regression is currently unguarded. Pointing it at the real path and asserting on proc.stderr (the outcome alone is bash-version-dependent) makes 08/09 fail there as expected.

    I have a patch for save-session.sh plus a regression test, tests red-before/green-after, full suite green. Happy to open it, or to leave this as a report if you'd rather take it yourself.

  6. added 3 commits that reference this issue on Aug 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions