Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
a3f25e4
✨ feat(lint): add tag-hygiene beside type-hygiene on a shared fold
cwest Sep 12, 2026
9827da4
πŸ› fix(lint): guard the tag fold with KStem plural rules and keep anal…
LGuichet Oct 2, 2026
2ca0898
πŸ› fix(index): tolerate CRLF index.md in check and build
LGuichet Oct 4, 2026
828aa63
Merge feat/eol-tolerant-index into next
LGuichet Oct 9, 2026
6482a61
Merge topic/tag-hygiene into next
LGuichet Oct 9, 2026
56384c8
♻️ refactor(index): expose directory shape as a DirShape struct behin…
LGuichet Oct 9, 2026
9fe3cc0
Merge feat/neighborhoods-manifest-tag-hygiene into next
LGuichet Oct 9, 2026
946fad2
πŸ› fix(bundle): read the Β§12 okf_version marker on the bundle-root ind…
LGuichet Oct 9, 2026
634eeb1
Merge fix/okf-version-root-marker into next
LGuichet Oct 9, 2026
27324e2
πŸ“ docs(spec): write-safety auditβ€”atomic, confined, injection-free writes
LGuichet Oct 12, 2026
329f2d3
✨ feat(fsutil): atomic file writer and bundle-root confinement helper
LGuichet Oct 12, 2026
2f43dbb
πŸ› fix(okf): write nodes, indexes, the log and the .okf sidecar atomic…
LGuichet Oct 12, 2026
0dd4c3b
πŸ› fix(write): save the user config, search store and migration plan a…
LGuichet Oct 12, 2026
3c4ec15
πŸ› fix(node): confine node new and node edit to the bundle root
LGuichet Oct 12, 2026
e17785e
πŸ› fix(node): refuse a node mv that leaves the bundle root
LGuichet Oct 12, 2026
2d3c1e9
πŸ› fix(node): confine node promote to the bundle root and its name to …
LGuichet Oct 12, 2026
20bd7ad
πŸ› fix(migrate): validate an edited plan before migrate --apply writes
LGuichet Oct 12, 2026
52b34e3
πŸ› fix(log): cut a log message at a bare CR as well as LF
LGuichet Oct 12, 2026
b3c7ab4
βœ… test(okf): fuzz the node, touch, okf_version marker and log write p…
LGuichet Oct 12, 2026
4f95f08
πŸ“ docs(spec): record the write-safety audit as implemented
LGuichet Oct 12, 2026
e7d044f
πŸ“ docs(agents): keep work on the fork and sign as the real author
LGuichet Oct 12, 2026
bd799a2
Merge docs/fork-contribution-rules into next
LGuichet Oct 12, 2026
ba71a31
πŸ“ docs(agents): drop the commit-signing requirement on the fork
LGuichet Oct 12, 2026
ced4353
Merge docs/drop-signing-rule into next
LGuichet Oct 12, 2026
fba88ad
πŸ”§ chore(git): force LF line endings via .gitattributes
LGuichet Oct 14, 2026
66f31bf
Merge branch 'cwest:main' into next
LGuichet Oct 15, 2026
f71e4e0
πŸ› fix(fsutil): keep the atomic writer working on Windows junctions an…
LGuichet Oct 27, 2026
5309c82
πŸ› fix(okf): confine move rewrites and check the promote destination b…
LGuichet Oct 27, 2026
848e0a2
Merge branch 'next' into fix/write-safety-audit
LGuichet Oct 27, 2026
efc58b3
Merge fix/write-safety-audit into next
LGuichet Oct 27, 2026
0538ad1
✨ feat(fsutil): hash-checked, rollback-safe multi-file transaction
LGuichet Oct 27, 2026
34042df
πŸ› fix(okf): refuse stale plans and roll back partial node mv and migr…
LGuichet Oct 27, 2026
2d52de9
🚨 fix(lint): wrap the confinement cause with %w, dedupe the separator…
LGuichet Oct 27, 2026
26437b7
Merge remote-tracking branch 'fork/next' into fix/hash-checked-writes
LGuichet Oct 27, 2026
1e2f6dd
πŸ”§ chore(deps): bump Go toolchain 1.26.9 -> 1.26.10 for GO-2026-6809
LGuichet Oct 27, 2026
d2b12d2
πŸ› fix(okf): refuse to touch a frontmatter block the parser rejects
LGuichet Oct 27, 2026
a238165
πŸ› fix(okf): double-quote a node new value that holds a control character
LGuichet Nov 4, 2026
5aa4404
Merge remote-tracking branch 'fork/next' into fix/hash-checked-writes
LGuichet Nov 4, 2026
f129a41
πŸ”₯ chore(okf): drop tagfold.go, which next removed
LGuichet Nov 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions cmd/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
102 changes: 102 additions & 0 deletions cmd/migrate_hashcheck_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
206 changes: 206 additions & 0 deletions internal/fsutil/tx.go
Original file line number Diff line number Diff line change
@@ -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...))
}
Loading
Loading