You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(sdk): stop reading unreadable git-notes state as empty - #2575
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.
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)
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.
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)
…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.
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.
…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.
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.
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.
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.
… 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.
@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.
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.
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.
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.
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.
…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.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
catchblocks instate-backend.ts, one swallowed an error in a way that loses data:GitNotesBackend.loadBlobAtreturned{}when the notes blob was invalid JSON, a non-object, or an array.mutateBlobreads 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 normalwrite('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-notesis migrated totwo-layerat runtime, so in practice this hits the notes layer oftwo-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 usesGitNotesBackenddirectly.How
loadBlobAtreturns{}only when there's no note yet. Invalid JSON, a non-object, or a non-string entry now throws the newStateBackendCorruptionError. Its message names the ref and commit, says Squad won't read or overwrite the blob, and gives thegit notes --ref=squad show <root>command to inspect it. Because the error is thrown beforeatomicSaveBlob, nothing is written over the blob.CircuitBreaker.executedoesn't countStateBackendCorruptionErroras 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.TwoLayerBackend.readNote(unparseable note →null) andpromoteNotes(unparseable note → skipped) keep their documented contracts, but log a[two-layer]warning that names the commit and ref.state-backend.mdso it sits next to the code. The new test enforces it over every catch in the file.[two-layer]notes-layer warnings, the config warning and local fallback inresolveStateBackend,verifyStateBackend's{ ok: false }results, and the two commented best-effort cleanups inWorktreeBackend.createIfAbsent. Inbackend/state-backend-store.tsthe catches are filesystem path probes (realpath fallbacks,.git/commondirchecks), not state reads.StateBackendCorruptionErroris exported from thestate-backendmodule, likeStateBackendConcurrencyError; I didn't add it to the package index.Testing
New
test/state-backend-silent-catches.test.ts(11 tests):state-backend.ts;write,append,delete,createIfAbsent,read,existsandlistall throwStateBackendCorruptionError, and the notes ref and note content are unchanged;two-layer: the write lands on the orphan branch, the notes ref is unchanged, and a[two-layer]warning names the corruption;readNotereturnsnullandpromoteNotesskips the note and leaves it in place, both with tagged warnings.Results:
dev'sstate-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-backendandresolution: 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..changeset/state-backend-no-silent-catches.md, sdk patch)PR Readiness Checklist
Branch & Commit
dev(notmain)dev(cfdc7c0)Build & Test
npm run lintpassesstate-backend.tsand the same docs page; they merge cleanly)Docs
features/state-backends.md: what "Unreadable Squad state" means and how to recoverBreaking 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.