diff --git a/cmd/migrate.go b/cmd/migrate.go index 67680ca..21ca65f 100644 --- a/cmd/migrate.go +++ b/cmd/migrate.go @@ -133,7 +133,19 @@ func runMigrateApply(cmd *cobra.Command, dir, planPath string, dry bool) error { return fmt.Errorf("load bundle: %w", err) } out := cmd.OutOrStdout() + // A plan from before per-node hashes (or one edited by hand) still applies, + // but nothing can tell whether its nodes changed since phase 1; say so. + if unhashed := okf.UnhashedMigrateNodes(plan); len(unhashed) > 0 { + fmt.Fprintf(cmd.ErrOrStderr(), "warning: %d plan node(s) carry no sha256, so edits made since phase 1 cannot be detected for them; re-run phase 1 to add the check.\n", + len(unhashed)) + } + // The dry run makes every check the real apply makes before its first + // write, so a drifted plan fails here too rather than previewing edits + // that would be refused. if dry { + if err := okf.CheckMigratePlan(dir, plan); err != nil { + return err + } for _, nm := range plan.Nodes { if nm.Generated != nil { fmt.Fprintf(out, "would rewrite %s: timestamp -> generated { by: %s, at: %s }\n", diff --git a/cmd/migrate_hashcheck_test.go b/cmd/migrate_hashcheck_test.go new file mode 100644 index 0000000..6bff905 --- /dev/null +++ b/cmd/migrate_hashcheck_test.go @@ -0,0 +1,102 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cmd + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" +) + +// Positive control: a node edited between `migrate --plan` and `--apply` is +// refused by the real apply AND by its --dry-run, and the bundle is untouched. +func TestMigrate_ApplyRefusesNodeEditedSincePlan(t *testing.T) { + dir := mkPromoteCLIBundle(t, migrateFixtureFiles()) + planPath := filepath.Join(t.TempDir(), "migrate-plan.json") + if out, err := runOKF(t, "migrate", dir, "--plan", planPath, "--generated-by", "human:casey"); err != nil { + t.Fatalf("plan phase must exit 0: err=%v out=%q", err, out) + } + if !strings.Contains(readFileStr(t, planPath), `"sha256": "`) { + t.Fatalf("plan carries no per-node sha256:\n%s", readFileStr(t, planPath)) + } + a := filepath.Join(dir, "a.md") + if err := os.WriteFile(a, []byte(readFileStr(t, a)+"\nEdited after the plan.\n"), 0o644); err != nil { + t.Fatal(err) + } + before := cliTreeHash(t, dir) + + for _, args := range [][]string{ + {"migrate", dir, "--apply", "--plan", planPath, "--dry-run"}, + {"migrate", dir, "--apply", "--plan", planPath}, + } { + out, err := runOKF(t, args...) + if err == nil || !strings.Contains(err.Error(), "a.md") || !strings.Contains(err.Error(), "changed since the plan") { + t.Fatalf("%v: want a refusal naming a.md, got err=%v out=%q", args, err, out) + } + } + if after := cliTreeHash(t, dir); before != after { + t.Fatal("a refused migrate wrote to the bundle") + } +} + +// Negative control: a plan from before per-node hashes still applies, with a +// warning on stderr that its nodes could not be checked. +func TestMigrate_ApplyLegacyPlanWarnsAndApplies(t *testing.T) { + dir := mkPromoteCLIBundle(t, migrateFixtureFiles()) + planPath := filepath.Join(t.TempDir(), "migrate-plan.json") + if out, err := runOKF(t, "migrate", dir, "--plan", planPath, "--generated-by", "human:casey"); err != nil { + t.Fatalf("plan phase must exit 0: err=%v out=%q", err, out) + } + var plan map[string]any + if err := json.Unmarshal([]byte(readFileStr(t, planPath)), &plan); err != nil { + t.Fatal(err) + } + for _, n := range plan["nodes"].([]any) { + delete(n.(map[string]any), "sha256") + } + data, _ := json.Marshal(plan) + if err := os.WriteFile(planPath, data, 0o644); err != nil { + t.Fatal(err) + } + + _, stderr, err := runOKFSplit(t, "migrate", dir, "--apply", "--plan", planPath) + if err != nil { + t.Fatalf("a legacy plan must still apply: %v", err) + } + if !strings.Contains(stderr, "carry no sha256") { + t.Errorf("stderr lacks the unchecked-plan warning: %q", stderr) + } + if out, err := runOKF(t, "validate", dir); err != nil { + t.Fatalf("validate must pass after migrate: err=%v out=%q", err, out) + } +} + +// Negative control: a fresh plan applies without the legacy warning. +func TestMigrate_ApplyHashedPlanNoWarning(t *testing.T) { + dir := mkPromoteCLIBundle(t, migrateFixtureFiles()) + planPath := filepath.Join(t.TempDir(), "migrate-plan.json") + if out, err := runOKF(t, "migrate", dir, "--plan", planPath, "--generated-by", "human:casey"); err != nil { + t.Fatalf("plan phase must exit 0: err=%v out=%q", err, out) + } + _, stderr, err := runOKFSplit(t, "migrate", dir, "--apply", "--plan", planPath) + if err != nil { + t.Fatalf("apply must exit 0: %v", err) + } + if strings.Contains(stderr, "sha256") { + t.Errorf("a hashed plan printed the legacy warning: %q", stderr) + } +} diff --git a/internal/fsutil/tx.go b/internal/fsutil/tx.go new file mode 100644 index 0000000..2f4a4b7 --- /dev/null +++ b/internal/fsutil/tx.go @@ -0,0 +1,206 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package fsutil + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" +) + +// ErrChanged reports that a file a Tx would write or move no longer holds the +// bytes the caller planned against: someone edited it in between. +var ErrChanged = errors.New("file changed since the plan was made") + +// txRename and txMkdirAll are a Tx's directory-entry steps; variables only so +// a test can inject a failure part-way through a commit. +var ( + txRename = os.Rename + txMkdirAll = os.MkdirAll +) + +// SHA256Hex returns the lowercase hex SHA-256 of data. +func SHA256Hex(data []byte) string { + sum := sha256.Sum256(data) + return hex.EncodeToString(sum[:]) +} + +// Tx stages several file writes and renames and commits them as one unit: it +// checks every target against the hash the caller planned against before it +// writes anything, then applies the steps in order, and if a step fails it +// undoes the steps already applied, newest first, so the files end as they +// began. +// +// Each write is atomic on its own (WriteFileAtomic). The undo runs in-process +// from in-memory copies of the originals, so it covers a failed step, not a +// crash part-way through a commit. +type Tx struct { + steps []txStep +} + +type txStep struct { + write bool + path string // write target, or rename source + to string // rename destination + data []byte + perm os.FileMode + expect string // planned SHA-256 of path's current bytes; "" skips the check +} + +// Write stages writing data to path. expect is the SHA-256 (SHA256Hex) of the +// bytes the caller read and planned against; Commit refuses the whole Tx if +// path no longer hashes to it. An empty expect skips the check. +func (t *Tx) Write(path string, data []byte, perm os.FileMode, expect string) { + t.steps = append(t.steps, txStep{write: true, path: path, data: data, perm: perm, expect: expect}) +} + +// Rename stages moving from to to, creating to's missing parent directories. +// expect checks from's bytes as Write's does; to must not exist. +func (t *Tx) Rename(from, to, expect string) { + t.steps = append(t.steps, txStep{path: from, to: to, expect: expect}) +} + +// Commit checks every staged step, then applies them in order. A check +// failure writes nothing. An apply failure rolls back what was applied and +// returns the failure joined with any rollback error, so a rollback that could +// not finish is never silent. +func (t *Tx) Commit() error { + for _, s := range t.steps { + if err := s.check(); err != nil { + return err + } + } + var undo []func() error + for _, s := range t.steps { + // Check again right before the step: the window between the + // up-front pass and this write is where a concurrent edit would land. + u, err := s.apply() + if err != nil { + return errors.Join(err, rollback(undo)) + } + undo = append(undo, u...) + } + return nil +} + +func (s txStep) check() error { + if s.expect != "" { + data, err := os.ReadFile(s.path) //nolint:gosec // G304: the caller's own staged target + if err != nil { + return fmt.Errorf("check %s: %w", s.path, err) + } + if SHA256Hex(data) != s.expect { + return fmt.Errorf("%s: %w", s.path, ErrChanged) + } + } + if !s.write { + if _, err := os.Lstat(s.to); err == nil { + return fmt.Errorf("destination already exists: %s", s.to) + } else if !errors.Is(err, fs.ErrNotExist) { + return fmt.Errorf("stat %s: %w", s.to, err) + } + } + return nil +} + +// apply runs one step after re-checking it, and returns the closures that +// undo it. +func (s txStep) apply() ([]func() error, error) { + if err := s.check(); err != nil { + return nil, err + } + if s.write { + return s.applyWrite() + } + return s.applyRename() +} + +func (s txStep) applyWrite() ([]func() error, error) { + orig, err := os.ReadFile(s.path) //nolint:gosec // G304: the caller's own staged target + existed := err == nil + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return nil, fmt.Errorf("read %s: %w", s.path, err) + } + if err := WriteFileAtomic(s.path, s.data, s.perm); err != nil { + return nil, err + } + path := s.path + if !existed { + return []func() error{func() error { return os.Remove(path) }}, nil + } + // WriteFileAtomic keeps the existing file's mode, so restoring the bytes + // restores the file. + return []func() error{func() error { return WriteFileAtomic(path, orig, 0o644) }}, nil //nolint:gosec // G306: the mode is kept from the existing file, perm is unused +} + +func (s txStep) applyRename() ([]func() error, error) { + var undo []func() error + // Record the parents that do not exist yet, outermost first, so the undo + // can remove exactly the directories this step created. + var created []string + for d := filepath.Dir(s.to); ; d = filepath.Dir(d) { + if _, err := os.Lstat(d); err == nil { + break + } + created = append([]string{d}, created...) + if filepath.Dir(d) == d { + break + } + } + // Bundle directories hold shareable knowledge documents; 0o755 is intended. + if err := txMkdirAll(filepath.Dir(s.to), 0o755); err != nil { //nolint:gosec // G301: shareable bundle content dir + return nil, errors.Join(fmt.Errorf("mkdir for %s: %w", s.to, err), removeDirs(created)) + } + if len(created) > 0 { + undo = append(undo, func() error { return removeDirs(created) }) + } + if err := txRename(s.path, s.to); err != nil { + return nil, errors.Join(fmt.Errorf("move %s -> %s: %w", s.path, s.to, err), rollback(undo)) + } + from, to := s.path, s.to + undo = append(undo, func() error { return os.Rename(to, from) }) + return undo, nil +} + +// removeDirs removes dirs innermost first; os.Remove refuses a directory that +// is not empty, so nothing that holds another file is ever deleted. +func removeDirs(dirs []string) error { + var errs []error + for i := len(dirs) - 1; i >= 0; i-- { + if err := os.Remove(dirs[i]); err != nil && !errors.Is(err, fs.ErrNotExist) { + errs = append(errs, err) + } + } + return errors.Join(errs...) +} + +// rollback runs undo newest first and joins every failure, wrapped so the +// caller can tell a failed step from a failed restore. +func rollback(undo []func() error) error { + var errs []error + for i := len(undo) - 1; i >= 0; i-- { + if err := undo[i](); err != nil { + errs = append(errs, err) + } + } + if len(errs) == 0 { + return nil + } + return fmt.Errorf("rollback incomplete: %w", errors.Join(errs...)) +} diff --git a/internal/fsutil/tx_test.go b/internal/fsutil/tx_test.go new file mode 100644 index 0000000..661d8bc --- /dev/null +++ b/internal/fsutil/tx_test.go @@ -0,0 +1,197 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package fsutil + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +func writeTx(t *testing.T, dir, name, content string) (string, string) { + t.Helper() + p := filepath.Join(dir, name) + if err := os.WriteFile(p, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + return p, SHA256Hex([]byte(content)) +} + +func readTx(t *testing.T, p string) string { + t.Helper() + b, err := os.ReadFile(p) //nolint:gosec // G304: test temp file + if err != nil { + t.Fatal(err) + } + return string(b) +} + +// Negative control: an untouched set of files commits every write and the +// rename, exactly as staged. +func TestTx_CommitsWhenNothingChanged(t *testing.T) { + dir := t.TempDir() + a, ha := writeTx(t, dir, "a.md", "A") + b, hb := writeTx(t, dir, "b.md", "B") + m, hm := writeTx(t, dir, "m.md", "M") + to := filepath.Join(dir, "new", "deep", "m.md") + + var tx Tx + tx.Write(a, []byte("A2"), 0o644, ha) + tx.Write(b, []byte("B2"), 0o644, hb) + tx.Rename(m, to, hm) + if err := tx.Commit(); err != nil { + t.Fatalf("Commit: %v", err) + } + if readTx(t, a) != "A2" || readTx(t, b) != "B2" || readTx(t, to) != "M" { + t.Fatal("staged steps not all applied") + } + if _, err := os.Stat(m); !os.IsNotExist(err) { + t.Fatalf("rename source still present: %v", err) + } + noTemps(t, dir) +} + +// Positive control: a target edited after the plan refuses the whole Tx before +// any write, and the error names the changed file. +func TestTx_RefusesDriftBeforeAnyWrite(t *testing.T) { + dir := t.TempDir() + a, ha := writeTx(t, dir, "a.md", "A") + b, hb := writeTx(t, dir, "b.md", "B") + if err := os.WriteFile(b, []byte("B edited"), 0o644); err != nil { + t.Fatal(err) + } + + var tx Tx + tx.Write(a, []byte("A2"), 0o644, ha) + tx.Write(b, []byte("B2"), 0o644, hb) + err := tx.Commit() + if !errors.Is(err, ErrChanged) { + t.Fatalf("err = %v, want ErrChanged", err) + } + if got := err.Error(); !strings.Contains(got, b) { + t.Fatalf("error %q does not name %s", got, b) + } + if readTx(t, a) != "A" || readTx(t, b) != "B edited" { + t.Fatal("a refused Tx wrote a file") + } +} + +// Positive control: a rename that fails after two writes landed restores both +// writes byte-for-byte and leaves the source where it was. +func TestTx_RollsBackWritesWhenRenameFails(t *testing.T) { + dir := t.TempDir() + a, ha := writeTx(t, dir, "a.md", "A") + b, hb := writeTx(t, dir, "b.md", "B") + m, hm := writeTx(t, dir, "m.md", "M") + to := filepath.Join(dir, "new", "m.md") + txRename = func(string, string) error { return errors.New("disk on fire") } + t.Cleanup(func() { txRename = os.Rename }) + + var tx Tx + tx.Write(a, []byte("A2"), 0o644, ha) + tx.Write(b, []byte("B2"), 0o644, hb) + tx.Rename(m, to, hm) + err := tx.Commit() + if err == nil || !strings.Contains(err.Error(), "disk on fire") { + t.Fatalf("err = %v, want the injected failure", err) + } + if readTx(t, a) != "A" || readTx(t, b) != "B" || readTx(t, m) != "M" { + t.Fatal("rollback left a file changed") + } + if _, err := os.Stat(filepath.Join(dir, "new")); !os.IsNotExist(err) { + t.Fatalf("rollback left the created directory: %v", err) + } + noTemps(t, dir) +} + +// Positive control: a failed directory creation rolls back the writes before it. +func TestTx_RollsBackWritesWhenMkdirFails(t *testing.T) { + dir := t.TempDir() + a, ha := writeTx(t, dir, "a.md", "A") + m, hm := writeTx(t, dir, "m.md", "M") + txMkdirAll = func(string, os.FileMode) error { return errors.New("no space") } + t.Cleanup(func() { txMkdirAll = os.MkdirAll }) + + var tx Tx + tx.Write(a, []byte("A2"), 0o644, ha) + tx.Rename(m, filepath.Join(dir, "new", "m.md"), hm) + if err := tx.Commit(); err == nil { + t.Fatal("expected the injected failure") + } + if readTx(t, a) != "A" || readTx(t, m) != "M" { + t.Fatal("rollback left a file changed") + } +} + +// A write that creates a new file is undone by removing it. +func TestTx_RollbackRemovesCreatedFile(t *testing.T) { + dir := t.TempDir() + created := filepath.Join(dir, "created.md") + m, hm := writeTx(t, dir, "m.md", "M") + txRename = func(string, string) error { return errors.New("disk on fire") } + t.Cleanup(func() { txRename = os.Rename }) + + var tx Tx + tx.Write(created, []byte("new"), 0o644, "") + tx.Rename(m, filepath.Join(dir, "m2.md"), hm) + if err := tx.Commit(); err == nil { + t.Fatal("expected the injected failure") + } + if _, err := os.Stat(created); !os.IsNotExist(err) { + t.Fatalf("rollback left the created file: %v", err) + } +} + +// Negative control: an existing directory that the rename did not create is +// never removed by a rollback, even when it ends up empty. +func TestTx_RollbackKeepsPreexistingDir(t *testing.T) { + dir := t.TempDir() + keep := filepath.Join(dir, "keep") + if err := os.Mkdir(keep, 0o755); err != nil { + t.Fatal(err) + } + m, hm := writeTx(t, dir, "m.md", "M") + txRename = func(string, string) error { return errors.New("disk on fire") } + t.Cleanup(func() { txRename = os.Rename }) + + var tx Tx + tx.Rename(m, filepath.Join(keep, "m.md"), hm) + if err := tx.Commit(); err == nil { + t.Fatal("expected the injected failure") + } + if _, err := os.Stat(keep); err != nil { + t.Fatalf("rollback removed a directory it did not create: %v", err) + } +} + +// A rename onto an existing file is refused before anything is written. +func TestTx_RefusesExistingRenameDestination(t *testing.T) { + dir := t.TempDir() + a, ha := writeTx(t, dir, "a.md", "A") + m, hm := writeTx(t, dir, "m.md", "M") + taken, _ := writeTx(t, dir, "taken.md", "T") + + var tx Tx + tx.Write(a, []byte("A2"), 0o644, ha) + tx.Rename(m, taken, hm) + if err := tx.Commit(); err == nil { + t.Fatal("expected a refusal") + } + if readTx(t, a) != "A" || readTx(t, taken) != "T" { + t.Fatal("a refused Tx wrote a file") + } +} diff --git a/internal/okf/authoring.go b/internal/okf/authoring.go index 701b62e..724e018 100644 --- a/internal/okf/authoring.go +++ b/internal/okf/authoring.go @@ -19,6 +19,7 @@ import ( "os" "path/filepath" "strings" + "unicode" "github.com/cwest/okfctl/internal/fsutil" "gopkg.in/yaml.v3" @@ -67,10 +68,15 @@ func NewNodeFromTemplate(root, relPath, typ, title string, t Template) (string, fm := &yaml.Node{Kind: yaml.MappingNode} appendKV := func(key, val string) { - fm.Content = append(fm.Content, - &yaml.Node{Kind: yaml.ScalarNode, Value: key}, - &yaml.Node{Kind: yaml.ScalarNode, Value: val}, - ) + v := &yaml.Node{Kind: yaml.ScalarNode, Value: val} + // yaml.v3 writes a multi-line value as a literal block, and a block + // whose first line starts with a tab does not parse back. Double quotes + // escape every control character, so such a value round-trips; any + // other value keeps the plain style. + if strings.IndexFunc(val, unicode.IsControl) >= 0 { + v.Style = yaml.DoubleQuotedStyle + } + fm.Content = append(fm.Content, &yaml.Node{Kind: yaml.ScalarNode, Value: key}, v) } appendKV("type", typ) if strings.TrimSpace(title) != "" { diff --git a/internal/okf/bundle.go b/internal/okf/bundle.go index 3e8e720..ba016e3 100644 --- a/internal/okf/bundle.go +++ b/internal/okf/bundle.go @@ -22,6 +22,8 @@ import ( "regexp" "sort" "strings" + + "github.com/cwest/okfctl/internal/fsutil" ) // ReservedFiles are the reserved base names that are not concept nodes. A file @@ -168,11 +170,11 @@ func Load(root string, opts ...LoadOption) (*Bundle, error) { if ferr != nil { // Preserve the node with nil frontmatter so validate can report it. // A malformed block was physically present, so record that. - n := &Node{Path: rel, Frontmatter: nil, Body: string(src), HasFrontmatterBlock: true} + n := &Node{Path: rel, Frontmatter: nil, Body: string(src), HasFrontmatterBlock: true, SHA256: fsutil.SHA256Hex(src)} b.place(rel, n) return nil } - n := &Node{Path: rel, Frontmatter: fm, Body: body, HasFrontmatterBlock: present} + n := &Node{Path: rel, Frontmatter: fm, Body: body, HasFrontmatterBlock: present, SHA256: fsutil.SHA256Hex(src)} b.place(rel, n) return nil }) diff --git a/internal/okf/hashcheck_test.go b/internal/okf/hashcheck_test.go new file mode 100644 index 0000000..efb8e4d --- /dev/null +++ b/internal/okf/hashcheck_test.go @@ -0,0 +1,296 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package okf + +import ( + "errors" + "io/fs" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/cwest/okfctl/internal/fsutil" +) + +// snapshotTree returns every file under root keyed by slash path, so a test +// can prove a refused or failed write left the tree byte-identical. +func snapshotTree(t *testing.T, root string) map[string]string { + t.Helper() + out := map[string]string{} + err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() { + return err + } + data, err := os.ReadFile(p) //nolint:gosec // G304: test-owned temp tree + if err != nil { + return err + } + rel, _ := filepath.Rel(root, p) + out[filepath.ToSlash(rel)] = string(data) + return nil + }) + if err != nil { + t.Fatal(err) + } + return out +} + +func assertTreeUnchanged(t *testing.T, root string, before map[string]string) { + t.Helper() + if after := snapshotTree(t, root); !reflect.DeepEqual(before, after) { + t.Fatalf("tree changed:\nbefore %v\nafter %v", before, after) + } +} + +// ---- node mv ---------------------------------------------------------------- + +func moveFixture(t *testing.T) (string, *Bundle) { + return mkMoveBundle(t, map[string]string{ + "a.md": nodeSrc("A") + "See [x](wine/foo.md).\n", + "b.md": nodeSrc("B") + "And [y](wine/foo.md).\n", + "wine/c.md": nodeSrc("C") + "Near [z](foo.md).\n", + "wine/foo.md": nodeSrc("Foo"), + }) +} + +// Positive control: a linking node edited after the load refuses the move +// before any rewrite lands, and the error names the edited node. +func TestApplyMove_RefusesLinkerEditedSinceLoad(t *testing.T) { + root, b := moveFixture(t) + rw, err := PlanMove(b, "wine/foo.md", "cellar/foo.md") + if err != nil { + t.Fatal(err) + } + writeTestFile(t, root, "wine/c.md", nodeSrc("C")+"Near [z](foo.md). Edited.\n") + before := snapshotTree(t, root) + + err = ApplyMove(root, b, "wine/foo.md", "cellar/foo.md", rw) + if !errors.Is(err, fsutil.ErrChanged) || !strings.Contains(err.Error(), "wine/c.md") { + t.Fatalf("err = %v, want ErrChanged naming wine/c.md", err) + } + assertTreeUnchanged(t, root, before) +} + +// Positive control: the moved node itself edited after the load is refused too. +func TestApplyMove_RefusesMovedNodeEditedSinceLoad(t *testing.T) { + root, b := moveFixture(t) + rw, err := PlanMove(b, "wine/foo.md", "cellar/foo.md") + if err != nil { + t.Fatal(err) + } + writeTestFile(t, root, "wine/foo.md", nodeSrc("Foo")+"New paragraph.\n") + before := snapshotTree(t, root) + + if err := ApplyMove(root, b, "wine/foo.md", "cellar/foo.md", rw); !errors.Is(err, fsutil.ErrChanged) { + t.Fatalf("err = %v, want ErrChanged", err) + } + assertTreeUnchanged(t, root, before) +} + +// Positive control: a move whose destination directory cannot be created +// leaves every inbound link and the node exactly as they were. Before the +// transaction, on Windows the rewrites landed first and stayed when the +// directory step failed, leaving links to a node that never moved. +func TestApplyMove_FailedDirectoryLeavesTreeUnchanged(t *testing.T) { + root, b := moveFixture(t) + writeTestFile(t, root, "blocker", "a file where a directory is needed\n") + rw, err := PlanMove(b, "wine/foo.md", "blocker/foo.md") + if err != nil { + t.Fatal(err) + } + before := snapshotTree(t, root) + + if err := ApplyMove(root, b, "wine/foo.md", "blocker/foo.md", rw); err == nil { + t.Fatal("expected the move to fail") + } + assertTreeUnchanged(t, root, before) +} + +// Negative control: an untouched bundle moves and rewrites every link exactly +// as before the hash check existed. +func TestApplyMove_UnchangedBundleStillMoves(t *testing.T) { + root, b := moveFixture(t) + rw, err := PlanMove(b, "wine/foo.md", "cellar/foo.md") + if err != nil { + t.Fatal(err) + } + if err := ApplyMove(root, b, "wine/foo.md", "cellar/foo.md", rw); err != nil { + t.Fatalf("ApplyMove: %v", err) + } + if got := readBody(t, root, "a.md"); !strings.Contains(got, "(cellar/foo.md)") { + t.Errorf("a.md not rewritten: %q", got) + } + if got := readBody(t, root, "b.md"); !strings.Contains(got, "(cellar/foo.md)") { + t.Errorf("b.md not rewritten: %q", got) + } + if got := readBody(t, root, "wine/c.md"); !strings.Contains(got, "(../cellar/foo.md)") { + t.Errorf("wine/c.md not rewritten: %q", got) + } + if _, err := os.Stat(filepath.Join(root, "cellar", "foo.md")); err != nil { + t.Fatalf("node not moved: %v", err) + } +} + +// Negative control: a node built in memory carries no hash, and the move is +// not refused for want of one. +func TestApplyMove_InMemoryNodeSkipsHashCheck(t *testing.T) { + root, b := moveFixture(t) + for _, n := range b.Nodes { + n.SHA256 = "" + } + rw, err := PlanMove(b, "wine/foo.md", "cellar/foo.md") + if err != nil { + t.Fatal(err) + } + if err := ApplyMove(root, b, "wine/foo.md", "cellar/foo.md", rw); err != nil { + t.Fatalf("ApplyMove: %v", err) + } +} + +// ---- migrate --apply ---------------------------------------------------------- + +func legacyMigrateFixture(t *testing.T) string { + node := func(title string) string { + return "---\ntype: Concept\ntitle: " + title + "\ntimestamp: '2026-05-28T22:53:05+00:00'\n---\n\n# " + title + "\n" + } + return mkMigrateBundle(t, map[string]string{ + ".okf": "okf_version: 0.1\n", + "index.md": "---\nokf_version: \"0.1\"\n---\n\n# KB\n", + "log.md": "# Log\n", + "a.md": node("A"), + "b.md": node("B"), + "c.md": node("C"), + }) +} + +// §13.1 migration plans carry the hash of each node they were computed from. +func TestMigratePlan_RecordsNodeHashes(t *testing.T) { + dir := legacyMigrateFixture(t) + plan, err := PlanMigration(loadMigrate(t, dir), "casey") + if err != nil { + t.Fatal(err) + } + if len(plan.Nodes) != 3 { + t.Fatalf("plan nodes = %d, want 3", len(plan.Nodes)) + } + for _, nm := range plan.Nodes { + raw, _ := os.ReadFile(filepath.Join(dir, nm.Path)) + if nm.SHA256 != fsutil.SHA256Hex(raw) { + t.Errorf("%s: plan sha256 %q does not match the file", nm.Path, nm.SHA256) + } + } + if got := UnhashedMigrateNodes(plan); len(got) != 0 { + t.Errorf("UnhashedMigrateNodes = %v, want none", got) + } +} + +// Positive control: a node edited between phase 1 and --apply refuses the whole +// plan before any write, markers included, and the error names the node. +func TestMigrateApply_RefusesNodeEditedSincePlan(t *testing.T) { + dir := legacyMigrateFixture(t) + b := loadMigrate(t, dir) + plan, err := PlanMigration(b, "casey") + if err != nil { + t.Fatal(err) + } + writeTestFile(t, dir, "c.md", "---\ntype: Concept\ntitle: C\ntimestamp: '2026-05-28T22:53:05+00:00'\n---\n\n# C\n\nEdited.\n") + before := snapshotTree(t, dir) + + err = MigrateApply(dir, b, plan) + if !errors.Is(err, fsutil.ErrChanged) || !strings.Contains(err.Error(), "c.md") { + t.Fatalf("err = %v, want ErrChanged naming c.md", err) + } + if err := CheckMigratePlan(dir, plan); !errors.Is(err, fsutil.ErrChanged) { + t.Fatalf("CheckMigratePlan err = %v, want ErrChanged", err) + } + assertTreeUnchanged(t, dir, before) +} + +// Positive control: a plan that fails on its LAST node writes none of the +// earlier ones. Before the transaction, a.md and b.md were rewritten and the +// failure on c.md left the bundle half-migrated. +func TestMigrateApply_LateFailureWritesNothing(t *testing.T) { + dir := legacyMigrateFixture(t) + b := loadMigrate(t, dir) + plan, err := PlanMigration(b, "casey") + if err != nil { + t.Fatal(err) + } + if err := os.Remove(filepath.Join(dir, "c.md")); err != nil { + t.Fatal(err) + } + before := snapshotTree(t, dir) + + if err := MigrateApply(dir, b, plan); err == nil { + t.Fatal("expected the apply to fail on the missing node") + } + assertTreeUnchanged(t, dir, before) +} + +// Negative control: a plan written before per-node hashes existed still +// applies, and is reported as unchecked. +func TestMigrateApply_LegacyPlanWithoutHashesApplies(t *testing.T) { + dir := legacyMigrateFixture(t) + b := loadMigrate(t, dir) + plan, err := PlanMigration(b, "casey") + if err != nil { + t.Fatal(err) + } + for i := range plan.Nodes { + plan.Nodes[i].SHA256 = "" + } + if got := UnhashedMigrateNodes(plan); len(got) != 3 { + t.Fatalf("UnhashedMigrateNodes = %v, want all 3", got) + } + if err := MigrateApply(dir, b, plan); err != nil { + t.Fatalf("MigrateApply: %v", err) + } + b2 := loadMigrate(t, dir) + if b2.OkfVersion != "0.2" { + t.Errorf("okf_version = %q, want 0.2", b2.OkfVersion) + } + if f := Validate(b2); len(f) != 0 { + t.Errorf("validate after migrate: %+v", f) + } +} + +// Negative control: an untouched bundle migrates to a valid v0.2 bundle with +// the hash check in place. +func TestMigrateApply_UnchangedBundleMigrates(t *testing.T) { + dir := legacyMigrateFixture(t) + b := loadMigrate(t, dir) + plan, err := PlanMigration(b, "casey") + if err != nil { + t.Fatal(err) + } + if err := CheckMigratePlan(dir, plan); err != nil { + t.Fatalf("CheckMigratePlan: %v", err) + } + if err := MigrateApply(dir, b, plan); err != nil { + t.Fatalf("MigrateApply: %v", err) + } + b2 := loadMigrate(t, dir) + if b2.OkfVersion != "0.2" { + t.Errorf("okf_version = %q, want 0.2", b2.OkfVersion) + } + if f := Validate(b2); len(f) != 0 { + t.Errorf("validate after migrate: %+v", f) + } + if raw, _ := os.ReadFile(filepath.Join(dir, ".okf")); string(raw) != "okf_version: 0.2\n" { + t.Errorf(".okf = %q", raw) + } +} diff --git a/internal/okf/migrate.go b/internal/okf/migrate.go index 748491c..9a09b8b 100644 --- a/internal/okf/migrate.go +++ b/internal/okf/migrate.go @@ -16,6 +16,7 @@ package okf import ( "bytes" + "errors" "fmt" "os" "path/filepath" @@ -93,6 +94,10 @@ type NodeMigration struct { Path string `json:"path"` Generated *GeneratedEdit `json:"generated,omitempty"` Sources []SourceEdit `json:"sources,omitempty"` + // SHA256 is the hex SHA-256 of the node file the plan was computed from. + // --apply refuses the whole plan when the file no longer matches it. A + // plan written before this field existed has none, and applies unchecked. + SHA256 string `json:"sha256,omitempty"` } // MigratePlan is the full, JSON-serializable migration plan: the deterministic @@ -127,7 +132,7 @@ func PlanMigration(b *Bundle, generatedBy string) (MigratePlan, error) { if n.Frontmatter == nil { continue // unparseable frontmatter is a different failure class } - nm := NodeMigration{Path: rel} + nm := NodeMigration{Path: rel, SHA256: n.SHA256} // §13.1: timestamp -> generated { by, at }. Only when generated is not // already present (idempotence) and a legacy timestamp exists. @@ -247,17 +252,57 @@ func migrateTimeString(v any) string { // MigrateApply applies a plan's deterministic edits to disk, order-preserving // and additive-only. root is the bundle root; b is the loaded bundle the plan -// was computed against. It writes each edited node in place, then bumps the -// version markers (.okf sidecar and bundle-root index.md). It never touches a -// judgment item — those stay for the plan's consumer. +// was computed against. It renders every edited node and the version markers +// (.okf sidecar and bundle-root index.md) first, then writes them as one +// transaction: a node whose bytes no longer match the plan's sha256 refuses the +// whole plan before any write, and a failure part-way restores every file +// already written. It never touches a judgment item — those stay for the +// plan's consumer. func MigrateApply(root string, b *Bundle, plan MigratePlan) error { + tx, err := stageMigration(root, plan) + if err != nil { + return err + } + if err := tx.Commit(); err != nil { + if errors.Is(err, fsutil.ErrChanged) { + return fmt.Errorf("migrate: %w; nothing was written (re-run phase 1 to plan against the current files)", err) + } + return fmt.Errorf("migrate: %w", err) + } + return nil +} + +// CheckMigratePlan reports, without writing, whether plan still applies to the +// bundle at root: every check MigrateApply makes before its first write. A +// --dry-run runs it so a preview fails exactly where the real apply would. +func CheckMigratePlan(root string, plan MigratePlan) error { + _, err := stageMigration(root, plan) + return err +} + +// UnhashedMigrateNodes returns the plan nodes that carry no sha256 (a plan +// written before the field existed, or edited by hand), which --apply cannot +// check for drift. +func UnhashedMigrateNodes(plan MigratePlan) []string { + var out []string + for _, nm := range plan.Nodes { + if nm.SHA256 == "" { + out = append(out, nm.Path) + } + } + return out +} + +// stageMigration validates plan against the files at root and renders every +// write into a transaction, writing nothing. +func stageMigration(root string, plan MigratePlan) (*fsutil.Tx, error) { // The plan is a JSON file the user (or an agent) may have edited between // phases, so nothing in it is trusted. Validate it whole before any write. // §12: the .okf sidecar is line-keyed, so a line break in the target would // write a second, forged key into it. for _, r := range plan.TargetVersion { if r < 0x20 || r == 0x7f { - return fmt.Errorf("migrate plan target_version %q contains a control character", plan.TargetVersion) + return nil, fmt.Errorf("migrate plan target_version %q contains a control character", plan.TargetVersion) } } // §3: every node the plan names must live inside the bundle root. @@ -265,28 +310,37 @@ func MigrateApply(root string, b *Bundle, plan MigratePlan) error { for i, nm := range plan.Nodes { abs, err := fsutil.ResolveInRoot(root, nm.Path) if err != nil { - return fmt.Errorf("migrate plan node %s: %w", nm.Path, err) + return nil, fmt.Errorf("migrate plan node %s: %w", nm.Path, err) } abss[i] = abs } + tx := &fsutil.Tx{} for i, nm := range plan.Nodes { abs := abss[i] raw, err := os.ReadFile(abs) //nolint:gosec // G304: reading a node from the user's own bundle if err != nil { - return fmt.Errorf("read %s: %w", nm.Path, err) + return nil, fmt.Errorf("read %s: %w", nm.Path, err) + } + // The plan's edits were computed from the file it hashed; applied to + // any other bytes they could drop or duplicate what changed since. + if nm.SHA256 != "" && fsutil.SHA256Hex(raw) != nm.SHA256 { + return nil, fmt.Errorf("migrate plan node %s: %w; nothing was written (re-run phase 1 to plan against the current files)", nm.Path, fsutil.ErrChanged) } out, err := renderMigratedNode(raw, nm) if err != nil { - return fmt.Errorf("migrate %s: %w", nm.Path, err) + return nil, fmt.Errorf("migrate %s: %w", nm.Path, err) } if bytes.Equal(out, raw) { continue } - if err := fsutil.WriteFileAtomic(abs, out, 0o644); err != nil { //nolint:gosec // G306: a bundle node is a shareable knowledge document; 0o644 is intended - return fmt.Errorf("write %s: %w", nm.Path, err) - } + // Expect the bytes just read, so an edit between this read and the + // commit is refused too. + tx.Write(abs, out, 0o644, fsutil.SHA256Hex(raw)) //nolint:gosec // G306: a bundle node is a shareable knowledge document; 0o644 is intended + } + if err := stageVersionMarkers(tx, root, plan.TargetVersion); err != nil { + return nil, err } - return bumpVersionMarkers(root, plan.TargetVersion) + return tx, nil } // renderMigratedNode returns the node file bytes with the planned deterministic @@ -475,20 +529,20 @@ func citationResource(item string) (string, bool) { return "", false } -// bumpVersionMarkers sets the bundle's declared version to target in both the -// .okf sidecar (§12) and the bundle-root index.md okf_version marker (§8/§12 — -// the only place index frontmatter is permitted). Each is a no-op when already -// at target (idempotence) or absent. -func bumpVersionMarkers(root, target string) error { - if err := bumpOkfSidecar(root, target); err != nil { +// stageVersionMarkers stages setting the bundle's declared version to target +// in both the .okf sidecar (§12) and the bundle-root index.md okf_version +// marker (§8/§12 — the only place index frontmatter is permitted). Each is a +// no-op when already at target (idempotence) or absent. +func stageVersionMarkers(tx *fsutil.Tx, root, target string) error { + if err := stageOkfSidecar(tx, root, target); err != nil { return err } - return bumpRootIndexMarker(root, target) + return stageRootIndexMarker(tx, root, target) } -// bumpOkfSidecar rewrites the okf_version line of the .okf sidecar to target, -// preserving every other line. Absent sidecar is a no-op. -func bumpOkfSidecar(root, target string) error { +// stageOkfSidecar stages rewriting the okf_version line of the .okf sidecar to +// target, preserving every other line. Absent sidecar is a no-op. +func stageOkfSidecar(tx *fsutil.Tx, root, target string) error { abs := filepath.Join(root, ".okf") data, err := os.ReadFile(abs) //nolint:gosec // G304: reading the user's own bundle .okf sidecar if err != nil { @@ -512,13 +566,14 @@ func bumpOkfSidecar(root, target string) error { if !changed { return nil } - return fsutil.WriteFileAtomic(abs, []byte(strings.Join(lines, "\n")), 0o644) //nolint:gosec // G306: the .okf sidecar is a shareable bundle artifact; 0o644 is intended + tx.Write(abs, []byte(strings.Join(lines, "\n")), 0o644, fsutil.SHA256Hex(data)) //nolint:gosec // G306: the .okf sidecar is a shareable bundle artifact; 0o644 is intended + return nil } -// bumpRootIndexMarker rewrites the bundle-root index.md okf_version marker to -// target, order-preserving and body-verbatim. Absent index or absent marker is -// a no-op — this never invents a marker where the author had none. -func bumpRootIndexMarker(root, target string) error { +// stageRootIndexMarker stages rewriting the bundle-root index.md okf_version +// marker to target, order-preserving and body-verbatim. Absent index or absent +// marker is a no-op — this never invents a marker where the author had none. +func stageRootIndexMarker(tx *fsutil.Tx, root, target string) error { abs := filepath.Join(root, "index.md") raw, err := os.ReadFile(abs) //nolint:gosec // G304: reading the user's own bundle index.md if err != nil { @@ -572,7 +627,8 @@ func bumpRootIndexMarker(root, target string) error { if bytes.Equal(out.Bytes(), raw) { return nil } - return fsutil.WriteFileAtomic(abs, out.Bytes(), 0o644) //nolint:gosec // G306: a bundle node is a shareable knowledge document; 0o644 is intended + tx.Write(abs, out.Bytes(), 0o644, fsutil.SHA256Hex(raw)) //nolint:gosec // G306: a bundle node is a shareable knowledge document; 0o644 is intended + return nil } // findScalar returns the scalar value of key in a mapping, or "". diff --git a/internal/okf/mutate.go b/internal/okf/mutate.go index 016f788..563a8e1 100644 --- a/internal/okf/mutate.go +++ b/internal/okf/mutate.go @@ -15,6 +15,7 @@ package okf import ( + "errors" "fmt" "os" "path/filepath" @@ -193,6 +194,19 @@ func ApplyMove(root string, b *Bundle, old, new string, rewrites []LinkRewrite) } else if !os.IsNotExist(err) { return fmt.Errorf("stat %s: %w", new, err) } + // The plan was computed from b, so b's bytes are what every write below + // assumes. Each file is checked against the hash recorded at load before + // anything is written: an edit made since the load refuses the whole move + // rather than being overwritten or half-rewritten. + hashOf := func(p string) string { + if n := b.Nodes[p]; n != nil { + return n.SHA256 + } + return "" + } + if err := checkLoaded(oldAbs, old, hashOf(old)); err != nil { + return err + } // Apply link rewrites to the FULL on-disk file content (not the parsed // body) so the YAML frontmatter block is preserved by construction. The @@ -221,6 +235,9 @@ func ApplyMove(root string, b *Bundle, old, new string, rewrites []LinkRewrite) if err != nil { return fmt.Errorf("read %s: %w", rw.NodePath, err) } + if h := hashOf(rw.NodePath); h != "" && fsutil.SHA256Hex(raw) != h { + return changedSinceLoad(rw.NodePath) + } content = string(raw) } dir := filepath.Dir(rw.NodePath) @@ -237,22 +254,48 @@ func ApplyMove(root string, b *Bundle, old, new string, rewrites []LinkRewrite) } edited[rw.NodePath] = content } - for path, content := range edited { - if err := fsutil.WriteFileAtomic(absOf[path], []byte(content), 0o644); err != nil { //nolint:gosec // G306: a bundle node is a shareable knowledge document; 0o644 is intended - return fmt.Errorf("write %s: %w", path, err) + // One transaction: every rewrite and the move land together, or a failure + // part-way restores the rewritten files and leaves the node where it was. + var tx fsutil.Tx + paths := make([]string, 0, len(edited)) + for path := range edited { + paths = append(paths, path) + } + sort.Strings(paths) + for _, path := range paths { + tx.Write(absOf[path], []byte(edited[path]), 0o644, hashOf(path)) //nolint:gosec // G306: a bundle node is a shareable knowledge document; 0o644 is intended + } + tx.Rename(oldAbs, newAbs, hashOf(old)) + if err := tx.Commit(); err != nil { + if errors.Is(err, fsutil.ErrChanged) { + return fmt.Errorf("move %s -> %s: %w (re-run to plan against the current files)", old, new, err) } + return fmt.Errorf("move %s -> %s: %w", old, new, err) } + return nil +} - // Bundle directories hold shareable knowledge documents; 0o755 is intended. - if err := os.MkdirAll(filepath.Dir(newAbs), 0o755); err != nil { //nolint:gosec // G301: shareable bundle content dir - return fmt.Errorf("mkdir for %s: %w", new, err) +// checkLoaded refuses a write to rel when its bytes on disk no longer hash to +// want, the hash recorded when the bundle was loaded. An empty want (a node +// built in memory) skips the check. +func checkLoaded(abs, rel, want string) error { + if want == "" { + return nil } - if err := os.Rename(oldAbs, newAbs); err != nil { - return fmt.Errorf("move %s -> %s: %w", old, new, err) + raw, err := os.ReadFile(abs) //nolint:gosec // G304: reading a node from the user's own bundle + if err != nil { + return fmt.Errorf("read %s: %w", rel, err) + } + if fsutil.SHA256Hex(raw) != want { + return changedSinceLoad(rel) } return nil } +func changedSinceLoad(rel string) error { + return fmt.Errorf("%s: %w; nothing was written (re-run to plan against the current files)", rel, fsutil.ErrChanged) +} + // PlanRemoveOrphans returns the bundle-relative nodes that become orphaned // (zero inbound links) as a direct consequence of removing path. It is pure. func PlanRemoveOrphans(b *Bundle, path string) ([]string, error) { diff --git a/internal/okf/node.go b/internal/okf/node.go index 6d09282..bd72696 100644 --- a/internal/okf/node.go +++ b/internal/okf/node.go @@ -29,6 +29,10 @@ type Node struct { // empty block (`---\n---`); this bit is the only way to tell them apart, // which §8/§12 validation needs (a present empty block is a violation). HasFrontmatterBlock bool + // SHA256 is the hex SHA-256 of the file bytes as loaded ("" for a node + // built in memory). A writer that edits the file later checks it first, so + // an edit made after the load is refused instead of overwritten. + SHA256 string } // Type returns the node's type value ("" if absent or not a string). diff --git a/internal/okf/testdata/fuzz/FuzzNewNodeFrontmatter/tab-led-multiline-title b/internal/okf/testdata/fuzz/FuzzNewNodeFrontmatter/tab-led-multiline-title new file mode 100644 index 0000000..db4effc --- /dev/null +++ b/internal/okf/testdata/fuzz/FuzzNewNodeFrontmatter/tab-led-multiline-title @@ -0,0 +1,3 @@ +go test fuzz v1 +string("0") +string("\t\n0") diff --git a/internal/okf/testdata/fuzz/FuzzTouchModifiedRoundTrip/duplicate-key-block b/internal/okf/testdata/fuzz/FuzzTouchModifiedRoundTrip/duplicate-key-block new file mode 100644 index 0000000..db7742f --- /dev/null +++ b/internal/okf/testdata/fuzz/FuzzTouchModifiedRoundTrip/duplicate-key-block @@ -0,0 +1,2 @@ +go test fuzz v1 +string("---\ne:\ne:\n---\n") diff --git a/internal/okf/writepath_fuzz_test.go b/internal/okf/writepath_fuzz_test.go index 2e10f1f..e0aea32 100644 --- a/internal/okf/writepath_fuzz_test.go +++ b/internal/okf/writepath_fuzz_test.go @@ -22,6 +22,8 @@ import ( "strings" "testing" "time" + + "github.com/cwest/okfctl/internal/fsutil" ) // The fuzz targets below drive the WRITE paths, where frontmatter_fuzz_test.go @@ -188,8 +190,12 @@ func FuzzRootIndexMarker(f *testing.F) { if err := os.WriteFile(p, []byte(src), 0o644); err != nil { //nolint:gosec // G306: test fixture t.Fatal(err) } - if err := bumpRootIndexMarker(root, version); err != nil { - t.Fatalf("bumpRootIndexMarker(%q): %v", version, err) + var tx fsutil.Tx + if err := stageRootIndexMarker(&tx, root, version); err != nil { + t.Fatalf("stageRootIndexMarker(%q): %v", version, err) + } + if err := tx.Commit(); err != nil { + t.Fatalf("commit marker %q: %v", version, err) } got, err := os.ReadFile(p) //nolint:gosec // G304: test-owned temp file if err != nil {