Skip to content

fix(sdk): stop reading unreadable git-notes state as empty - #2575

Open
joslat wants to merge 5 commits into
github:devfrom
joslat:joslat/1211-state-backend-silent-catches
Open

joslat wants to merge 5 commits into
github:devfrom
joslat:joslat/1211-state-backend-silent-catches

Conversation

@joslat

@joslat joslat commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

What

The git-notes state layer stops treating an unreadable notes blob as empty. Before, the next write after any corruption silently replaced every entry. This is the C-residual part of #1211; D-residual (verifyLayers) is a separate feature and stays open there.

Why

Refs #1211 (C-residual: "audit other backends for swallowed catches")

I did the source verification Brady asked for on #1211. Out of 41 catch blocks in state-backend.ts, one swallowed an error in a way that loses data:

  • GitNotesBackend.loadBlobAt returned {} when the notes blob was invalid JSON, a non-object, or an array.
  • mutateBlob reads through it before every write, so the write then saved a blob containing only its own key.

Reproduced on dev (cfdc7c0): two entries are written, the note is truncated ({"decisions/a.md": "A", "decisions/b.md": "B"), then one normal write('decisions/c.md', 'C') runs. The note becomes { "decisions/c.md": "C" }, with no error. Reads in that state also report every key as missing.

Standalone git-notes is migrated to two-layer at runtime, so in practice this hits the notes layer of two-layer, which mirrors every write. The orphan branch stays authoritative there, so it's the mirror that gets wiped. It also hits SDK code that uses GitNotesBackend directly.

How

  • loadBlobAt returns {} only when there's no note yet. Invalid JSON, a non-object, or a non-string entry now throws the new StateBackendCorruptionError. Its message names the ref and commit, says Squad won't read or overwrite the blob, and gives the git notes --ref=squad show <root> command to inspect it. Because the error is thrown before atomicSaveBlob, nothing is written over the blob.
  • Circuit breaker: CircuitBreaker.execute doesn't count StateBackendCorruptionError as a failure. Corruption fails the same way every time; counting it would open the circuit after five calls and replace the actionable message with "Circuit breaker OPEN after 5 consecutive git failures".
  • two-layer: the existing [two-layer] notes write failed … catch now reports the corruption, and the orphan write still goes through. The notes blob is left alone instead of being reset.
  • Documented swallows, now tagged: TwoLayerBackend.readNote (unparseable note → null) and promoteNotes (unparseable note → skipped) keep their documented contracts, but log a [two-layer] warning that names the commit and ref.
  • Policy: the module header states the rule from State-backend v2: ref-level CAS, recursive deleteDir, stub-name collision, regression coverage #1211. Every catch rethrows, warns, returns an explicit failure result, or is a commented best-effort cleanup. I put it there instead of a separate state-backend.md so it sits next to the code. The new test enforces it over every catch in the file.
  • Audit result, unchanged on purpose: the [two-layer] notes-layer warnings, the config warning and local fallback in resolveStateBackend, verifyStateBackend's { ok: false } results, and the two commented best-effort cleanups in WorktreeBackend.createIfAbsent. In backend/state-backend-store.ts the catches are filesystem path probes (realpath fallbacks, .git/commondir checks), not state reads.
  • Docs: a short note under "Inspecting State → Git Notes" on what the error means and how to recover.

StateBackendCorruptionError is exported from the state-backend module, like StateBackendConcurrencyError; I didn't add it to the package index.

Testing

New test/state-backend-silent-catches.test.ts (11 tests):

  • the policy check over every catch in state-backend.ts;
  • for a note that is invalid JSON, a JSON array, a JSON string, or has a non-string entry: write, append, delete, createIfAbsent, read, exists and list all throw StateBackendCorruptionError, and the notes ref and note content are unchanged;
  • the message names the ref and the inspect command;
  • eight consecutive reads keep throwing the corruption error, not "circuit OPEN";
  • a repo without notes is still empty state (regression guard);
  • two-layer: the write lands on the orphan branch, the notes ref is unchanged, and a [two-layer] warning names the corruption;
  • readNote returns null and promoteNotes skips the note and leaves it in place, both with tagged warnings.

Results:

  • Against dev's state-backend.ts, 10 of the 11 fail; the one that passes is the regression guard.
  • state-backend, the root guard, the handshake, watch-notes-promote, cli/state-mcp, backend, upgrade-state-backend and resolution: 346 passed, 1 skipped.
  • npm run lint: clean. ESLint shows no errors, only the file's existing warnings. markdownlint and cspell are clean on the docs and changeset.

⚠️ Quick Check

  • If SDK/CLI source files changed: changeset added (.changeset/state-backend-no-silent-catches.md, sdk patch)

PR Readiness Checklist

Branch & Commit

  • Branch created from dev (not main)
  • Branch is up to date with dev (cfdc7c0)
  • Verified diff contains only intended changes (4 files)
  • PR is not in draft mode
  • Commit history is clean (one commit)

Build & Test

Docs

  • features/state-backends.md: what "Unreadable Squad state" means and how to recover

Breaking Changes

None for valid state. A git-notes blob that isn't a JSON object of strings now produces an error, where before Squad read it as empty and the next write replaced it.

Waivers

None.

GitNotesBackend.loadBlobAt returned {} when the notes blob was not a JSON
object. mutateBlob reads through it before every write, so the next write
saved a blob with only its own key and silently dropped every other entry,
and reads reported every key as missing. That hit the notes layer of
two-layer and any direct use of GitNotesBackend.

- loadBlobAt now throws StateBackendCorruptionError for invalid JSON, a
  non-object, or a non-string entry, naming the ref and how to inspect
  it, and nothing is written over the blob. A missing note is still
  empty state.
- The error doesn't count toward the circuit breaker, so repeated calls
  keep the actionable message.
- TwoLayerBackend.readNote and promoteNotes keep their documented
  behavior for unparseable notes but log a [two-layer] warning.
- The no-silent-catch policy is documented in the module header and
  enforced by a test over every catch in state-backend.ts.

Refs github#1211 (C-residual)
Copilot AI adaptive review requested due to automatic review settings December 3, 2026 03:20
@github-actions

github-actions Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

🟡 Impact Analysis — PR #2575

Risk tier: 🟡 MEDIUM

📊 Summary

Metric Count
Files changed 5
Files added 2
Files modified 3
Files deleted 0
Modules touched 4
Critical files 1

🎯 Risk Factors

  • 5 files changed (≤5 → LOW)
  • 4 modules touched (2-4 → MEDIUM)
  • Critical files touched: packages/squad-sdk/src/index.ts

📦 Modules Affected

docs (1 file)
  • docs/src/content/docs/features/state-backends.md
root (1 file)
  • .changeset/state-backend-no-silent-catches.md
squad-sdk (2 files)
  • packages/squad-sdk/src/index.ts
  • packages/squad-sdk/src/state-backend.ts
tests (1 file)
  • test/state-backend-silent-catches.test.ts

⚠️ Critical Files

  • packages/squad-sdk/src/index.ts

This report is generated automatically for every PR. See #733 for details.

@github-actions

github-actions Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

🛫 PR Readiness Check

ℹ️ This comment updates on each push. Last checked: commit dff2b11

PR Scope: 📦🔧 Mixed (product + infrastructure)

⚠️ 3 item(s) to address before review

Status Check Details
❌ Single commit 5 commits — consider squashing before review
✅ Not in draft Ready for review
✅ Branch up to date Up to date with dev
❌ Copilot review No Copilot review yet — it may still be processing
✅ Changeset present Changeset file found
✅ Scope clean No .squad/ or docs/proposals/ files
✅ No merge conflicts No merge conflicts
✅ Copilot threads resolved 1 active Copilot thread(s) resolved (12 outdated skipped)
❌ CI passing 10 check(s) still running

Files Changed (5 files, +618 −13)

File +/−
.changeset/state-backend-no-silent-catches.md +5 −0
docs/src/content/docs/features/state-backends.md +59 −0
packages/squad-sdk/src/index.ts +1 −1
packages/squad-sdk/src/state-backend.ts +115 −12
test/state-backend-silent-catches.test.ts +438 −0

Total: +618 −13


This check runs automatically on every push. Fix any ❌ items and push again.
See CONTRIBUTING.md and PR Requirements for details.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Malformed-note parse errors can expose stored state through warnings, leaving a critical data-exposure issue unresolved.

4 open issues
What changed in this PR

Protects unreadable git-notes state from being silently overwritten, addressing the swallowed-error audit in #1211.

Changes:

  • Adds typed corruption errors and excludes them from circuit-breaker failure counts.
  • Adds tagged warnings and regression tests.
  • Documents recovery and records an SDK patch changeset.
File Description
test/​state-backend-silent-catches.test.ts Tests corruption handling, state preservation, and catch policy.
packages/​squad-sdk/​src/​state-backend.ts Validates stored notes and surfaces parse failures.
docs/​src/​content/​docs/​features/​state-backends.md Explains corruption errors and recovery.
.changeset/​state-backend-no-silent-catches.md Records the SDK patch release note.

Review effort: Max (adaptive)

Comment thread packages/squad-sdk/src/state-backend.ts Resolved
Comment thread packages/squad-sdk/src/state-backend.ts Resolved
Comment thread packages/squad-sdk/src/state-backend.ts Resolved
…error

Follow-up from review:

- JSON.parse messages quote the start of the input, so the corruption
  error and the two-layer warnings now use a fixed reason and never
  include the note's content.
- Recovery advice no longer suggests deleting the ref. refs/notes/squad
  is a commit history, so the error and the docs explain how to back it
  up, find the last good version and re-add it as a new note, and to push
  the repaired ref before squad sync fetches the remote copy back.
- StateBackendCorruptionError is exported from the package index, next
  to GitNotesBackend.
- The circuit breaker counts a corruption error as a successful git call
  (it resets the failure count and closes a half-open circuit) instead
  of only skipping it.
@github-actions

github-actions Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

🏗️ Architectural Review

Authoritative evidence: scanners from the PR base commit, posted by the default-branch workflow_run reporter.
Results for head commit dff2b11addbe7976f6a31216f84d4ec5002d1e29.

⚠️ Architectural review: 1 warning(s).

Severity Category Finding Files
🟡 warning export-surface Package entry point(s) modified with 2 new/changed export(s). New public API surface requires careful review for backward compatibility. packages/squad-sdk/src/index.ts

Automated architectural review — informational only.

Comment thread packages/squad-sdk/src/state-backend.ts Resolved
…r from squad-state

The corruption error for a note whose entries aren't strings named the
first bad key, and a key can be stored text too. It now gives only a
count ("1 of 2 entries are not strings").

With two-layer, the notes ref only mirrors squad-state, and writes keep
reaching squad-state while the note is unreadable. Restoring an older
note version would bring back keys deleted meanwhile, and a later create
of such a key would fail on the stale mirror entry. TwoLayerBackend now
builds its notes layer with mirrorOf: 'squad-state', so the error says to
rebuild the note from squad-state instead, and the state backends guide
has the steps. The new test runs the guide's script on that scenario.
@bradygaster

bradygaster commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

Needs human approval/action — current-head reassessment

Assessed head: dff2b11addbe7976f6a31216f84d4ec5002d1e29
Actual base dev: cfdc7c0016703bf7340f1f50a4ce1924f725c41d

Independent state and security reviews found the specific legacy-entry issue addressed, but recovery completeness and recovery-process safety still require correction and human security review. Follow the repository security policy for security details.

The required test failed; gh-aw strict compile passed and license compliance was pending. Copilot completed a current-head COMMENTED review reporting 1 open issue(s); it is not an approval. Tamir and Brady remain requested. No human approval was found. Static review only; no PR code was run. Resolved threads do not themselves clear the hold.

Earlier assessments below apply only to their stated heads.

Needs human approval/action — current-head reassessment

Assessed head: a6195fc5c2a09e29ffde2824ff459b97795a3c45
Actual base dev: cfdc7c0016703bf7340f1f50a4ce1924f725c41d

Recovery hold: Independent state-storage review found that the recovery script stops at the first JSON object even if it contains non-string values. A corrupt current note can therefore hide a valid older legacy-only entry. Skip invalid objects before selecting a historical note, and cover this recovery case. Human reassessment of the earlier recovery hold remains necessary.

Evidence: Current-head test and Verify exact SHA and build evidence failed; gh-aw strict compile passed and license compliance was pending. Copilot review was requested for this head; Tamir and Brady remain requested, with no human approval established. Static review only; no PR code was run. This is not an approval.

Earlier assessments below apply only to their stated heads.

Squad review — hold

Assessed head: 35cc830817f201c57aaa0f85d62fcaeff13a8425
Assessed base: cfdc7c0016703bf7340f1f50a4ce1924f725c41d

Hold: Independent SDK and state-storage review found the recovery example can omit a valid root key named __proto__ from the repaired notes mirror. The authoritative branch remains intact; comparable behavior exists elsewhere in the base. Use a null-prototype object and cover the key in recovery tests. Required test failed; strict compile passed. Both humans are requested; Copilot feedback is noted below.

Focused static review only; no PR code was run. This is not an approval. Reassess after any head or base change.

Additional recovery hold: Independent state review confirmed current-head Copilot feedback: legacy git-notes entries are not necessarily copied when configuration normalizes to two-layer, so rebuilding a note solely from a partial orphan branch can omit recoverable keys. Reconcile history and establish source completeness before replacement; also pin the snapshot, pause concurrent writers, and check recovery commands for failure. Missing-note/shallow-anchor handling was not established as a new regression in this PR.

Copilot has commented on this head; both human reviews remain requested.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Critical state-handling flaws can overwrite nonempty notes or rebuild from incomplete data, risking loss of recoverable legacy keys.

5 open issues
1 previously missed issue

In code that hasn't changed since last review

Medium severity Reject catch paths that silently return instead of throwing

test/​state-backend-silent-catches.test.ts:49

The predicate accepts catch { /* do not throw */ return {}; }, and a conditional throw also masks a silent return. This lets the same swallowed-read pattern pass the claimed policy guard. Check executable catch paths or explicitly approved catches, and add negative fixtures for both cases.

4 resolved since last review

Review effort: Max (adaptive)

Comment thread packages/squad-sdk/src/state-backend.ts Resolved
Comment thread packages/squad-sdk/src/state-backend.ts Resolved
Comment thread packages/squad-sdk/src/state-backend.ts Resolved
… safe

- A ref whose root commit has no note while its tree holds others (a
  shallow clone anchored at the boundary, a missing blob, a note on
  another commit) no longer reads as empty state. It raises the
  corruption error, which says to unshallow in a shallow clone.
- Backups go to refs/squad-backup/notes-squad-<commit>, outside the
  refs/notes/ namespace that squad sync fetches and pushes.
- The two-layer rebuild reads squad-state at one commit, keeps (and
  lists) keys that only the notes ever had, such as entries from the old
  git-notes backend, and builds a null-prototype object so a __proto__
  key survives. The note is replaced only if the script succeeded and
  squad-state didn't move; both recipes chain with &&, so a failed step
  leaves the note as it was. The guide says to stop Squad and sync
  hooks during the repair.

The recovery tests run the guide's bash blocks as written, including a
failing extraction and a failing rebuild, and a shallow clone.
@joslat

joslat commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

@bradygaster thanks. Fixed in a6195fc. The recovery script now builds the state with Object.create(null), so a root key named __proto__ is an ordinary entry instead of setting the prototype. The two-layer recovery test writes a __proto__ key and checks that it's in the rebuilt mirror.

The same commit covers Copilot's five points on this head: each thread has the details and is resolved.

  • A missing root note while the ref holds others (a shallow clone, a missing blob) fails closed instead of reading as empty.
  • The rebuild reads squad-state at one pinned commit, keeps and lists keys that only the notes ever had, and replaces the note only if squad-state didn't move.
  • Backups go to refs/squad-backup/, outside the namespace squad sync fetches and pushes.
  • Both recipes chain with &&, so a failed step leaves the note as it was.

The recovery tests now run the guide's bash blocks as written, including the failing paths. All seven new tests fail on the previous head.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

An unreadable notes tree is treated as empty, risking state loss on the next write, and unsafe recovery commands can overwrite files outside the repository.

4 open issues
3 previously missed issues

In code that hasn't changed since last review

High severity Use private temporary files for recovery commands

docs/​src/​content/​docs/​features/​state-backends.md:175

A checkout can supply state.json or good.json as a symlink, so these recovery commands overwrite a file outside the repository. They also truncate existing project files and leave complete state copies in the working tree. Use private temporary files outside the checkout and always clean them up; the standalone recipe at line 142 needs mktemp and an EXIT trap too.

Medium severity Check that the two-layer branch exists before recommending it

packages/​squad-sdk/​src/​state-backend.ts:604

A legacy git-notes configuration can resolve to two-layer before squad-state has ever been created. This hint then claims a nonexistent branch holds the full state and recommends a rebuild that cannot run. Check whether that branch exists and use notes-history recovery when it does not; add the same fallback in the guide at line 145.

Medium severity Test createIfAbsent behavior with an unreadable mirror

test/​state-backend-silent-catches.test.ts:346

The corruption regression only tests TwoLayerBackend.write, but createIfAbsent commits the orphan key and then throws StateBackendUncertaintyError when the mirror is unreadable. A retry reports a key conflict, so callers receive failure even though the create landed. Add a regression asserting this existing fail-closed contract, the committed orphan value, and the unchanged notes ref.

5 resolved since last review

Review effort: Max (adaptive)

Comment thread packages/squad-sdk/src/state-backend.ts Resolved
Comment thread packages/squad-sdk/src/state-backend.ts Resolved
…yer rebuild

- A notes tree that can't be read is corruption, not empty state: only a
  listing that succeeds and is empty reads as {}.
- In a shallow clone, the cached root commit (the shallow boundary) is
  dropped when the mismatch is detected, so a retry after
  `git fetch --unshallow` uses the real root.
- The rebuild script in the guide:
  - stops when refs/notes/squad holds notes on other commits, since the
    backend's next write keeps only the root commit's note;
  - takes the newest note version that is an object of strings, skipping
    unreadable ones, instead of stopping at the first object;
  - checks a key's history on squad-state with a literal pathspec and
    an exact path, so `legacy/*.md` or a directory-like key isn't
    mistaken for files under it.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The catch in state-backend.ts replaces underlying Git errors with a generic corruption message, hiding details operators need to diagnose tree-read failures.

1 open issue
4 resolved since last review

Review effort: Max (adaptive)

Comment on lines +620 to +622
} catch {
throw new StateBackendCorruptionError(location, "the ref's notes tree can't be read", hint);
}

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

3 participants