From 60f406e29907a81271a57015552639a38597d7f2 Mon Sep 17 00:00:00 2001 From: cairn-reviewer-scratch Date: Wed, 19 Aug 2026 13:21:24 -0700 Subject: [PATCH 1/3] =?UTF-8?q?test(feat):=20red=20=E2=80=94=20Branch-awar?= =?UTF-8?q?e=20discovery:=20Reindex/IterEntries=20read=20pending=20remembe?= =?UTF-8?q?r/*=20branches=20(refs=20crn-evw98.2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/backfill_test.go | 2 +- cmd/remember_test.go | 108 ++++----- internal/cairn/dedup_test.go | 27 +-- internal/cairn/doctor_test.go | 18 +- internal/cairn/entry_test.go | 156 +++++++++++-- internal/cairn/index_test.go | 2 +- internal/cairn/relative_store_test.go | 6 +- internal/cairn/remember_test.go | 274 ++++++++++++++++++----- internal/cairn/review_status_test.go | 4 +- internal/cairn/sweep_test.go | 2 +- internal/critic/freshness_test.go | 2 +- internal/critic/perf_test.go | 2 +- internal/critic/recall_test.go | 2 +- internal/critic/scope_precedence_test.go | 2 +- 14 files changed, 446 insertions(+), 161 deletions(-) diff --git a/cmd/backfill_test.go b/cmd/backfill_test.go index 83b7ac1b..30f0cc88 100644 --- a/cmd/backfill_test.go +++ b/cmd/backfill_test.go @@ -63,7 +63,7 @@ func TestBackfillPreservesLegacyRemediationClassification(t *testing.T) { require.NoError(t, os.WriteFile(filepath.Join(store, "global", "known.md"), []byte(classified), 0o600)) gitInit(t, store) - records, counts, err := collectBackfill(store) + records, counts, err := collectBackfill(context.Background(), store) require.NoError(t, err) require.Len(t, records, 1) assert.Equal(t, 1, counts.Classified, "reruns skip entries already carrying a type") diff --git a/cmd/remember_test.go b/cmd/remember_test.go index e43a4310..15ea0ad2 100644 --- a/cmd/remember_test.go +++ b/cmd/remember_test.go @@ -1256,19 +1256,20 @@ func TestRememberSharedTierRoleScopeVisibleAfterReviewMerge(t *testing.T) { // TestCommitRecurrenceToReviewBranchAppendsSecondCommitToExistingBranch for // the same fix exercised directly against the git primitive; this proves // RunE actually wires it up end to end. -// TestRememberCrossCallSharedTierRecurrenceNotDetectedWhilePendingReview -// documents crn-rymq3's fix as it appears one layer above -// TestWriteBackRecurrenceCountFailsWhilePendingReview -// (internal/cairn/remember_test.go): recurrenceMatch (cmd/remember.go) -// finds candidates via cairn.IterEntries, a disk scan of the store's own -// working tree -- and crn-rymq3 removes e1's body file from there entirely -// once its first review commit lands, for as long as that commit is still -// pending on remember/. So a second call with a near-identical body, -// made before anyone has reviewed the first, no longer finds e1 as a -// candidate at all: it is treated as an unrelated, brand-new capture, not -// discarded as a recurrence -- crn-qxj3's dedup behavior, working correctly -// before crn-rymq3, is now a known, documented gap. Follow-up: crn-evw98. -func TestRememberCrossCallSharedTierRecurrenceNotDetectedWhilePendingReview(t *testing.T) { +// TestRememberCrossCallSharedTierRecurrenceReusesReviewBranch documents +// crn-evw98's fix restoring crn-qxj3's dedup behavior on the shared tier: +// recurrenceMatch (cmd/remember.go) finds candidates via cairn.IterEntries, +// which now enumerates open remember/* branches (cairn.ListReviewBranches) +// in addition to the store's own working tree -- so e1 remains a visible +// recurrence candidate for as long as its review commit is pending on +// remember/, exactly as it was before commitToReviewWorktree started +// clearing the working-tree copy (#121). Mirrors +// TestRememberCrossCallPrivateTierRecurrenceCommitsDirectly's shape, the +// shared tier's own already-passing counterpart; see internal/cairn's +// TestCommitRecurrenceToReviewBranchAppendsSecondCommitToExistingBranch for +// the same fix exercised directly against the git primitive, proving RunE +// actually wires it up end to end. +func TestRememberCrossCallSharedTierRecurrenceReusesReviewBranch(t *testing.T) { t.Setenv("CAIRN_IDENTITY", "rig:web role:reviewer") store := t.TempDir() gitInit(t, store) @@ -1283,28 +1284,33 @@ func TestRememberCrossCallSharedTierRecurrenceNotDetectedWhilePendingReview(t *t branch1 := "remember/" + e1.ID firstCommit := strings.TrimSpace(gitOutput(t, store, "rev-parse", branch1)) - secondOut := captureStdout(t, func() { - err := runRememberAgainstStore(t, store, "--topic", "shared-hook", "--scope", "role:reviewer", "configure the shared hook") - require.NoError(t, err, "with e1 no longer visible on disk while its review is pending, a near-identical second call must be treated as an unrelated new entry, not rejected as a recurrence") + var secondErr error + stderr := captureStderr(t, func() { + captureStdout(t, func() { + secondErr = runRememberAgainstStore(t, store, "--topic", "shared-hook", "--scope", "role:reviewer", "configure the shared hook") + }) }) - secondLines := strings.Split(strings.TrimSpace(secondOut), "\n") - require.Len(t, secondLines, 3, "the second call must print the same ordinary new-entry shape as the first -- it has no way left to know e1 exists") + require.Error(t, secondErr, "crn-qxj3: a genuine same-body recurrence must be reported as a discarded write, not silent success") + assert.Contains(t, secondErr.Error(), e1.ID) + assert.Contains(t, stderr, e1.ID, "the discard must be explained on stderr") - // e1's own review branch, under rig/web, must be completely untouched: - // still the only entry there, RecurrenceCount still 0, tip unmoved. + // e1's own review branch, under rig/web, must gain a second commit + // bumping RecurrenceCount -- the recurrence bump is real telemetry even + // though the overall write is reported as an error (crn-qxj3). e1After := requireSingleEntryOnReviewBranch(t, store, filepath.Join(store, "rig", "web")) assert.Equal(t, e1.ID, e1After.ID) - assert.Equal(t, 0, e1After.RecurrenceCount, "e1 must remain unmatched -- its RecurrenceCount was never incremented") + assert.Equal(t, 1, e1After.RecurrenceCount, "e1 must be matched -- its RecurrenceCount must be incremented") - unchangedCommit := strings.TrimSpace(gitOutput(t, store, "rev-parse", branch1)) - assert.Equal(t, firstCommit, unchangedCommit, "e1's own review branch must be completely untouched -- no recurrence commit was ever appended to it") + secondCommit := strings.TrimSpace(gitOutput(t, store, "rev-parse", branch1)) + assert.NotEqual(t, firstCommit, secondCommit, "the recurrence commit must land as a second commit on e1's own review branch") + parent := strings.TrimSpace(gitOutput(t, store, "rev-parse", branch1+"~1")) + assert.Equal(t, firstCommit, parent, "the recurrence commit must land directly on top of e1's first-capture commit") - // The second call's own --scope (role:reviewer, unchanged from the - // original pre-crn-rymq3 test's deliberate cross-scope setup) routes its - // new entry to a directory of its own, independent of e1: proof it was - // filed as a brand-new capture, not detected as a recurrence and merged. - e2 := requireSingleEntryOnReviewBranch(t, store, filepath.Join(store, "role", "reviewer")) - assert.NotEqual(t, e1.ID, e2.ID, "the second call must create its own independent entry, not reuse or merge into e1's id") + // A recurrence hit never calls Create (recordRecurrence returns before + // RunE reaches it), so the second call's own --scope (role:reviewer) + // must never get a scope directory of its own. + assert.NoDirExists(t, filepath.Join(store, "role", "reviewer"), + "a recurrence hit must never create the discarded candidate's own scope directory, since Create is never called") } // TestRememberCrossCallPrivateTierRecurrenceCommitsDirectly covers @@ -1536,17 +1542,12 @@ func TestRememberEmptyTopicNeverMatchesForRecurrence(t *testing.T) { // role:reviewer; an identity of just rig:web can't see it (Visible is a // subset match -- every scope tag on the entry must be in the identity's own // tag set, and role:reviewer isn't in {rig:web}) -- even though E1's scope -// IS genuinely incomparable with the second call's rig:web scope, the same -// mechanism that lets -// TestRememberCrossCallSharedTierRecurrenceNotDetectedWhilePendingReview's -// first call be found at all once merged. E1 is merged before the second -// call specifically so that recurrenceMatch's disk scan (cairn.IterEntries) -// can find it in principle: left pending, crn-rymq3 would remove it from -// the store's working tree entirely, giving this test a second, unrelated -// reason for the same "no match" outcome and confounding what it claims to -// isolate (see -// TestRememberCrossCallSharedTierRecurrenceNotDetectedWhilePendingReview for -// that pending-review case on its own). This keeps visibility the one +// IS genuinely incomparable with the second call's rig:web scope. E1 is +// merged before the second call purely to keep the fixture on a plain +// working-tree read (requireSingleEntry, not the review-branch helpers); +// since crn-evw98, cairn.IterEntries finds a candidate whether its review is +// pending or merged, so that choice no longer isolates anything -- it's +// simplification, not confound-avoidance. This keeps visibility the one // variable under test. func TestRememberRecurrenceRequiresVisibleMatch(t *testing.T) { store := t.TempDir() @@ -1948,19 +1949,15 @@ func TestRememberForceOverridesRecurrenceMatchPrivateTier(t *testing.T) { assert.Equal(t, first.ID, second.OverriddenDuplicateOf, "the forced entry must record which entry it overrode") } -// TestRememberForceCannotNameDuplicateWhilePendingReview is +// TestRememberForceOverridesRecurrenceMatchSharedTier is // TestRememberForceOverridesRecurrenceMatchPrivateTier's shared-tier -// counterpart, documenting the same crn-rymq3 gap from --force's angle: -// --force's override-and-name-duplicate behavior (crn-lzn4.1.1) still goes -// through recurrenceMatch to find what it's overriding, and that lookup no -// longer finds a shared-tier entry once its own review commit is pending -// (see TestRememberCrossCallSharedTierRecurrenceNotDetectedWhilePendingReview -// above). So --force against a still-pending first entry can no longer name -// a duplicate to override at all: it falls back to behaving exactly like -// TestRememberForceWithNoMatchBehavesLikeOrdinaryCreate below -- an -// ordinary create, no override line, no OverriddenDuplicateOf -- even -// though a genuine duplicate exists. Follow-up: crn-evw98. -func TestRememberForceCannotNameDuplicateWhilePendingReview(t *testing.T) { +// counterpart: --force against a candidate that would otherwise match an +// existing pending-review entry as a recurrence (see +// TestRememberCrossCallSharedTierRecurrenceReusesReviewBranch) instead +// creates a new entry on its own review branch, records +// OverriddenDuplicateOf on it, and prints the override line between the id +// and the review-branch/mailed-reviewer lines. +func TestRememberForceOverridesRecurrenceMatchSharedTier(t *testing.T) { store := t.TempDir() gitInit(t, store) t.Setenv("CAIRN_IDENTITY", "rig:web") @@ -1984,7 +1981,10 @@ func TestRememberForceCannotNameDuplicateWhilePendingReview(t *testing.T) { require.Contains(t, byID, first.ID, "first's own review branch must still exist, untouched") secondLines := strings.Split(strings.TrimSpace(secondOut), "\n") - require.Len(t, secondLines, 3, "with no duplicate left to name, --force must fall back to the ordinary create shape: id, review branch, mailed reviewer -- no override line") + require.Len(t, secondLines, 4, "a forced-override shared-tier create prints the id, override line, review branch, and mailed reviewer") + assert.Equal(t, "override: forced past duplicate of "+first.ID, secondLines[1]) + assert.True(t, strings.HasPrefix(secondLines[2], "review branch: ")) + assert.True(t, strings.HasPrefix(secondLines[3], "mailed reviewer: ")) var second *cairn.Entry for _, e := range byID { @@ -1993,7 +1993,7 @@ func TestRememberForceCannotNameDuplicateWhilePendingReview(t *testing.T) { } } require.NotNil(t, second) - assert.Empty(t, second.OverriddenDuplicateOf, "with the duplicate undiscoverable, --force has nothing to record as overridden") + assert.Equal(t, first.ID, second.OverriddenDuplicateOf, "the forced entry must record which entry it overrode") } // TestRememberForceWithNoMatchBehavesLikeOrdinaryCreate covers crn-lzn4.1.1's diff --git a/internal/cairn/dedup_test.go b/internal/cairn/dedup_test.go index 27d663ea..339a1c5d 100644 --- a/internal/cairn/dedup_test.go +++ b/internal/cairn/dedup_test.go @@ -1,6 +1,7 @@ package cairn import ( + "context" "os" "path/filepath" "testing" @@ -37,7 +38,7 @@ func TestDedupTopicKeyCollisionSameTier(t *testing.T) { writeFile(t, dir, "rig/alpha/one.md", minimalEntry("rig/one", "One", "s1", "dup-key", `["rig:alpha"]`)) writeFile(t, dir, "rig/beta/two.md", minimalEntry("rig/two", "Two", "s2", "dup-key", `["rig:beta"]`)) - findings, err := Dedup(dir) + findings, err := Dedup(context.Background(), dir) require.NoError(t, err) tk := dedupFindingsOfKind(findings, "topic_key") @@ -55,7 +56,7 @@ func TestDedupEntriesUsesSuppliedList(t *testing.T) { writeFile(t, dir, "rig/alpha/one.md", minimalEntry("rig/one", "One", "s1", "dup-key", `["rig:alpha"]`)) writeFile(t, dir, "rig/beta/two.md", minimalEntry("rig/two", "Two", "s2", "dup-key", `["rig:beta"]`)) - all, failures, err := IterEntriesTolerant(dir) + all, failures, err := IterEntriesTolerant(context.Background(), dir) require.NoError(t, err) require.Empty(t, failures) @@ -75,7 +76,7 @@ func TestDedupTopicKeyCollisionGroupOfThree(t *testing.T) { writeFile(t, dir, "global/b.md", minimalEntry("g/b", "B", "sb", "shared", "[]")) writeFile(t, dir, "global/c.md", minimalEntry("g/c", "C", "sc", "shared", "[]")) - findings, err := Dedup(dir) + findings, err := Dedup(context.Background(), dir) require.NoError(t, err) tk := dedupFindingsOfKind(findings, "topic_key") @@ -91,7 +92,7 @@ func TestDedupTopicKeyNoCollisionAcrossTiers(t *testing.T) { writeFile(t, dir, "rig/alpha/default.md", minimalEntry("rig/default", "Default", "d", "override-me", `["rig:alpha"]`)) writeFile(t, dir, "role/builder/override.md", minimalEntry("role/override", "Override", "o", "override-me", `["rig:alpha", "role:builder"]`)) - findings, err := Dedup(dir) + findings, err := Dedup(context.Background(), dir) require.NoError(t, err) assert.Empty(t, dedupFindingsOfKind(findings, "topic_key"), "cross-tier shared topic_key is intentional shadowing, not a dup") @@ -105,7 +106,7 @@ func TestDedupUntopicedNeverCollide(t *testing.T) { writeFile(t, dir, "global/a.md", "+++\nid = \"g/a\"\ntitle = \"A\"\nscope = []\n+++\nbody\n") writeFile(t, dir, "global/b.md", "+++\nid = \"g/b\"\ntitle = \"B\"\nscope = []\n+++\nbody\n") - findings, err := Dedup(dir) + findings, err := Dedup(context.Background(), dir) require.NoError(t, err) assert.Empty(t, dedupFindingsOfKind(findings, "topic_key")) @@ -169,7 +170,7 @@ func TestDedupContentSimilarityPair(t *testing.T) { "g/hook-b", "Enabling the shared pre-commit hook", "How to configure the git pre-commit hook in this repo", "topic-b", "[]")) - findings, err := Dedup(dir) + findings, err := Dedup(context.Background(), dir) require.NoError(t, err) content := dedupFindingsOfKind(findings, "content") @@ -190,7 +191,7 @@ func TestDedupDistinctLowOverlapNoBead(t *testing.T) { "g/deploy", "Deploying the worker service to production", "Rolling out a new worker build via the deploy pipeline", "topic-b", "[]")) - findings, err := Dedup(dir) + findings, err := Dedup(context.Background(), dir) require.NoError(t, err) assert.Empty(t, findings) } @@ -209,7 +210,7 @@ func TestDedupSkipsContentPairAlreadySharingTopicKey(t *testing.T) { "role/hook", "Enabling the shared pre-commit hook", "How to configure the git pre-commit hook in this repo", "shared-hook", `["rig:alpha", "role:builder"]`)) - findings, err := Dedup(dir) + findings, err := Dedup(context.Background(), dir) require.NoError(t, err) assert.Empty(t, findings, "same topic_key with a genuine superset scope relationship is legitimate shadowing; no separate content finding") } @@ -230,7 +231,7 @@ func TestDedupCrossTierSharedTopicKeyIncomparableScopesGetsContentCheck(t *testi "role/hook", "Enabling the shared pre-commit hook", "How to configure the git pre-commit hook in this repo", "shared-hook", `["role:builder"]`)) - findings, err := Dedup(dir) + findings, err := Dedup(context.Background(), dir) require.NoError(t, err) content := dedupFindingsOfKind(findings, "content") @@ -257,7 +258,7 @@ func TestDedupCrossTierSharedTopicKeyIncomparableScopesLowSimilarityStillNoBead( "role/deploy", "Deploying the worker service to production", "Rolling out a new worker build via the deploy pipeline", "shared-key", `["role:builder"]`)) - findings, err := Dedup(dir) + findings, err := Dedup(context.Background(), dir) require.NoError(t, err) assert.Empty(t, findings) } @@ -269,7 +270,7 @@ func TestDedupAgentTierExcluded(t *testing.T) { writeFile(t, dir, "agent/bot1/a.md", minimalEntry("agent/a", "A", "sa", "dup", "[]")) writeFile(t, dir, "agent/bot2/b.md", minimalEntry("agent/b", "B", "sb", "dup", "[]")) - findings, err := Dedup(dir) + findings, err := Dedup(context.Background(), dir) require.NoError(t, err) assert.Empty(t, findings) } @@ -299,7 +300,7 @@ func TestDedupNeverWrites(t *testing.T) { before[p] = b } - findings, err := Dedup(dir) + findings, err := Dedup(context.Background(), dir) require.NoError(t, err) require.NotEmpty(t, findings, "this fixture must actually produce findings for the no-write check to mean anything") @@ -314,7 +315,7 @@ func TestDedupNeverWrites(t *testing.T) { // return an empty, non-nil-shaped result rather than erroring. func TestDedupEmptyStoreNoPanic(t *testing.T) { dir := t.TempDir() - findings, err := Dedup(dir) + findings, err := Dedup(context.Background(), dir) require.NoError(t, err) assert.Empty(t, findings) } diff --git a/internal/cairn/doctor_test.go b/internal/cairn/doctor_test.go index 82970e04..b613561a 100644 --- a/internal/cairn/doctor_test.go +++ b/internal/cairn/doctor_test.go @@ -45,7 +45,7 @@ func TestScopeMismatchCleanWhenTagMatchesDir(t *testing.T) { dir := t.TempDir() writeFile(t, dir, "rig/alpha/r.md", "+++\nid = \"r\"\ntitle = \"r\"\nscope = [\"rig:alpha\"]\n+++\nx\n") - entries, failures, err := IterEntriesTolerant(dir) + entries, failures, err := IterEntriesTolerant(t.Context(), dir) require.NoError(t, err) require.Empty(t, failures) @@ -56,7 +56,7 @@ func TestScopeMismatchReportsWrongTag(t *testing.T) { dir := t.TempDir() writeFile(t, dir, "rig/alpha/r.md", "+++\nid = \"r\"\ntitle = \"r\"\nscope = [\"rig:beta\"]\n+++\nx\n") - entries, failures, err := IterEntriesTolerant(dir) + entries, failures, err := IterEntriesTolerant(t.Context(), dir) require.NoError(t, err) require.Empty(t, failures) @@ -72,7 +72,7 @@ func TestScopeMismatchExemptsGlobalTier(t *testing.T) { dir := t.TempDir() writeFile(t, dir, "global/g.md", "+++\nid = \"g\"\ntitle = \"g\"\nscope = [\"rig:anything\"]\n+++\nx\n") - entries, failures, err := IterEntriesTolerant(dir) + entries, failures, err := IterEntriesTolerant(t.Context(), dir) require.NoError(t, err) require.Empty(t, failures) @@ -174,7 +174,7 @@ func TestAgentFreshnessOnlyChecksAgentTier(t *testing.T) { writeFile(t, dir, "agent/bot/a.md", "+++\nid = \"a\"\ntitle = \"a\"\nscope = [\"agent:bot\"]\n+++\nx\n") writeFile(t, dir, "global/g.md", "+++\nid = \"g\"\ntitle = \"g\"\nscope = []\n+++\nx\n") - entries, failures, err := IterEntriesTolerant(dir) + entries, failures, err := IterEntriesTolerant(ctx, dir) require.NoError(t, err) require.Empty(t, failures) @@ -190,7 +190,7 @@ func TestIndexDriftCleanWhenIndexAlreadyFresh(t *testing.T) { dir := t.TempDir() writeFile(t, dir, "global/a.md", "+++\nid = \"a\"\ntitle = \"A\"\n+++\nbody\n") - entries, failures, err := IterEntriesTolerant(dir) + entries, failures, err := IterEntriesTolerant(ctx, dir) require.NoError(t, err) require.Empty(t, failures) @@ -215,7 +215,7 @@ func TestIndexDriftReportsStaleIndex(t *testing.T) { writeFile(t, dir, "global/b.md", "+++\nid = \"b\"\ntitle = \"B\"\n+++\nbody\n") gitCommitAll(t, dir, "add b") - entries, failures, err := IterEntriesTolerant(dir) + entries, failures, err := IterEntriesTolerant(ctx, dir) require.NoError(t, err) require.Empty(t, failures) @@ -411,7 +411,7 @@ func TestDiagnoseStatsCountsEntriesByTierAndReportsCleanIndex(t *testing.T) { writeFile(t, dir, "rig/alpha/r2.md", "+++\nid = \"r2\"\ntitle = \"r2\"\nscope = [\"rig:alpha\"]\n+++\nx\n") writeFile(t, dir, "role/investigator/o.md", "+++\nid = \"o\"\ntitle = \"o\"\nscope = [\"role:investigator\"]\n+++\nx\n") - entries, failures, err := IterEntriesTolerant(dir) + entries, failures, err := IterEntriesTolerant(ctx, dir) require.NoError(t, err) require.Empty(t, failures) _, err = ReindexEntries(ctx, dir, entries) @@ -460,9 +460,9 @@ func TestDiagnoseCallsIterEntriesTolerantAndIndexStaleExactlyOnce(t *testing.T) require.NoError(t, err) var iterCalls, staleCalls int - iter := func(store string) ([]*Entry, []ParseFailure, error) { + iter := func(ctx context.Context, store string) ([]*Entry, []ParseFailure, error) { iterCalls++ - return IterEntriesTolerant(store) + return IterEntriesTolerant(ctx, store) } staleFn := func(ctx context.Context, store string) (bool, error) { staleCalls++ diff --git a/internal/cairn/entry_test.go b/internal/cairn/entry_test.go index 8c343ff8..57ff0a24 100644 --- a/internal/cairn/entry_test.go +++ b/internal/cairn/entry_test.go @@ -83,7 +83,7 @@ func TestIterEntriesTolerantCleanStoreNoFailures(t *testing.T) { writeFile(t, dir, "global/g.md", sampleEntry) writeFile(t, dir, "rig/alpha/r.md", "+++\nid = \"r1\"\ntitle = \"r1\"\nscope = [\"rig:alpha\"]\n+++\nx\n") - entries, failures, err := IterEntriesTolerant(dir) + entries, failures, err := IterEntriesTolerant(t.Context(), dir) require.NoError(t, err) assert.Empty(t, failures) ids := map[string]bool{} @@ -98,7 +98,7 @@ func TestIterEntriesTolerantCollectsParseFailures(t *testing.T) { writeFile(t, dir, "global/good.md", sampleEntry) badPath := writeFile(t, dir, "global/bad.md", "+++\nid = \"a\"\nno closing fence\n") - entries, failures, err := IterEntriesTolerant(dir) + entries, failures, err := IterEntriesTolerant(t.Context(), dir) require.NoError(t, err, "a malformed entry must not abort the tolerant walk") ids := map[string]bool{} @@ -118,7 +118,7 @@ func TestIterEntriesStillAbortsOnParseFailure(t *testing.T) { writeFile(t, dir, "global/good.md", sampleEntry) writeFile(t, dir, "global/bad.md", "+++\nid = \"a\"\nno closing fence\n") - _, err := IterEntries(dir) + _, err := IterEntries(t.Context(), dir) require.Error(t, err, "IterEntries' existing abort-on-first-error contract must be unchanged") } @@ -427,12 +427,13 @@ func TestWriteBackMissingAnchorTableErrorsWithoutWriting(t *testing.T) { } func TestWriteBackRecurrenceCountRoundTrip(t *testing.T) { - p := writeFile(t, t.TempDir(), "global/one.md", sampleEntry) + store := t.TempDir() + p := writeFile(t, store, "global/one.md", sampleEntry) e, err := ParseEntry(p) require.NoError(t, err) e.RecurrenceCount = 5 - require.NoError(t, e.WriteBackRecurrenceCount()) + require.NoError(t, e.WriteBackRecurrenceCount(t.Context(), store)) e2, err := ParseEntry(p) require.NoError(t, err) @@ -466,7 +467,8 @@ body text // [anchor]-boundary-finding shape -- while every other original line // survives verbatim. func TestWriteBackRecurrenceCountFirstIncrementAppendsAndPreservesRest(t *testing.T) { - p := writeFile(t, t.TempDir(), "global/one.md", writeBackFixtureNoRecurrence) + store := t.TempDir() + p := writeFile(t, store, "global/one.md", writeBackFixtureNoRecurrence) before, err := os.ReadFile(p) require.NoError(t, err) @@ -475,7 +477,7 @@ func TestWriteBackRecurrenceCountFirstIncrementAppendsAndPreservesRest(t *testin require.Equal(t, 0, e.RecurrenceCount, "fixture must start with no recurrence_count") e.RecurrenceCount = 1 - require.NoError(t, e.WriteBackRecurrenceCount()) + require.NoError(t, e.WriteBackRecurrenceCount(t.Context(), store)) after, err := os.ReadFile(p) require.NoError(t, err) @@ -529,7 +531,8 @@ body text // must update in place with zero line-count delta, not grow the file or // reorder anything. func TestWriteBackRecurrenceCountSecondIncrementUpdatesInPlace(t *testing.T) { - p := writeFile(t, t.TempDir(), "global/one.md", writeBackFixtureRecurrenceAlreadySet) + store := t.TempDir() + p := writeFile(t, store, "global/one.md", writeBackFixtureRecurrenceAlreadySet) before, err := os.ReadFile(p) require.NoError(t, err) beforeLines := strings.Split(string(before), "\n") @@ -539,7 +542,7 @@ func TestWriteBackRecurrenceCountSecondIncrementUpdatesInPlace(t *testing.T) { require.Equal(t, 3, e.RecurrenceCount) e.RecurrenceCount = 4 - require.NoError(t, e.WriteBackRecurrenceCount()) + require.NoError(t, e.WriteBackRecurrenceCount(t.Context(), store)) after, err := os.ReadFile(p) require.NoError(t, err) @@ -562,7 +565,8 @@ func TestWriteBackRecurrenceCountSecondIncrementUpdatesInPlace(t *testing.T) { // same hard-failure path, so it must behave identically -- an error naming // the entry id, and the file left exactly as it was, never a partial write. func TestWriteBackRecurrenceCountMissingAnchorTableErrorsWithoutWriting(t *testing.T) { - p := writeFile(t, t.TempDir(), "global/one.md", writeBackFixtureNoAnchor) + store := t.TempDir() + p := writeFile(t, store, "global/one.md", writeBackFixtureNoAnchor) before, err := os.ReadFile(p) require.NoError(t, err) @@ -570,7 +574,7 @@ func TestWriteBackRecurrenceCountMissingAnchorTableErrorsWithoutWriting(t *testi require.NoError(t, err) e.RecurrenceCount = 1 - err = e.WriteBackRecurrenceCount() + err = e.WriteBackRecurrenceCount(t.Context(), store) require.Error(t, err) assert.Contains(t, err.Error(), e.ID, "the error must name the entry id") @@ -580,12 +584,13 @@ func TestWriteBackRecurrenceCountMissingAnchorTableErrorsWithoutWriting(t *testi } func TestWriteBackPromotedBeadIDRoundTrip(t *testing.T) { - p := writeFile(t, t.TempDir(), "global/one.md", sampleEntry) + store := t.TempDir() + p := writeFile(t, store, "global/one.md", sampleEntry) e, err := ParseEntry(p) require.NoError(t, err) e.PromotedBeadID = "crn-abcd" - require.NoError(t, e.WriteBackPromotedBeadID()) + require.NoError(t, e.WriteBackPromotedBeadID(t.Context(), store)) e2, err := ParseEntry(p) require.NoError(t, err) @@ -619,7 +624,8 @@ body text // via the same [anchor]-boundary-finding shape -- while every other original // line survives verbatim. func TestWriteBackPromotedBeadIDFirstSetAppendsAndPreservesRest(t *testing.T) { - p := writeFile(t, t.TempDir(), "global/one.md", writeBackFixtureNoPromotedBeadID) + store := t.TempDir() + p := writeFile(t, store, "global/one.md", writeBackFixtureNoPromotedBeadID) before, err := os.ReadFile(p) require.NoError(t, err) @@ -628,7 +634,7 @@ func TestWriteBackPromotedBeadIDFirstSetAppendsAndPreservesRest(t *testing.T) { require.Empty(t, e.PromotedBeadID, "fixture must start with no promoted_bead_id") e.PromotedBeadID = "crn-abcd" - require.NoError(t, e.WriteBackPromotedBeadID()) + require.NoError(t, e.WriteBackPromotedBeadID(t.Context(), store)) after, err := os.ReadFile(p) require.NoError(t, err) @@ -682,7 +688,8 @@ body text // already present must update in place with zero line-count delta, not grow // the file or reorder anything. func TestWriteBackPromotedBeadIDSecondSetUpdatesInPlace(t *testing.T) { - p := writeFile(t, t.TempDir(), "global/one.md", writeBackFixturePromotedBeadIDAlreadySet) + store := t.TempDir() + p := writeFile(t, store, "global/one.md", writeBackFixturePromotedBeadIDAlreadySet) before, err := os.ReadFile(p) require.NoError(t, err) beforeLines := strings.Split(string(before), "\n") @@ -692,7 +699,7 @@ func TestWriteBackPromotedBeadIDSecondSetUpdatesInPlace(t *testing.T) { require.Equal(t, "crn-old1", e.PromotedBeadID) e.PromotedBeadID = "crn-new2" - require.NoError(t, e.WriteBackPromotedBeadID()) + require.NoError(t, e.WriteBackPromotedBeadID(t.Context(), store)) after, err := os.ReadFile(p) require.NoError(t, err) @@ -716,7 +723,8 @@ func TestWriteBackPromotedBeadIDSecondSetUpdatesInPlace(t *testing.T) { // an error naming the entry id, and the file left exactly as it was, never a // partial write. func TestWriteBackPromotedBeadIDMissingAnchorTableErrorsWithoutWriting(t *testing.T) { - p := writeFile(t, t.TempDir(), "global/one.md", writeBackFixtureNoAnchor) + store := t.TempDir() + p := writeFile(t, store, "global/one.md", writeBackFixtureNoAnchor) before, err := os.ReadFile(p) require.NoError(t, err) @@ -724,7 +732,7 @@ func TestWriteBackPromotedBeadIDMissingAnchorTableErrorsWithoutWriting(t *testin require.NoError(t, err) e.PromotedBeadID = "crn-abcd" - err = e.WriteBackPromotedBeadID() + err = e.WriteBackPromotedBeadID(t.Context(), store) require.Error(t, err) assert.Contains(t, err.Error(), e.ID, "the error must name the entry id") @@ -1335,7 +1343,7 @@ func TestFindUsesIndexPointLookupNotWalk(t *testing.T) { // indexing would break a walk-based lookup: IterEntries propagates any // ParseEntry error that isn't errNotEntry. writeFile(t, store, "global/bad.md", "+++\nid = \"bad\nno closing fence\n") - _, err = IterEntries(store) + _, err = IterEntries(ctx, store) require.Error(t, err, "sanity check: the malformed sibling file must break a walk") // Find resolves "a" via the already-built index rather than re-walking -- @@ -1384,7 +1392,7 @@ func TestVisibleNeverReadsBodiesAfterIndexBuilt(t *testing.T) { // it really would break a body walk if it were, so the assertion below // is a real proof rather than a vacuous one. writeFile(t, dir, "global/broken.md", "+++\nid = \"broken\"\nno closing fence\n") - _, walkErr := IterEntries(dir) + _, walkErr := IterEntries(t.Context(), dir) require.Error(t, walkErr, "sanity check: the malformed sibling must actually break a body walk") vs2, err := Visible(t.Context(), dir, nil) @@ -1408,7 +1416,7 @@ func TestStatusNeverReadsBodiesAfterIndexBuilt(t *testing.T) { // it really would break a body walk if it were, so the assertion below // is a real proof rather than a vacuous one. writeFile(t, dir, "global/broken.md", "+++\nid = \"broken\"\nno closing fence\n") - _, walkErr := IterEntries(dir) + _, walkErr := IterEntries(t.Context(), dir) require.Error(t, walkErr, "sanity check: the malformed sibling must actually break a body walk") entries2, err := Status(t.Context(), dir) @@ -1578,10 +1586,112 @@ func TestIterEntriesWrapsParseFailureAsMalformedEntryError(t *testing.T) { dir := t.TempDir() bad := writeFile(t, dir, "global/broken.md", "+++\nid = \"broken\"\nno closing fence\n") - _, err := IterEntries(dir) + _, err := IterEntries(t.Context(), dir) require.Error(t, err) var malformed *MalformedEntryError require.True(t, errors.As(err, &malformed), "IterEntries' parse-failure error must be a *MalformedEntryError") assert.Equal(t, bad, malformed.Path, "MalformedEntryError.Path must name the offending file") } + +// TestIterEntriesIncludesEntriesFromMultiplePendingReviewBranches covers +// crn-evw98.2's exit_contract "multiple pending branches" bullet: +// reviewBranchEntries (entry.go) must enumerate every open remember/* +// branch, not just the first one ListReviewBranches happens to return, each +// stamped review_status=pending (crn-evw98.1). Neither entry ever lands on +// disk -- commitToReviewWorktree removes each one's untracked draft the +// moment fixtureBranch's CommitToReviewBranch call commits it -- so this +// also pins that IterEntries does not depend on the disk-walk half of +// walkEntries to find them at all. +func TestIterEntriesIncludesEntriesFromMultiplePendingReviewBranches(t *testing.T) { + store := reviewStore(t) + _, e1 := fixtureBranch(t, store, "topic-one", []string{"rig:web"}, "first pending note") + _, e2 := fixtureBranch(t, store, "topic-two", []string{"rig:web"}, "second pending note") + + entries, err := IterEntries(t.Context(), store) + require.NoError(t, err) + require.Len(t, entries, 2, "both pending review branches must be enumerated, not just one") + + byID := map[string]*Entry{} + for _, e := range entries { + byID[e.ID] = e + } + require.Contains(t, byID, e1.ID) + require.Contains(t, byID, e2.ID) + assert.Equal(t, ReviewStatusPending, byID[e1.ID].ReviewStatus) + assert.Equal(t, ReviewStatusPending, byID[e2.ID].ReviewStatus) +} + +// TestIterEntriesExcludesAlreadyMergedReviewBranchFromDoubleCounting covers +// crn-evw98.2's exit_contract "a branch whose entry was later merged (must +// not double-count)" bullet. MergeReviewBranch deletes remember/ once it +// merges it, but nothing enforces that as the only way a branch gets merged +// -- reviewBranchEntries relies entirely on ListReviewBranches' own +// isMergedInto exclusion (branches.go) to stay correct when a branch is +// merged (e.g. by a plain `git merge`) yet its ref lives on. Mirrors +// TestListReviewBranchesExcludesMergedBranches' technique: a real --no-ff +// merge, not MergeReviewBranch, so the ref survives its own merge. +func TestIterEntriesExcludesAlreadyMergedReviewBranchFromDoubleCounting(t *testing.T) { + ctx := t.Context() + store := reviewStore(t) + branch, e := fixtureBranch(t, store, "merged-topic", []string{"rig:web"}, "a note that gets merged") + + _, err := gitRun(ctx, store, "merge", "--no-ff", "-m", "merge review branch", branch) + require.NoError(t, err) + _, err = gitRun(ctx, store, "rev-parse", "--verify", branch) + require.NoError(t, err, "precondition: the branch ref must still exist after the merge, unlike MergeReviewBranch's own cleanup") + + entries, err := IterEntries(ctx, store) + require.NoError(t, err) + + count := 0 + for _, got := range entries { + if got.ID == e.ID { + count++ + } + } + assert.Equal(t, 1, count, "an entry whose review branch was merged (but not deleted) must be counted exactly once, not once from disk and again from the branch") +} + +// TestFindEntryByIDAndWriteBackReportOriginalErrorWhenReviewBranchAbandoned +// covers crn-evw98.2's exit_contract "a branch for an entry later +// closed/abandoned" bullet, for all four call sites reviewBranchContent +// backs: Find and EntryByID via parseEntryOrReviewBranch, and +// WriteBackRecurrenceCount and WriteBackPromotedBeadID via +// writeBackPatchedOrBranch. Deleting the review branch outright (as opposed +// to merging it) leaves no fallback content anywhere, so every one of the +// four must surface the same original os.IsNotExist-satisfying disk error +// each already returns when there was never a review branch at all -- not a +// new error shape, and specifically not ErrNotFound, since the index row +// (seeded here via an explicit Reindex before the branch is deleted) is +// still present; only the body content is gone. +func TestFindEntryByIDAndWriteBackReportOriginalErrorWhenReviewBranchAbandoned(t *testing.T) { + ctx := t.Context() + store := reviewStore(t) + branch, e := fixtureBranch(t, store, "rejected-topic", []string{"rig:web"}, "a note that gets rejected") + + _, err := Reindex(ctx, store) + require.NoError(t, err, "seed the index while the branch still exists, so the later lookups see a stale-but-present row rather than Find's own forced-reindex-and-retry changing the observed error shape") + + _, err = gitRun(ctx, store, "branch", "-D", branch) + require.NoError(t, err) + + _, err = Find(ctx, store, e.ID) + require.Error(t, err) + assert.False(t, errors.Is(err, ErrNotFound), "the index row still exists -- this must not look like an unindexed id") + assert.True(t, os.IsNotExist(err), "Find must surface the original not-exist error when no branch is left to fall back to: %v", err) + + _, err = EntryByID(ctx, store, e.ID) + require.Error(t, err) + assert.True(t, os.IsNotExist(err), "EntryByID shares parseEntryOrReviewBranch with Find and must behave identically: %v", err) + + e.RecurrenceCount = 1 + err = e.WriteBackRecurrenceCount(ctx, store) + require.Error(t, err) + assert.True(t, os.IsNotExist(err), "WriteBackRecurrenceCount must surface the original disk error, not synthesize a new one: %v", err) + + e.PromotedBeadID = "crn-abcd" + err = e.WriteBackPromotedBeadID(ctx, store) + require.Error(t, err) + assert.True(t, os.IsNotExist(err), "WriteBackPromotedBeadID must surface the original disk error, not synthesize a new one: %v", err) +} diff --git a/internal/cairn/index_test.go b/internal/cairn/index_test.go index 937351ae..5f49c2e4 100644 --- a/internal/cairn/index_test.go +++ b/internal/cairn/index_test.go @@ -67,7 +67,7 @@ func TestReindexEntriesBuildsIndexFromSuppliedList(t *testing.T) { body := "+++\nid = \"a\"\ntitle = \"A\"\ntopic_key = \"t/a\"\nscope = [\"rig:alpha\"]\n+++\nbody\n" require.NoError(t, os.WriteFile(filepath.Join(store, "global", "a.md"), []byte(body), 0o600)) - entries, failures, err := IterEntriesTolerant(store) + entries, failures, err := IterEntriesTolerant(ctx, store) require.NoError(t, err) require.Empty(t, failures) diff --git a/internal/cairn/relative_store_test.go b/internal/cairn/relative_store_test.go index b260a586..ff4e9b5c 100644 --- a/internal/cairn/relative_store_test.go +++ b/internal/cairn/relative_store_test.go @@ -29,7 +29,7 @@ func TestEntryTierResolvesFromARelativeStore(t *testing.T) { dir := t.TempDir() writeFile(t, dir, "rig/alpha/r1.md", relStoreEntryA) - entries, err := IterEntries(dir) + entries, err := IterEntries(t.Context(), dir) require.NoError(t, err) require.Len(t, entries, 1) @@ -37,7 +37,7 @@ func TestEntryTierResolvesFromARelativeStore(t *testing.T) { // Same store, named relatively from inside it. t.Chdir(dir) - relEntries, err := IterEntries(".") + relEntries, err := IterEntries(t.Context(), ".") require.NoError(t, err) require.Len(t, relEntries, 1) assert.Equal(t, "rig", entryTier(".", relEntries[0]), @@ -83,7 +83,7 @@ func TestDiagnoseFindsTheSameProblemsFromARelativeStore(t *testing.T) { func TestEntryTierRejectsAnEntryOutsideTheStore(t *testing.T) { dir := t.TempDir() writeFile(t, dir, "rig/alpha/r1.md", relStoreEntryA) - entries, err := IterEntries(dir) + entries, err := IterEntries(t.Context(), dir) require.NoError(t, err) assert.Equal(t, "", entryTier(filepath.Join(dir, "elsewhere"), entries[0])) diff --git a/internal/cairn/remember_test.go b/internal/cairn/remember_test.go index 8888afe1..47fc5574 100644 --- a/internal/cairn/remember_test.go +++ b/internal/cairn/remember_test.go @@ -679,7 +679,7 @@ func TestCommitRecurrenceToReviewBranchCreatesBranchWhenAbsent(t *testing.T) { require.NoError(t, err) require.NoError(t, e.Create(store)) e.RecurrenceCount = 1 - require.NoError(t, e.WriteBackRecurrenceCount()) + require.NoError(t, e.WriteBackRecurrenceCount(ctx, store)) branch, err := e.CommitRecurrenceToReviewBranch(ctx, store) require.NoError(t, err) @@ -711,29 +711,31 @@ func TestCommitRecurrenceToReviewBranchCreatesBranchWhenAbsent(t *testing.T) { assert.Len(t, strings.Split(strings.TrimSpace(worktrees), "\n"), 1, "the scratch review worktree must be cleaned up") } -// TestWriteBackRecurrenceCountFailsWhilePendingReview documents crn-rymq3's -// intentional cost, not an accident: the ordinary case (crn-28ge.1.4) is a -// recurrence hit landing while the entry's original review commit from -// CommitToReviewBranch is still pending on its remember/ branch -- a -// recurring topic tends to recur before anyone has reviewed the first -// report, not only after. commitToReviewWorktree's post-commit cleanup -// (crn-rymq3) now removes e.BodyPath from the store's working tree entirely -// once it's committed there for the first time (the untracked, -// never-merged case), because leaving it there is exactly what made `git -// merge remember/` refuse to merge later. WriteBackRecurrenceCount's -// read/patch/write cycle (writeBackPatched, entry.go) unconditionally reads -// e.BodyPath first, so it now has nothing left to read: a recurrence can no -// longer be persisted at all while the original is still pending review, -// not just left undetected by the caller one layer up (see +// TestWriteBackRecurrenceCountSucceedsViaReviewBranch documents crn-evw98's +// fix: the ordinary case (crn-28ge.1.4) is a recurrence hit landing while +// the entry's original review commit from CommitToReviewBranch is still +// pending on its remember/ branch -- a recurring topic tends to recur +// before anyone has reviewed the first report, not only after. +// commitToReviewWorktree's post-commit cleanup (crn-rymq3) removes +// e.BodyPath from the store's working tree entirely once it's committed +// there for the first time (the untracked, never-merged case), so +// WriteBackRecurrenceCount's read/patch/write cycle (writeBackPatched, +// entry.go) has nothing left to read on disk -- crn-evw98 gives it a +// fallback: read e's last-committed content from its own pending review +// branch instead (mirroring ShowReviewBranch's git-show pattern, +// internal/cairn/review.go), patch recurrence_count into that content, and +// write the patched result BACK to e.BodyPath, rematerializing the +// untracked file so CommitRecurrenceToReviewBranch's own plain +// os.ReadFile(e.BodyPath) right after this call succeeds unchanged -- see // cmd/remember_test.go's -// TestRememberCrossCallSharedTierRecurrenceNotDetectedWhilePendingReview, -// where recurrenceMatch itself never even finds the candidate to try). -// Follow-up: crn-evw98. The complementary case -- an already-merged entry -// recurring again -- is unaffected and still fully covered by +// TestRememberCrossCallSharedTierRecurrenceReusesReviewBranch, where +// recurrenceMatch itself finds the candidate via this same fix one layer +// up. The complementary case -- an already-merged entry recurring again -- +// is unaffected and still fully covered by // TestCommitRecurrenceToReviewBranchOnAlreadyMergedEntryRestoresWorkingTree // below: e.BodyPath is tracked and present there, just stale, so -// writeBackPatched's read succeeds. -func TestWriteBackRecurrenceCountFailsWhilePendingReview(t *testing.T) { +// writeBackPatched's read succeeds without ever reaching this fallback. +func TestWriteBackRecurrenceCountSucceedsViaReviewBranch(t *testing.T) { ctx := t.Context() store := t.TempDir() gitInit(t, store) @@ -744,14 +746,103 @@ func TestWriteBackRecurrenceCountFailsWhilePendingReview(t *testing.T) { require.NoError(t, err) require.NoError(t, e.Create(store)) - _, err = e.CommitToReviewBranch(ctx, store) + branch, err := e.CommitToReviewBranch(ctx, store) require.NoError(t, err) assert.NoFileExists(t, e.BodyPath, "precondition: the first commit's cleanup must have already removed the untracked working-tree copy (crn-rymq3)") + branchBefore, err := gitRun(ctx, store, "rev-parse", branch) + require.NoError(t, err) + + e.RecurrenceCount = 1 + err = e.WriteBackRecurrenceCount(ctx, store) + require.NoError(t, err, "a recurrence patch on a still-pending entry must succeed by reading the pending review branch, not fail loudly (crn-evw98)") + + restored, err := ParseEntry(e.BodyPath) + require.NoError(t, err, "the patched content must be rematerialized to e.BodyPath so CommitRecurrenceToReviewBranch's own os.ReadFile finds it unchanged") + assert.Equal(t, e.ID, restored.ID) + assert.Equal(t, 1, restored.RecurrenceCount) + + rel, err := filepath.Rel(store, e.BodyPath) + require.NoError(t, err) + status, err := gitRun(ctx, store, "status", "--porcelain", "--untracked-files=all") + require.NoError(t, err) + assert.Contains(t, status, "?? "+rel, "the rematerialized file must stay untracked, exactly the pre-state CommitRecurrenceToReviewBranch's commitToReviewWorktree already knows how to clean back up") + + branchAfter, err := gitRun(ctx, store, "rev-parse", branch) + require.NoError(t, err) + assert.Equal(t, strings.TrimSpace(branchBefore), strings.TrimSpace(branchAfter), "WriteBackRecurrenceCount only reads the review branch -- it must not itself add a commit to it") +} + +// TestCommitRecurrenceToReviewBranchAppendsSecondCommitToExistingBranch +// restores crn-rymq3's original ordinary-case coverage (crn-28ge.1.4), now +// that crn-evw98's review-branch fallback (see +// TestWriteBackRecurrenceCountSucceedsViaReviewBranch above) makes the whole +// WriteBackRecurrenceCount -> CommitRecurrenceToReviewBranch sequence +// succeed again while the entry's original review commit is still pending: a +// recurrence hit almost always lands before anyone has reviewed the first +// report, not only after. CommitRecurrenceToReviewBranch must append a +// second commit to that SAME branch rather than fail on "branch already +// exists" (what reusing CommitToReviewBranch as-is would do) or fork a +// competing one -- and, new to this restoration, the second commit's own +// commitToReviewWorktree cleanup must leave e.BodyPath removed again, not +// just after the first commit. +func TestCommitRecurrenceToReviewBranchAppendsSecondCommitToExistingBranch(t *testing.T) { + ctx := t.Context() + store := t.TempDir() + gitInit(t, store) + require.NoError(t, os.WriteFile(filepath.Join(store, "README.md"), []byte("seed\n"), 0o600)) + gitCommitAll(t, store, "seed") + + e, err := NewEntry(NewEntryParams{Type: EntryTypeKnowledge, TopicKey: "build-flags", Scope: []string{"rig:web"}, Body: "prefer feature flags over env vars", CreatedBy: "agent:bot"}) + require.NoError(t, err) + require.NoError(t, e.Create(store)) + + firstBranch, err := e.CommitToReviewBranch(ctx, store) + require.NoError(t, err) + firstCommit, err := gitRun(ctx, store, "rev-parse", firstBranch) + require.NoError(t, err) + firstCommit = strings.TrimSpace(firstCommit) + + branchBefore, err := gitRun(ctx, store, "branch", "--show-current") + require.NoError(t, err) + headBefore, err := gitRun(ctx, store, "rev-parse", "HEAD") + require.NoError(t, err) + headBefore = strings.TrimSpace(headBefore) e.RecurrenceCount = 1 - err = e.WriteBackRecurrenceCount() - require.Error(t, err, "a recurrence patch on a still-pending entry must fail loudly, not silently no-op or corrupt a neighboring file") - assert.True(t, os.IsNotExist(err), "the failure must be exactly the missing working-tree file, not some other error masking it: %v", err) + require.NoError(t, e.WriteBackRecurrenceCount(ctx, store)) + + branch, err := e.CommitRecurrenceToReviewBranch(ctx, store) + require.NoError(t, err) + assert.Equal(t, firstBranch, branch, "a recurrence commit must reuse the entry's existing review branch, not a new one") + + parent, err := gitRun(ctx, store, "rev-parse", branch+"~1") + require.NoError(t, err) + assert.Equal(t, firstCommit, strings.TrimSpace(parent), + "the recurrence commit must be appended on top of the original review commit, not replace or precede it, and must be the only new commit") + + msg, err := gitRun(ctx, store, "log", "-1", "--format=%B", branch) + require.NoError(t, err) + assert.Contains(t, msg, e.ID) + assert.Contains(t, msg, "recurrence") + assert.Contains(t, msg, "count 1") + + rel, err := filepath.Rel(store, e.BodyPath) + require.NoError(t, err) + status, err := gitRun(ctx, store, "status", "--porcelain", "--untracked-files=all") + require.NoError(t, err) + assert.NotContains(t, status, rel, "the second review commit's own commitToReviewWorktree cleanup must remove the rematerialized working-tree copy again, not just the first commit's") + + branchAfter, err := gitRun(ctx, store, "branch", "--show-current") + require.NoError(t, err) + assert.Equal(t, strings.TrimSpace(branchBefore), strings.TrimSpace(branchAfter), + "CommitRecurrenceToReviewBranch must not switch the store's checked-out branch") + headAfter, err := gitRun(ctx, store, "rev-parse", "HEAD") + require.NoError(t, err) + assert.Equal(t, headBefore, strings.TrimSpace(headAfter), "the store's own HEAD must be unaffected") + + worktrees, err := gitRun(ctx, store, "worktree", "list") + require.NoError(t, err) + assert.Len(t, strings.Split(strings.TrimSpace(worktrees), "\n"), 1, "the scratch review worktree must be cleaned up") } // TestCommitRecurrenceToReviewBranchOnAlreadyMergedEntryRestoresWorkingTree @@ -816,7 +907,7 @@ func TestCommitRecurrenceToReviewBranchOnAlreadyMergedEntryRestoresWorkingTree(t headBefore = strings.TrimSpace(headBefore) e.RecurrenceCount = 1 - require.NoError(t, e.WriteBackRecurrenceCount()) + require.NoError(t, e.WriteBackRecurrenceCount(ctx, store)) // Precondition: the patch left the tracked file modified, not untracked. status, err := gitRun(ctx, store, "status", "--porcelain") @@ -873,7 +964,7 @@ func TestCommitPromotionToReviewBranchCreatesBranchWhenAbsent(t *testing.T) { require.NoError(t, err) require.NoError(t, e.Create(store)) e.PromotedBeadID = "crn-abcd" - require.NoError(t, e.WriteBackPromotedBeadID()) + require.NoError(t, e.WriteBackPromotedBeadID(ctx, store)) branch, err := e.CommitPromotionToReviewBranch(ctx, store) require.NoError(t, err) @@ -905,16 +996,14 @@ func TestCommitPromotionToReviewBranchCreatesBranchWhenAbsent(t *testing.T) { assert.Len(t, strings.Split(strings.TrimSpace(worktrees), "\n"), 1, "the scratch review worktree must be cleaned up") } -// TestWriteBackPromotedBeadIDFailsWhilePendingReview mirrors -// TestWriteBackRecurrenceCountFailsWhilePendingReview one field over +// TestWriteBackPromotedBeadIDSucceedsViaReviewBranch mirrors +// TestWriteBackRecurrenceCountSucceedsViaReviewBranch one field over // (crn-ghn8.1 is promotion's counterpart to crn-28ge.1.4): a promotion // frequently lands while the entry's original review commit is still // pending on its remember/ branch, and WriteBackPromotedBeadID shares -// the same writeBackPatched read/patch/write cycle (entry.go), so it fails -// for the identical reason -- e.BodyPath was already removed from the -// store's working tree by commitToReviewWorktree's crn-rymq3 cleanup. -// Follow-up: crn-evw98. -func TestWriteBackPromotedBeadIDFailsWhilePendingReview(t *testing.T) { +// the same writeBackPatched read/patch/write cycle (entry.go) and the same +// crn-evw98 review-branch fallback, for the identical reason. +func TestWriteBackPromotedBeadIDSucceedsViaReviewBranch(t *testing.T) { ctx := t.Context() store := t.TempDir() gitInit(t, store) @@ -925,14 +1014,98 @@ func TestWriteBackPromotedBeadIDFailsWhilePendingReview(t *testing.T) { require.NoError(t, err) require.NoError(t, e.Create(store)) - _, err = e.CommitToReviewBranch(ctx, store) + branch, err := e.CommitToReviewBranch(ctx, store) require.NoError(t, err) assert.NoFileExists(t, e.BodyPath, "precondition: the first commit's cleanup must have already removed the untracked working-tree copy (crn-rymq3)") + branchBefore, err := gitRun(ctx, store, "rev-parse", branch) + require.NoError(t, err) + + e.PromotedBeadID = "crn-abcd" + err = e.WriteBackPromotedBeadID(ctx, store) + require.NoError(t, err, "a promotion patch on a still-pending entry must succeed by reading the pending review branch, not fail loudly (crn-evw98)") + + restored, err := ParseEntry(e.BodyPath) + require.NoError(t, err, "the patched content must be rematerialized to e.BodyPath so CommitPromotionToReviewBranch's own os.ReadFile finds it unchanged") + assert.Equal(t, e.ID, restored.ID) + assert.Equal(t, "crn-abcd", restored.PromotedBeadID) + + rel, err := filepath.Rel(store, e.BodyPath) + require.NoError(t, err) + status, err := gitRun(ctx, store, "status", "--porcelain", "--untracked-files=all") + require.NoError(t, err) + assert.Contains(t, status, "?? "+rel, "the rematerialized file must stay untracked, exactly the pre-state CommitPromotionToReviewBranch's commitToReviewWorktree already knows how to clean back up") + + branchAfter, err := gitRun(ctx, store, "rev-parse", branch) + require.NoError(t, err) + assert.Equal(t, strings.TrimSpace(branchBefore), strings.TrimSpace(branchAfter), "WriteBackPromotedBeadID only reads the review branch -- it must not itself add a commit to it") +} + +// TestCommitPromotionToReviewBranchAppendsSecondCommitToExistingBranch +// mirrors TestCommitRecurrenceToReviewBranchAppendsSecondCommitToExistingBranch +// one field over, restoring crn-rymq3's original promotion-side ordinary-case +// coverage (crn-28ge.1.4's sibling): a promotion frequently lands while the +// entry's original review commit is still pending, and +// CommitPromotionToReviewBranch must append a second commit to that SAME +// branch, with the second commit's own commitToReviewWorktree cleanup again +// removing the rematerialized e.BodyPath. +func TestCommitPromotionToReviewBranchAppendsSecondCommitToExistingBranch(t *testing.T) { + ctx := t.Context() + store := t.TempDir() + gitInit(t, store) + require.NoError(t, os.WriteFile(filepath.Join(store, "README.md"), []byte("seed\n"), 0o600)) + gitCommitAll(t, store, "seed") + + e, err := NewEntry(NewEntryParams{Type: EntryTypeKnowledge, TopicKey: "build-flags", Scope: []string{"rig:web"}, Body: "prefer feature flags over env vars", CreatedBy: "agent:bot"}) + require.NoError(t, err) + require.NoError(t, e.Create(store)) + + firstBranch, err := e.CommitToReviewBranch(ctx, store) + require.NoError(t, err) + firstCommit, err := gitRun(ctx, store, "rev-parse", firstBranch) + require.NoError(t, err) + firstCommit = strings.TrimSpace(firstCommit) + + branchBefore, err := gitRun(ctx, store, "branch", "--show-current") + require.NoError(t, err) + headBefore, err := gitRun(ctx, store, "rev-parse", "HEAD") + require.NoError(t, err) + headBefore = strings.TrimSpace(headBefore) e.PromotedBeadID = "crn-abcd" - err = e.WriteBackPromotedBeadID() - require.Error(t, err, "a promotion patch on a still-pending entry must fail loudly, not silently no-op or corrupt a neighboring file") - assert.True(t, os.IsNotExist(err), "the failure must be exactly the missing working-tree file, not some other error masking it: %v", err) + require.NoError(t, e.WriteBackPromotedBeadID(ctx, store)) + + branch, err := e.CommitPromotionToReviewBranch(ctx, store) + require.NoError(t, err) + assert.Equal(t, firstBranch, branch, "a promotion commit must reuse the entry's existing review branch, not a new one") + + parent, err := gitRun(ctx, store, "rev-parse", branch+"~1") + require.NoError(t, err) + assert.Equal(t, firstCommit, strings.TrimSpace(parent), + "the promotion commit must be appended on top of the original review commit, not replace or precede it, and must be the only new commit") + + msg, err := gitRun(ctx, store, "log", "-1", "--format=%B", branch) + require.NoError(t, err) + assert.Contains(t, msg, e.ID) + assert.Contains(t, msg, "promote") + assert.Contains(t, msg, "crn-abcd") + + rel, err := filepath.Rel(store, e.BodyPath) + require.NoError(t, err) + status, err := gitRun(ctx, store, "status", "--porcelain", "--untracked-files=all") + require.NoError(t, err) + assert.NotContains(t, status, rel, "the second review commit's own commitToReviewWorktree cleanup must remove the rematerialized working-tree copy again, not just the first commit's") + + branchAfter, err := gitRun(ctx, store, "branch", "--show-current") + require.NoError(t, err) + assert.Equal(t, strings.TrimSpace(branchBefore), strings.TrimSpace(branchAfter), + "CommitPromotionToReviewBranch must not switch the store's checked-out branch") + headAfter, err := gitRun(ctx, store, "rev-parse", "HEAD") + require.NoError(t, err) + assert.Equal(t, headBefore, strings.TrimSpace(headAfter), "the store's own HEAD must be unaffected") + + worktrees, err := gitRun(ctx, store, "worktree", "list") + require.NoError(t, err) + assert.Len(t, strings.Split(strings.TrimSpace(worktrees), "\n"), 1, "the scratch review worktree must be cleaned up") } func TestCommitDirectLogsWritePathAndSteps(t *testing.T) { @@ -1046,16 +1219,17 @@ func TestCommitToReviewBranchLogsWritePathAndSteps(t *testing.T) { // TestCommitRecurrenceAndPromotionLogDistinctOperationNames confirms the // write_path/write_path_step log records tag recurrence and promotion // commits with their own operation names, not a shared or blank one. Runs -// against an already-merged entry (not the ordinary pending-review case -// crn-28ge.1.4/crn-ghn8.1 usually land in) because WriteBackRecurrenceCount -// and WriteBackPromotedBeadID both require a tracked e.BodyPath to patch -// (writeBackPatched, entry.go) -- crn-rymq3 removes that file from the -// store's working tree entirely for as long as the review commit is still -// pending, so only the already-merged pre-state can reach either write-back -// call at all here (see TestWriteBackRecurrenceCountFailsWhilePendingReview -// and TestWriteBackPromotedBeadIDFailsWhilePendingReview above for the -// pending case itself). That choice is orthogonal to what this test -// actually verifies: operation-name tagging, not pending-vs-merged timing. +// against an already-merged entry rather than the ordinary still-pending +// case crn-28ge.1.4/crn-ghn8.1 usually land in -- since crn-evw98, +// WriteBackRecurrenceCount and WriteBackPromotedBeadID succeed either way +// (see TestWriteBackRecurrenceCountSucceedsViaReviewBranch and +// TestWriteBackPromotedBeadIDSucceedsViaReviewBranch above), so this is now +// a deliberate simplification rather than the only reachable pre-state: an +// already-merged entry's WriteBack* patches its tracked e.BodyPath directly +// (writeBackPatched, entry.go), without exercising the review-branch +// fallback at all, which keeps this test's own fixture setup minimal. That +// choice is orthogonal to what this test actually verifies: operation-name +// tagging, not pending-vs-merged timing. func TestCommitRecurrenceAndPromotionLogDistinctOperationNames(t *testing.T) { ctx := t.Context() store := t.TempDir() @@ -1077,7 +1251,7 @@ func TestCommitRecurrenceAndPromotionLogDistinctOperationNames(t *testing.T) { gitCommitAll(t, store, "simulate merge of "+branch) e.RecurrenceCount = 1 - require.NoError(t, e.WriteBackRecurrenceCount()) + require.NoError(t, e.WriteBackRecurrenceCount(ctx, store)) recurRecs := testLogRecords(t, func(ctx context.Context) { _, err := e.CommitRecurrenceToReviewBranch(ctx, store) require.NoError(t, err) @@ -1092,7 +1266,7 @@ func TestCommitRecurrenceAndPromotionLogDistinctOperationNames(t *testing.T) { } e.PromotedBeadID = "crn-abcd" - require.NoError(t, e.WriteBackPromotedBeadID()) + require.NoError(t, e.WriteBackPromotedBeadID(ctx, store)) promoRecs := testLogRecords(t, func(ctx context.Context) { _, err := e.CommitPromotionToReviewBranch(ctx, store) require.NoError(t, err) diff --git a/internal/cairn/review_status_test.go b/internal/cairn/review_status_test.go index 99a6f4d7..393c984c 100644 --- a/internal/cairn/review_status_test.go +++ b/internal/cairn/review_status_test.go @@ -80,7 +80,7 @@ func TestCommitPromotionToReviewBranchStampsPendingReviewStatus(t *testing.T) { require.NoError(t, err) require.NoError(t, e.Create(store)) e.PromotedBeadID = "crn-abcd" - require.NoError(t, e.WriteBackPromotedBeadID()) + require.NoError(t, e.WriteBackPromotedBeadID(ctx, store)) branch, err := e.CommitPromotionToReviewBranch(ctx, store) require.NoError(t, err) @@ -138,7 +138,7 @@ func TestCommitRecurrenceToReviewBranchOnAlreadyMergedEntryReflipsToPending(t *t gitCommitAll(t, store, "simulate merge of "+firstBranch) e.RecurrenceCount = 1 - require.NoError(t, e.WriteBackRecurrenceCount()) + require.NoError(t, e.WriteBackRecurrenceCount(ctx, store)) branch, err := e.CommitRecurrenceToReviewBranch(ctx, store) require.NoError(t, err) diff --git a/internal/cairn/sweep_test.go b/internal/cairn/sweep_test.go index 01a1ed27..dd899ab6 100644 --- a/internal/cairn/sweep_test.go +++ b/internal/cairn/sweep_test.go @@ -79,7 +79,7 @@ func TestSweepEntriesUsesSuppliedList(t *testing.T) { require.NotEmpty(t, fp) writeFile(t, dir, "global/fresh.md", filesEntry("fresh-1", repo, []string{"a.go"}, fp)) - entries, failures, err := IterEntriesTolerant(dir) + entries, failures, err := IterEntriesTolerant(ctx, dir) require.NoError(t, err) require.Empty(t, failures) diff --git a/internal/critic/freshness_test.go b/internal/critic/freshness_test.go index 0b0c74b6..d462fb58 100644 --- a/internal/critic/freshness_test.go +++ b/internal/critic/freshness_test.go @@ -29,7 +29,7 @@ func TestRunFreshnessScenarioCleansUpAfterItself(t *testing.T) { r := RunFreshnessScenario(t.Context(), store) require.Equal(t, Pass, r.Verdict, "detail: %s", r.Detail) - entries, err := cairn.IterEntries(store) + entries, err := cairn.IterEntries(t.Context(), store) require.NoError(t, err) assert.Empty(t, entries, "RunFreshnessScenario must leave no entries behind in the store after a passing run") } diff --git a/internal/critic/perf_test.go b/internal/critic/perf_test.go index 0041b96a..0d1b1364 100644 --- a/internal/critic/perf_test.go +++ b/internal/critic/perf_test.go @@ -33,7 +33,7 @@ func TestRunPerfScenarioCleansUpAfterItself(t *testing.T) { r := RunPerfScenario(t.Context(), store) require.NotEqual(t, Fail, r.Verdict, "detail: %s", r.Detail) - entries, err := cairn.IterEntries(store) + entries, err := cairn.IterEntries(t.Context(), store) require.NoError(t, err) assert.Empty(t, entries, "RunPerfScenario must leave no entries behind in the store after a run") } diff --git a/internal/critic/recall_test.go b/internal/critic/recall_test.go index 52c58f6a..002abc2f 100644 --- a/internal/critic/recall_test.go +++ b/internal/critic/recall_test.go @@ -30,7 +30,7 @@ func TestRunRecallScenarioCleansUpAfterItself(t *testing.T) { r := RunRecallScenario(t.Context(), store) require.Equal(t, Pass, r.Verdict, "detail: %s", r.Detail) - entries, err := cairn.IterEntries(store) + entries, err := cairn.IterEntries(t.Context(), store) require.NoError(t, err) assert.Empty(t, entries, "RunRecallScenario must leave no entries behind in the store after a passing run") } diff --git a/internal/critic/scope_precedence_test.go b/internal/critic/scope_precedence_test.go index ded6881a..2de5f55a 100644 --- a/internal/critic/scope_precedence_test.go +++ b/internal/critic/scope_precedence_test.go @@ -29,7 +29,7 @@ func TestRunScopePrecedenceScenarioCleansUpAfterItself(t *testing.T) { r := RunScopePrecedenceScenario(t.Context(), store) require.Equal(t, Pass, r.Verdict, "detail: %s", r.Detail) - entries, err := cairn.IterEntries(store) + entries, err := cairn.IterEntries(t.Context(), store) require.NoError(t, err) assert.Empty(t, entries, "RunScopePrecedenceScenario must leave no entries behind in the store after a passing run") } From 3df225ceca4a6358650849bf3365f623cae9099f Mon Sep 17 00:00:00 2001 From: cairn-reviewer-scratch Date: Wed, 19 Aug 2026 13:29:13 -0700 Subject: [PATCH 2/3] =?UTF-8?q?feat:=20green=20=E2=80=94=20Branch-aware=20?= =?UTF-8?q?discovery:=20Reindex/IterEntries=20read=20pending=20remember/*?= =?UTF-8?q?=20branches=20(refs=20crn-evw98.2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/backfill.go | 6 +- cmd/commands.go | 2 +- cmd/dedup.go | 2 +- cmd/promote.go | 2 +- cmd/rage.go | 2 +- cmd/remember.go | 4 +- cmd/remember_batch.go | 2 +- internal/cairn/dedup.go | 5 +- internal/cairn/doctor.go | 8 +- internal/cairn/entry.go | 279 +++++++++++++++++++++++++--- internal/cairn/evict.go | 2 +- internal/cairn/index.go | 2 +- internal/cairn/remember.go | 42 ++++- internal/cairn/sweep.go | 2 +- internal/critic/scope_precedence.go | 2 +- 15 files changed, 308 insertions(+), 54 deletions(-) diff --git a/cmd/backfill.go b/cmd/backfill.go index 38b2ebc9..62c838fd 100644 --- a/cmd/backfill.go +++ b/cmd/backfill.go @@ -62,7 +62,7 @@ func init() { var backfillExportCmd = &cobra.Command{ Use: "export", Short: "Emit unclassified entry work as JSONL", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { - records, counts, err := collectBackfill(storePath()) + records, counts, err := collectBackfill(cmd.Context(), storePath()) if err != nil { return err } @@ -148,8 +148,8 @@ var backfillApplyCmd = &cobra.Command{ }, } -func collectBackfill(store string) ([]backfillRecord, classificationCounts, error) { - entries, err := cairn.IterEntries(store) +func collectBackfill(ctx context.Context, store string) ([]backfillRecord, classificationCounts, error) { + entries, err := cairn.IterEntries(ctx, store) if err != nil { return nil, classificationCounts{}, err } diff --git a/cmd/commands.go b/cmd/commands.go index 87404d0d..3d948dda 100644 --- a/cmd/commands.go +++ b/cmd/commands.go @@ -193,7 +193,7 @@ var getCmd = &cobra.Command{ for _, v := range visible { visibleIDs[v.ID] = true } - all, err := cairn.IterEntries(storePath()) + all, err := cairn.IterEntries(cmd.Context(), storePath()) if err != nil { return emitError(cmd, err) } diff --git a/cmd/dedup.go b/cmd/dedup.go index b24ed6d2..98b77756 100644 --- a/cmd/dedup.go +++ b/cmd/dedup.go @@ -20,7 +20,7 @@ var dedupCmd = &cobra.Command{ return fmt.Errorf("dedup covers every shared-tier entry and does not filter by identity; " + "use 'cairn map' or 'cairn prime' for a scoped view") } - findings, err := cairn.Dedup(storePath()) + findings, err := cairn.Dedup(cmd.Context(), storePath()) if err != nil { return err } diff --git a/cmd/promote.go b/cmd/promote.go index 3d46eda8..9f9b758d 100644 --- a/cmd/promote.go +++ b/cmd/promote.go @@ -50,7 +50,7 @@ var promoteMarkCmd = &cobra.Command{ } e.PromotedBeadID = bead - if err := e.WriteBackPromotedBeadID(); err != nil { + if err := e.WriteBackPromotedBeadID(cmd.Context(), storePath()); err != nil { return fmt.Errorf("write promoted_bead_id for %s: %w", e.ID, err) } diff --git a/cmd/rage.go b/cmd/rage.go index 5a8f41aa..5f0b1fa1 100644 --- a/cmd/rage.go +++ b/cmd/rage.go @@ -157,7 +157,7 @@ func runRage(cmd *cobra.Command, _ []string) (int, error) { var entryBodies []RageEntryBody if includeBodies, _ := cmd.Flags().GetBool("include-bodies"); includeBodies { - entries, _, ierr := cairn.IterEntriesTolerant(storeP) + entries, _, ierr := cairn.IterEntriesTolerant(cmd.Context(), storeP) if ierr != nil { return 1, fmt.Errorf("read entry bodies: %w", ierr) } diff --git a/cmd/remember.go b/cmd/remember.go index db296a8d..a5982a75 100644 --- a/cmd/remember.go +++ b/cmd/remember.go @@ -395,7 +395,7 @@ func recurrenceMatch(cmd *cobra.Command, candidate *cairn.Entry) (matched *cairn for _, v := range visible { visibleIDs[v.ID] = true } - all, err := cairn.IterEntries(store) + all, err := cairn.IterEntries(cmd.Context(), store) if err != nil { return nil, false, fmt.Errorf("check for a recurring entry: %w", err) } @@ -470,7 +470,7 @@ func bestMatch(others []*cairn.Entry, topicMatch, contentMatch map[string]bool) // only the exit code must be told too, not just a human reading stdout. func recordRecurrence(cmd *cobra.Command, matched *cairn.Entry) error { matched.RecurrenceCount++ - if err := matched.WriteBackRecurrenceCount(); err != nil { + if err := matched.WriteBackRecurrenceCount(cmd.Context(), storePath()); err != nil { return emitError(cmd, fmt.Errorf("record recurrence for %s: %w", matched.ID, err)) } diff --git a/cmd/remember_batch.go b/cmd/remember_batch.go index 85310d39..62e7c83f 100644 --- a/cmd/remember_batch.go +++ b/cmd/remember_batch.go @@ -379,7 +379,7 @@ func commitBatchEntry(cmd *cobra.Command, e *cairn.Entry, scope []string, res *B // view. func recordBatchRecurrence(ctx context.Context, matched *cairn.Entry) error { matched.RecurrenceCount++ - if err := matched.WriteBackRecurrenceCount(); err != nil { + if err := matched.WriteBackRecurrenceCount(ctx, storePath()); err != nil { return fmt.Errorf("record recurrence for %s: %w", matched.ID, err) } diff --git a/internal/cairn/dedup.go b/internal/cairn/dedup.go index 20877539..2d62a55b 100644 --- a/internal/cairn/dedup.go +++ b/internal/cairn/dedup.go @@ -1,6 +1,7 @@ package cairn import ( + "context" "fmt" "regexp" "sort" @@ -62,8 +63,8 @@ const dedupSimilarityThreshold = 0.5 // concern, deferred to crn-0yv.5 and documented in // docs/plans/cairn-librarian-dedup-detection-beads.md, the same split // crn-0yv.2 established for freshness-drift beads. -func Dedup(store string) ([]DedupFinding, error) { - all, err := IterEntries(store) +func Dedup(ctx context.Context, store string) ([]DedupFinding, error) { + all, err := IterEntries(ctx, store) if err != nil { return nil, err } diff --git a/internal/cairn/doctor.go b/internal/cairn/doctor.go index ce410486..f2dc2110 100644 --- a/internal/cairn/doctor.go +++ b/internal/cairn/doctor.go @@ -84,10 +84,10 @@ func Diagnose(ctx context.Context, store string) (*Report, error) { func diagnose( ctx context.Context, store string, - iterEntriesTolerant func(string) ([]*Entry, []ParseFailure, error), + iterEntriesTolerant func(context.Context, string) ([]*Entry, []ParseFailure, error), indexStaleFn func(context.Context, string) (bool, error), ) (*Report, error) { - entries, failures, err := iterEntriesTolerant(store) + entries, failures, err := iterEntriesTolerant(ctx, store) if err != nil { return nil, err } @@ -439,7 +439,7 @@ type ExplainResult struct { // //nolint:revive // see doc comment: deliberate signature-consistency param func ExplainEntry(ctx context.Context, store, entryID string) (*ExplainResult, error) { - entries, _, err := IterEntriesTolerant(store) + entries, _, err := IterEntriesTolerant(ctx, store) if err != nil { return nil, err } @@ -508,7 +508,7 @@ type IdentityExplainResult struct { // //nolint:revive // see doc comment: deliberate signature-consistency param func ExplainForIdentity(ctx context.Context, store string, identity []string, topicKey string) (*IdentityExplainResult, error) { - entries, _, err := IterEntriesTolerant(store) + entries, _, err := IterEntriesTolerant(ctx, store) if err != nil { return nil, err } diff --git a/internal/cairn/entry.go b/internal/cairn/entry.go index 18ff9edb..9112d6c4 100644 --- a/internal/cairn/entry.go +++ b/internal/cairn/entry.go @@ -235,9 +235,12 @@ func patchTopLevelScalar(lines []string, key, value string) []string { // and calls this to persist it, without disturbing any other field a // curator or a prior WriteBack already wrote. As with WriteBack, // incrementing the field is the caller's responsibility; this only persists -// whatever value is already there. -func (e *Entry) WriteBackRecurrenceCount() error { - return e.writeBackPatched(func(front string) (string, error) { +// whatever value is already there. ctx/store are threaded through to +// writeBackPatchedOrBranch's still-pending-review branch fallback +// (crn-evw98.2): a recurrence on an entry whose first commit hasn't been +// reviewed yet finds no on-disk file to patch. +func (e *Entry) WriteBackRecurrenceCount(ctx context.Context, store string) error { + return e.writeBackPatchedOrBranch(ctx, store, func(front string) (string, error) { return patchRecurrenceCount(front, e.RecurrenceCount) }) } @@ -247,9 +250,11 @@ func (e *Entry) WriteBackRecurrenceCount() error { // WriteBack and WriteBackRecurrenceCount use. cmd/promote.go's promote-mark // command sets e.PromotedBeadID in memory and calls this to persist it, // without disturbing any other field a curator or a prior WriteBack already -// wrote. -func (e *Entry) WriteBackPromotedBeadID() error { - return e.writeBackPatched(func(front string) (string, error) { +// wrote. ctx/store are threaded through to writeBackPatchedOrBranch's +// still-pending-review branch fallback (crn-evw98.2), the same as +// WriteBackRecurrenceCount above. +func (e *Entry) WriteBackPromotedBeadID(ctx context.Context, store string) error { + return e.writeBackPatchedOrBranch(ctx, store, func(front string) (string, error) { return patchPromotedBeadID(front, e.PromotedBeadID) }) } @@ -264,16 +269,66 @@ func (e *Entry) WriteBackReviewStatus() error { } // writeBackPatched is the read/split/patch/reassemble/write shell shared by -// WriteBack, WriteBackRecurrenceCount, and WriteBackPromotedBeadID: read the -// on-disk file, split it into frontmatter and body, hand the frontmatter to -// patch, and write the merged result back. Every line patch itself doesn't -// touch survives byte-for-byte, matching WriteBack's own "surgical patch, -// not a full re-encode" contract. +// WriteBack, WriteBackAnchor, WriteBackRetrievalMetadata, WriteBackBackfill, +// and WriteBackReviewStatus: read the on-disk file, split it into +// frontmatter and body, hand the frontmatter to patch, and write the merged +// result back. Every line patch itself doesn't touch survives byte-for-byte, +// matching WriteBack's own "surgical patch, not a full re-encode" contract. +// +// WriteBackRecurrenceCount and WriteBackPromotedBeadID use +// writeBackPatchedOrBranch instead, not this: crn-evw98's still-pending- +// review gap (see reviewBranchContent) applies to exactly those two, per +// crn-evw98.2's exit_contract, and no other WriteBack* caller has been +// observed to need it. func (e *Entry) writeBackPatched(patch func(front string) (string, error)) error { raw, err := os.ReadFile(e.BodyPath) if err != nil { return err } + return e.applyPatchedFrontmatter(raw, patch) +} + +// writeBackPatchedOrBranch is writeBackPatched's counterpart for +// WriteBackRecurrenceCount and WriteBackPromotedBeadID. commitToReviewWorktree +// removes (or HEAD-restores) a shared-tier entry's on-disk copy the moment it +// is first committed to its remember/ review branch, so a recurrence or +// promotion write landing while that first commit is still pending review +// finds no on-disk file to patch, or a stale pre-recurrence one. On +// os.IsNotExist specifically, this reads the entry's last-committed content +// back from its own pending review branch (reviewBranchContent, the same +// git-show mechanism Find/EntryByID fall back to via parseEntryOrReviewBranch) +// instead, patches that, and -- critically -- writes the patched result back +// to e.BodyPath, rematerializing the untracked file so +// CommitRecurrenceToReviewBranch/CommitPromotionToReviewBranch's own plain +// os.ReadFile(e.BodyPath) right after this call finds it unchanged +// (crn-evw98.2). +func (e *Entry) writeBackPatchedOrBranch(ctx context.Context, store string, patch func(front string) (string, error)) error { + raw, err := os.ReadFile(e.BodyPath) + if err == nil { + return e.applyPatchedFrontmatter(raw, patch) + } + if !os.IsNotExist(err) { + return err + } + + relPath, rerr := storeRelPath(store, e.BodyPath) + if rerr != nil { + return err // the original disk-read error is more useful than a path-resolution one + } + branchRaw, _, ok, berr := reviewBranchContent(ctx, store, e.ID, relPath) + if berr != nil { + return berr + } + if !ok { + return err // no pending branch either -- surface the original disk error + } + return e.applyPatchedFrontmatter(branchRaw, patch) +} + +// applyPatchedFrontmatter is writeBackPatched/writeBackPatchedOrBranch's +// shared split/patch/reassemble/write tail, once raw content has been +// obtained from wherever (disk, or a pending review branch). +func (e *Entry) applyPatchedFrontmatter(raw []byte, patch func(front string) (string, error)) error { front, body, ok, err := splitFrontmatter(string(raw)) if err != nil { return fmt.Errorf("%s: %w", e.BodyPath, err) @@ -581,14 +636,19 @@ func (e *Entry) marshal() ([]byte, error) { return []byte(sb.String()), nil } -// walkEntries walks the scope dirs, parsing every .md file into an Entry. -// onParseErr is invoked for each file that fails to parse for a reason other -// than errNotEntry (which always just means "skip, not an entry"); returning -// the error aborts the walk (IterEntries' contract), while recording it and -// returning nil keeps going (IterEntriesTolerant's contract) -- the -// traversal itself is identical between the two, only the parse-failure -// policy differs. -func walkEntries(store string, onParseErr func(path string, err error) error) ([]*Entry, error) { +// walkEntries walks the scope dirs, parsing every .md file into an Entry, +// then folds in every entry still pending review on an open remember/ +// branch (reviewBranchEntries) -- crn-evw98's fix for the gap left by +// commitToReviewWorktree removing a shared-tier entry's on-disk copy the +// moment it's first committed for review (see mergeReviewBranchEntries for +// why a branch-sourced copy always wins over a same-ID disk one). onParseErr +// is invoked for each file -- or, now, each review branch -- that fails to +// parse for a reason other than errNotEntry (which always just means "skip, +// not an entry"); returning the error aborts the walk (IterEntries' +// contract), while recording it and returning nil keeps going +// (IterEntriesTolerant's contract) -- the traversal itself is identical +// between the two, only the parse-failure policy differs. +func walkEntries(ctx context.Context, store string, onParseErr func(path string, err error) error) ([]*Entry, error) { // Absolute-ise the store root before joining, so the BodyPath on every // entry -- and therefore every body_path the indexer records -- describes // the file independently of the cwd this walk ran from. Default store @@ -625,13 +685,115 @@ func walkEntries(store string, onParseErr func(path string, err error) error) ([ return nil, err } } + + branchEntries, err := reviewBranchEntries(ctx, store, onParseErr) + if err != nil { + return nil, err + } + out = mergeReviewBranchEntries(out, branchEntries) + sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID }) return out, nil } -// IterEntries walks the scope dirs and returns all entries, sorted by id. -func IterEntries(store string) ([]*Entry, error) { - return walkEntries(store, func(p string, err error) error { return &MalformedEntryError{Path: p, Err: err} }) +// reviewBranchEntries parses every remember/ branch still open (i.e. not +// yet merged -- ListReviewBranches' own isMergedInto filter) into an Entry, +// stamping ReviewStatus=pending on each. Tolerates store not being a git +// repo, or being one with no commits yet, the same way Reindex's own +// watermark read already does (index.go) -- neither IterEntries nor Reindex +// has ever required git, and this must not newly impose that requirement on +// every non-git store. A branch ListReviewBranches itself couldn't resolve +// (its own per-branch Error field) is routed through onParseErr exactly like +// a same-shaped on-disk parse failure, so a single malformed branch can never +// abort discovery of every other entry (crn-evw98). +func reviewBranchEntries(ctx context.Context, store string, onParseErr func(path string, err error) error) ([]*Entry, error) { + // Discards the error like index.go's indexed_at_commit stamp does, not + // just !ok: unlike indexStale (which must tell "confirmed non-git" apart + // from "invocation error" to avoid under-detecting staleness, crn-t250), + // a store that can't invoke git at all -- missing binary included, as + // TestSweepGitInvocationFailureIsIncomplete simulates -- could not have + // created a remember/* branch either, so there is no branch to miss. + if _, ok, _ := git(ctx, store, "rev-parse", "HEAD"); !ok { + return nil, nil + } + + branches, err := ListReviewBranches(ctx, store, time.Now()) + if err != nil { + return nil, err + } + + var out []*Entry + for _, b := range branches { + if b.Error != "" { + if perr := onParseErr(b.Name, errors.New(b.Error)); perr != nil { + return nil, perr + } + continue + } + source := b.Name + ":" + b.Path + raw, err := gitRun(ctx, store, "show", source) + if err != nil { + if perr := onParseErr(source, fmt.Errorf("read entry from review branch: %w", err)); perr != nil { + return nil, perr + } + continue + } + e, perr := parseEntryContent([]byte(raw), source) + if perr != nil { + if errors.Is(perr, errNotEntry) { + continue + } + if oerr := onParseErr(source, perr); oerr != nil { + return nil, oerr + } + continue + } + e.BodyPath = filepath.Join(store, b.Path) + e.ReviewStatus = ReviewStatusPending + out = append(out, e) + } + return out, nil +} + +// mergeReviewBranchEntries folds branchEntries into diskEntries, keyed by ID: +// a branch-sourced copy always wins over a same-ID disk copy. The two +// overlap in exactly the recurrence/promotion case (crn-evw98): an +// already-merged entry recurring again leaves a stale, HEAD-restored disk +// copy AND a fresh pending-branch copy with the same ID +// (commitToReviewWorktree's own cat-file/checkout-HEAD tail), and the branch +// copy is the one carrying the actually-current +// recurrence_count/promoted_bead_id -- writeBackPatchedOrBranch +// rematerializes it there first, before CommitRecurrenceToReviewBranch/ +// CommitPromotionToReviewBranch read and commit it. A branch already merged +// since ListReviewBranches ran can never appear in branchEntries at all +// (isMergedInto excludes it), so no dedup against an up-to-date disk copy is +// needed for that case. +func mergeReviewBranchEntries(diskEntries, branchEntries []*Entry) []*Entry { + if len(branchEntries) == 0 { + return diskEntries + } + byID := make(map[string]*Entry, len(diskEntries)) + out := make([]*Entry, 0, len(diskEntries)+len(branchEntries)) + for _, e := range diskEntries { + byID[e.ID] = e + out = append(out, e) + } + for _, be := range branchEntries { + if existing, ok := byID[be.ID]; ok { + *existing = *be + continue + } + byID[be.ID] = be + out = append(out, be) + } + return out +} + +// IterEntries walks the scope dirs and returns all entries, sorted by id -- +// including entries still pending review on an open remember/ branch +// (crn-evw98, see walkEntries). +func IterEntries(ctx context.Context, store string) ([]*Entry, error) { + return walkEntries(ctx, store, func(p string, err error) error { return &MalformedEntryError{Path: p, Err: err} }) } // ParseFailure records one file that failed to parse during a tolerant walk. @@ -641,13 +803,14 @@ type ParseFailure struct { } // IterEntriesTolerant walks the scope dirs the same way IterEntries does, -// but a malformed file never aborts the whole scan (FR-3/NFR-1): its path -// and error are appended to the returned failures instead. The error return -// is reserved for a genuine I/O failure on the store root itself (e.g. an -// unreadable directory), never a parse error. -func IterEntriesTolerant(store string) ([]*Entry, []ParseFailure, error) { +// but a malformed file -- or unreadable review branch -- never aborts the +// whole scan (FR-3/NFR-1): its path and error are appended to the returned +// failures instead. The error return is reserved for a genuine I/O failure on +// the store root itself (e.g. an unreadable directory) or a genuine git +// invocation failure, never a parse error. +func IterEntriesTolerant(ctx context.Context, store string) ([]*Entry, []ParseFailure, error) { var failures []ParseFailure - out, err := walkEntries(store, func(p string, perr error) error { + out, err := walkEntries(ctx, store, func(p string, perr error) error { failures = append(failures, ParseFailure{Path: p, Err: perr}) return nil }) @@ -690,7 +853,7 @@ func Find(ctx context.Context, store, id string) (*Entry, error) { return nil, err } - e, err := ParseEntry(resolveBodyPath(store, bodyPath)) + e, err := parseEntryOrReviewBranch(ctx, store, id, bodyPath) if err != nil { return nil, err } @@ -746,6 +909,64 @@ func resolveBodyPath(store, bodyPath string) string { return filepath.Join(store, bodyPath) } +// parseEntryOrReviewBranch parses the entry at bodyPath (store-relative or +// absolute, per resolveBodyPath), falling back to id's pending remember/ +// review branch content on os.IsNotExist -- see reviewBranchContent. Shared +// by Find and EntryByID: both resolve bodyPath via the same findBodyPath +// index lookup and hit the identical gap (crn-evw98) where the index still +// names a body file commitToReviewWorktree has already removed from disk +// because the entry is still pending review. +func parseEntryOrReviewBranch(ctx context.Context, store, id, bodyPath string) (*Entry, error) { + resolved := resolveBodyPath(store, bodyPath) + e, err := ParseEntry(resolved) + if err == nil { + return e, nil + } + if !os.IsNotExist(err) { + return nil, err + } + + relPath, rerr := storeRelPath(store, resolved) + if rerr != nil { + return nil, err // the original disk-read error is more useful than a path-resolution one + } + raw, branch, ok, berr := reviewBranchContent(ctx, store, id, relPath) + if berr != nil { + return nil, berr + } + if !ok { + return nil, err // no pending branch either -- the original ErrNotExist stands + } + be, perr := parseEntryContent(raw, branch+":"+relPath) + if perr != nil { + return nil, perr + } + be.BodyPath = resolved + be.ReviewStatus = ReviewStatusPending + return be, nil +} + +// storeRelPath resolves p (a body path as ParseEntry would open it) to a path +// relative to store's repo root -- the form every remember/ review branch +// commit uses (commitToReviewWorktree's own filepath.Rel(store, e.BodyPath)). +// Needed because resolveBodyPath's own output can be either absolute +// (walkEntries' current convention) or, for an index built by an older +// binary, still relative to whatever cwd built it (crn-o6mn). Both p and +// store are absolute-ized first so filepath.Rel always compares like with +// like, regardless of which convention produced p or what form the caller's +// own store string takes. +func storeRelPath(store, p string) (string, error) { + absStore, err := filepath.Abs(store) + if err != nil { + return "", err + } + absP, err := filepath.Abs(p) + if err != nil { + return "", err + } + return filepath.Rel(absStore, absP) +} + // Visible returns entries an identity may see: every scope-tag on the entry // must be satisfied by the identity (a subset match). Global (untagged) // entries are visible to all. When multiple visible entries share a diff --git a/internal/cairn/evict.go b/internal/cairn/evict.go index ded36c18..1eb6fbc5 100644 --- a/internal/cairn/evict.go +++ b/internal/cairn/evict.go @@ -29,7 +29,7 @@ func EntryByID(ctx context.Context, store, id string) (*Entry, error) { if err != nil { return nil, err } - return ParseEntry(resolveBodyPath(store, bodyPath)) + return parseEntryOrReviewBranch(ctx, store, id, bodyPath) } // EvictDirect deletes e's body file and commits that deletion straight to diff --git a/internal/cairn/index.go b/internal/cairn/index.go index 053a58ca..a2451dbe 100644 --- a/internal/cairn/index.go +++ b/internal/cairn/index.go @@ -144,7 +144,7 @@ func openDB(store string) (*sql.DB, error) { // Reindex rebuilds the index from the bodies. It returns the entry count. func Reindex(ctx context.Context, store string) (int, error) { - entries, err := IterEntries(store) + entries, err := IterEntries(ctx, store) if err != nil { return 0, err } diff --git a/internal/cairn/remember.go b/internal/cairn/remember.go index db5680db..3cf460ff 100644 --- a/internal/cairn/remember.go +++ b/internal/cairn/remember.go @@ -333,8 +333,12 @@ func (e *Entry) CommitDirect(ctx context.Context, store string) (string, error) // reviewBranchName is the git branch a shared-tier entry's review commit // lands on -- namespaced under remember/ and keyed by the entry's own ID, so // concurrent remember calls (even for the same topic_key) never collide. -func reviewBranchName(e *Entry) string { - return "remember/" + e.ID +// Takes a bare id, not an *Entry: reviewBranchContent's callers +// (Find/EntryByID/writeBackPatchedOrBranch, crn-evw98.2) only ever have an id +// in hand at the point they need this, an already-parsed entry being exactly +// what they're trying to obtain. +func reviewBranchName(id string) string { + return "remember/" + id } // CommitToReviewBranch commits e -- already written to store by Create -- @@ -347,7 +351,7 @@ func reviewBranchName(e *Entry) string { // worktree -- entirely separate from the store's HEAD, index, and working // tree -- cannot. Returns the branch name on success. func (e *Entry) CommitToReviewBranch(ctx context.Context, store string) (string, error) { - branch := reviewBranchName(e) + branch := reviewBranchName(e.ID) msg := fmt.Sprintf("remember: %s\n\nscope: %s", e.ID, strings.Join(e.Scope, " ")) if err := e.commitToReviewWorktree(ctx, store, branch, true, msg, "commit_to_review_branch"); err != nil { return "", err @@ -498,6 +502,34 @@ func reviewBranchExists(ctx context.Context, store, branch string) (bool, error) return false, fmt.Errorf("check for existing review branch %q: %w", branch, err) } +// reviewBranchContent reads id's last-committed content from its pending +// remember/ review branch (CommitToReviewBranch's namespace) at relPath, +// mirroring ShowReviewBranch's git-show pattern (review.go) -- a remember/* +// branch is never checked out anywhere, so `git show branch:relPath` is the +// only way to read it. relPath must be relative to store's repo root, the +// same convention commitToReviewWorktree committed it under +// (filepath.Rel(store, e.BodyPath)); storeRelPath (entry.go) derives it from +// a caller's own possibly-absolute BodyPath. ok is false, with raw, branch, +// and err all zero, when no remember/ branch exists at all -- callers +// should fall back to their own original disk-read error in that case, not +// synthesize a new one. A branch that exists but fails to read at relPath +// (corrupt ref, entry moved since) is a real error, not "no branch". +func reviewBranchContent(ctx context.Context, store, id, relPath string) (raw []byte, branch string, ok bool, err error) { + branch = reviewBranchName(id) + exists, err := reviewBranchExists(ctx, store, branch) + if err != nil { + return nil, "", false, err + } + if !exists { + return nil, "", false, nil + } + out, err := gitRun(ctx, store, "show", branch+":"+filepath.ToSlash(relPath)) + if err != nil { + return nil, "", false, fmt.Errorf("read %s from %s: %w", relPath, branch, err) + } + return []byte(out), branch, true, nil +} + // CommitRecurrenceToReviewBranch commits e -- an existing shared-tier entry // whose RecurrenceCount cmd/remember.go's capture-time recurrence path // (crn-28ge.1.4) just incremented in place -- onto its own remember/ @@ -511,7 +543,7 @@ func reviewBranchExists(ctx context.Context, store, branch string) (bool, error) // falling back to creating it fresh (identical to CommitToReviewBranch) // only when no such branch exists yet. func (e *Entry) CommitRecurrenceToReviewBranch(ctx context.Context, store string) (string, error) { - branch := reviewBranchName(e) + branch := reviewBranchName(e.ID) exists, err := reviewBranchExists(ctx, store, branch) if err != nil { return "", err @@ -533,7 +565,7 @@ func (e *Entry) CommitRecurrenceToReviewBranch(ctx context.Context, store string // branch -- appending a second commit to the same pending review -- falling // back to creating it fresh only when no such branch exists yet. func (e *Entry) CommitPromotionToReviewBranch(ctx context.Context, store string) (string, error) { - branch := reviewBranchName(e) + branch := reviewBranchName(e.ID) exists, err := reviewBranchExists(ctx, store, branch) if err != nil { return "", err diff --git a/internal/cairn/sweep.go b/internal/cairn/sweep.go index 8bb859f4..59b2e2d2 100644 --- a/internal/cairn/sweep.go +++ b/internal/cairn/sweep.go @@ -32,7 +32,7 @@ type SweepFinding struct { // detail with the specific untracked path(s), which Check's generic "not // verifiable" message can't name and which the eventual bd bead body needs. func Sweep(ctx context.Context, store string) ([]SweepFinding, error) { - entries, err := IterEntries(store) + entries, err := IterEntries(ctx, store) if err != nil { return nil, err } diff --git a/internal/critic/scope_precedence.go b/internal/critic/scope_precedence.go index b7872d96..adf588a8 100644 --- a/internal/critic/scope_precedence.go +++ b/internal/critic/scope_precedence.go @@ -174,7 +174,7 @@ func checkShadowMapSupersetSemantics(ctx context.Context, store, n string) Resul return NewResult(DimensionScopePrecedence, scopePrecedenceScenarioID, Fail, fmt.Sprintf("seed fixtures: %v", err)) } - all, err := cairn.IterEntries(store) + all, err := cairn.IterEntries(ctx, store) if err != nil { return NewResult(DimensionScopePrecedence, scopePrecedenceScenarioID, Fail, fmt.Sprintf("IterEntries: %v", err)) } From 381a578c215ed67f745e713c38908cd35142ec72 Mon Sep 17 00:00:00 2001 From: cairn-reviewer-scratch Date: Thu, 20 Aug 2026 00:42:04 -0700 Subject: [PATCH 3/3] =?UTF-8?q?deploy=20gate:=20crn-1elei=20=E2=80=94=207/?= =?UTF-8?q?7=20PASS?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Branch-aware discovery: Reindex/IterEntries read pending remember/* branches (feature bead crn-evw98.2, review bead crn-hy7ll re-review PASS). Deploy commit 3df225ceca4a6358650849bf3365f623cae9099f, cut from builder/crn-evw98.2-v3. Full evidence in release-gates/crn-1elei-gate.md. --- release-gates/crn-1elei-gate.md | 116 ++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 release-gates/crn-1elei-gate.md diff --git a/release-gates/crn-1elei-gate.md b/release-gates/crn-1elei-gate.md new file mode 100644 index 00000000..b02a010d --- /dev/null +++ b/release-gates/crn-1elei-gate.md @@ -0,0 +1,116 @@ +# Release Gate: crn-1elei + +**Deploy commit:** 3df225ceca4a6358650849bf3365f623cae9099f +**Source branch:** builder/crn-evw98.2-v3 +**Deploy-gate branch:** deploy/crn-1elei-gate +**Feature:** Branch-aware discovery: Reindex/IterEntries read pending remember/* branches +**Feature bead:** crn-evw98.2 (epic: crn-evw98) +**Review bead:** crn-hy7ll (verdict: pass, re-review) — original review crn-8co68 (verdict: pass) +**Evaluated:** 2026-08-20 by cairn/deployer + +Deploy bead crn-1elei is a freshly-minted deploy-tracking wrapper (per crn-hy7ll's own close +reason: "new standalone needs-deploy bead crn-1elei created ... and slung to cairn/deployer"). +It carries no commits of its own — the underlying commits cite crn-evw98.2, the actual feature +bead. This is expected and was confirmed at the commit-ancestry-scope check below, not assumed. + +## Evaluation order + +Criterion 6 evaluated first (cheap), per protocol. All others follow in numeric order. + +## Criterion 6 — Clean divergence from main: PASS + +`git merge-base --is-ancestor origin/main 3df225c` → true: the deploy commit already contains +the current origin/main tip (80020792e7812636bcf0b5eae9ba81748a989148) as an ancestor. No +rebase needed. Independently re-confirmed at gate-evaluation time — origin/main is unchanged +since the review's own check against the same SHA (review notes cite the identical origin/main +tip). + +## Criterion 1 — SHA integrity / review-deploy match: PASS + +Both SHAs resolved via `git rev-parse --verify --quiet "^{commit}"` before comparison, +not trusted as literal strings: +- Review verdict (crn-hy7ll notes, re-review section): `deploy_commit: 3df225ceca4a6358650849bf3365f623cae9099f`, `deploy_branch: builder/crn-evw98.2-v3` +- crn-1elei deploy commit: `3df225ceca4a6358650849bf3365f623cae9099f`, branch `builder/crn-evw98.2-v3` + +Exact match. + +## Criterion 2 — Acceptance criteria: PASS + +crn-evw98.2 exit_contract (per review notes, re-checked against this SHA): (1) branch-aware +discovery via git-show/ShowReviewBranch reuse, (2) 4 pinned test flips, (3) 3 new-coverage +scenarios, (4) dependency on crn-evw98.1 review_status stamping — satisfied. Independently +corroborated via diff review (see criterion 7): core logic concentrated in +internal/cairn/entry.go (+279/-) and internal/cairn/remember.go, consistent with the described +scope. + +## Criterion 3 — Tests pass: PASS + +Independently re-ran (not trusting the reviewer's claimed counts alone) from a fresh, isolated +scratch worktree (`/var/tmp/cairn-builder-crn-hy7ll.wk1`, clean, HEAD independently verified to +equal the deploy commit) with an isolated `GOLANGCI_LINT_CACHE`: + +- `go build ./...` → clean +- `go vet ./...` → clean +- `golangci-lint run ./...` → 0 issues +- `go test -race -count=1 ./...` → all 7 packages PASS, 0 FAIL: + +``` +ok github.com/quad341/cairn 1.022s +ok github.com/quad341/cairn/cmd 299.453s +ok github.com/quad341/cairn/formulas 1.062s +ok github.com/quad341/cairn/internal/cairn 180.699s +ok github.com/quad341/cairn/internal/critic 30.577s +ok github.com/quad341/cairn/internal/obslog 1.048s +ok github.com/quad341/cairn/scripts 5.262s +``` + +Matches the review's own more granular count (932 PASS / 0 FAIL / 0 SKIP, with the 9 +diff-owned tests individually re-verified by name under `-v -race`). + +## Criterion 4 — No open HIGH findings: PASS + +Searched for beads referencing crn-hy7ll / crn-evw98.2 / crn-1elei: only the parent +architecture epic (crn-evw98, open/hold:mayor — expected; incremental sub-features ship while +the epic stays open) and one incidental text match on an unrelated bead (crn-x81gk, distinct +branch/commit/molecule — builder/crn-rott9.3 — not this diff, confirmed by inspection). No +finding bead exists against this content. Review notes independently state +`security_findings: none` (mechanical extract-function refactor, no new trust boundary or +external input path; core feature logic byte-identical to crn-8co68's already-fully-walked +OWASP review). + +## Criterion 5 — Clean tree: PASS + +Own worktree was clean before starting. Verification scratch worktree was clean at the exact +deploy commit with no untracked cruft. Build succeeded (no missing files). + +## Criterion 7 — Single feature theme: PASS + +Verified two independent ways: + +1. **File-level:** `git diff --stat origin/main 3df225c` → 29 files changed, +754/-215, + entirely within `cmd/` and `internal/{cairn,critic}/`. Core logic in entry.go/remember.go; + the remainder is mechanical context-threading, per the review's own characterization. + `cmd/list.go` and `internal/cairn/prime.go` do **not** appear in the diff — confirms the + earlier squash-merge ancestry-conflict resolution (documented on crn-hy7ll) did not leak + scope; those two files remain byte-identical to origin/main. +2. **Commit-level:** `assert_deploy_ancestry_scope origin/main 3df225c crn-evw98.2` → PASS + (rc=0, via `packs/actual/deployer/scripts/rebase-resolve-lib.sh`, sourced by absolute path). + The only two commits unique to this deploy vs. origin/main both explicitly cite crn-evw98.2 + in their subject line (red/green pair for branch-aware discovery) — no foreign content. + +## Gate result: 7/7 PASS + +## Merge authority + +quad341/cairn — standing self-merge authorization applies (mayor ruling `gm-wisp-2yhv7u`, +2026-08-19 03:01:50; memory `cairn-auto-merge-requires-explicit-strategy`). This bead's own +description carries the older "cut isolated deploy branch, open PR, route merge-request to +mayor/mpr, no self-merge" boilerplate — per the ruling's explicit guidance this is a known +stale-copy artifact on quad341/cairn (a repo mpr does not cover) and is not treated as a fresh +signal to re-escalate. + +Proceeding: open PR from `deploy/crn-1elei-gate`, bounded CI check, then plain +`gh pr merge --squash` (never `--auto`) once CLEAN/MERGEABLE with both required checks +(`build-test`, `lint`) COMPLETED/SUCCESS, confirmed via a fresh `gh pr view --json` read taken +immediately before merging. Independently verify `state=MERGED` / `mergedAt` non-null +afterward — never trust a bare exit 0.