From a3f25e43ead544954e543b27b1c30d83277bb5e6 Mon Sep 17 00:00:00 2001 From: Casey West Date: Sat, 12 Sep 2026 02:54:28 -0400 Subject: [PATCH 01/28] =?UTF-8?q?=E2=9C=A8=20feat(lint):=20add=20tag-hygie?= =?UTF-8?q?ne=20beside=20type-hygiene=20on=20a=20shared=20fold?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit lint warned that Concept and Concepts are one type spelled twice but had no opinion about Wine/wine or runbook/runbooks/run-book — even though tags is the other §4.1 field every consumer routes and filters on. The --tag scope filter and the /api/v1/search tag parameter match exactly and case-sensitively, so one tag spelled three ways is three disjoint result sets, and analyze's cluster detector counted the variants separately and missed the cluster. Extract the shared base fold (case, trim, single trailing 's') as canonFold; canonType is now a thin wrapper over it, so type-hygiene is byte-identical. canonTag layers separator-insensitivity (-, _, space) on top — for tags only. Add lintTagHygiene as a sibling of lintTypeHygiene: bundle-level, advisory, "tag-hygiene" in --json, --strict treats it like any finding; the message lists each variant with its per-node count, variants sorted. analyze adopts canonTag for cluster detection so it and lint agree on when two spellings are one tag, and it now dedups the node set per cluster (the old per-occurrence append double-counted a tag repeated within one node's list. The check never rejects a value (PRD §7.4 anti-taxonomy): it flags only spellings that fold to one value, never two genuinely distinct ones. Closes #166 EOF ) --- cmd/lint.go | 5 + docs/commands/README.md | 2 + internal/okf/analyze.go | 53 ++++-- internal/okf/analyze_clusters_test.go | 80 +++++++++ internal/okf/lint.go | 105 ++++++++++- internal/okf/lint_taghygiene_test.go | 244 ++++++++++++++++++++++++++ 6 files changed, 472 insertions(+), 17 deletions(-) create mode 100644 internal/okf/analyze_clusters_test.go create mode 100644 internal/okf/lint_taghygiene_test.go diff --git a/cmd/lint.go b/cmd/lint.go index 86bfed0..babb357 100644 --- a/cmd/lint.go +++ b/cmd/lint.go @@ -80,6 +80,11 @@ func newLintCmd() *cobra.Command { "node with the same basename exists elsewhere — a moved or mistyped path (a defect), " + "distinct from a genuinely unwritten concept (a coverage gap, which analyze reports " + "advisorily and lint stays quiet on).\n\n" + + "tag-hygiene reports two or more `tags` spellings that fold to one canonical form " + + "(case, trimmed, a single trailing 's', and — for tags — separator-insensitive so " + + "run-book, run_book and runbook are one value). Like type-hygiene, it never rejects a " + + "value: it only reports spellings that fold together, so a curator can pick one. It " + + "never flags two genuinely distinct tags.\n\n" + "--semantic adds similarity-driven checks (similar-but-unlinked pairs, nodes with " + "no semantic neighbors) by reading the index built by 'okfctl-search index build'. " + "Core only reads that index, so no embedding model is needed to lint.", diff --git a/docs/commands/README.md b/docs/commands/README.md index 018689a..c41656b 100644 --- a/docs/commands/README.md +++ b/docs/commands/README.md @@ -408,6 +408,8 @@ lint surfaces judgment-worthy curation findings, not spec-floor violations (use A broken-link finding reports an internal .md link that resolves to no node when a node with the same basename exists elsewhere — a moved or mistyped path (a defect), distinct from a genuinely unwritten concept (a coverage gap, which analyze reports advisorily and lint stays quiet on). +tag-hygiene reports two or more `tags` spellings that fold to one canonical form (case, trimmed, a single trailing 's', and — for tags — separator-insensitive so run-book, run_book and runbook are one value). Like type-hygiene, it never rejects a value: it only reports spellings that fold together, so a curator can pick one. It never flags two genuinely distinct tags. + --semantic adds similarity-driven checks (similar-but-unlinked pairs, nodes with no semantic neighbors) by reading the index built by 'okfctl-search index build'. Core only reads that index, so no embedding model is needed to lint. ``` diff --git a/internal/okf/analyze.go b/internal/okf/analyze.go index 8945dd5..999fc2a 100644 --- a/internal/okf/analyze.go +++ b/internal/okf/analyze.go @@ -589,28 +589,55 @@ func analyzeConnectivity(b *Bundle) ConnectivityReport { } func analyzeClusters(b *Bundle, opts AnalyzeOptions) []ClusterFinding { - byTag := map[string][]string{} + // Adopt lint's shared tag fold (canonTag: case + trim + single trailing 's' + // + separator-insensitive) so analyze and lint agree on when two spellings + // are one tag. Group by canonical key; within a key, keep the DISTINCT node + // set (a node tagged both `wine` and `Wine` counts once) and the raw variants + // so the reported tag is a real spelling, not the fold key. + type cluster struct { + nodes map[string]bool + variants map[string]bool + } + byKey := map[string]*cluster{} for _, p := range sortedNodePaths(b) { for _, tag := range nodeTags(b.Nodes[p]) { - key := strings.ToLower(strings.TrimSpace(tag)) + key := canonTag(tag) if key == "" { continue } - byTag[key] = append(byTag[key], p) + c := byKey[key] + if c == nil { + c = &cluster{nodes: map[string]bool{}, variants: map[string]bool{}} + byKey[key] = c + } + c.nodes[p] = true + c.variants[strings.TrimSpace(tag)] = true } } var out []ClusterFinding - tags := make([]string, 0, len(byTag)) - for t := range byTag { - tags = append(tags, t) - } - sort.Strings(tags) - for _, t := range tags { - members := byTag[t] - if len(members) >= opts.ClusterMin { - sort.Strings(members) - out = append(out, ClusterFinding{Tag: t, Nodes: members}) + keys := make([]string, 0, len(byKey)) + for k := range byKey { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + c := byKey[k] + if len(c.nodes) < opts.ClusterMin { + continue + } + members := make([]string, 0, len(c.nodes)) + for p := range c.nodes { + members = append(members, p) + } + sort.Strings(members) + // Report the lexicographically-first raw variant as the cluster tag: a + // real spelling from the corpus, deterministic across runs. + variants := make([]string, 0, len(c.variants)) + for v := range c.variants { + variants = append(variants, v) } + sort.Strings(variants) + out = append(out, ClusterFinding{Tag: variants[0], Nodes: members}) } return out } diff --git a/internal/okf/analyze_clusters_test.go b/internal/okf/analyze_clusters_test.go new file mode 100644 index 0000000..5f5d8bf --- /dev/null +++ b/internal/okf/analyze_clusters_test.go @@ -0,0 +1,80 @@ +// 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 okf + +import "testing" + +// analyze adopts the shared tag fold, so three spellings of one tag over three +// nodes form a single cluster that reaches the default --cluster-min 3 — where +// today's case-only fold leaves them as three 1-node tags, all invisible. +func TestAnalyzeClusters_FoldedVariantsFormOneCluster(t *testing.T) { + b := mkLintBundle(t, map[string]string{ + "index.md": "---\ntype: Index\ntitle: Index\n---\n\n# Index\n\n- [A](a.md)\n- [B](b.md)\n- [C](c.md)\n", + "a.md": lintDocTags("Concept", "A", []string{"runbook"}, "Body."), + "b.md": lintDocTags("Concept", "B", []string{"runbooks"}, "Body."), + "c.md": lintDocTags("Concept", "C", []string{"run-book"}, "Body."), + }) + clusters := analyzeClusters(b, DefaultAnalyzeOptions()) + var runbook *ClusterFinding + for i := range clusters { + if canonTag(clusters[i].Tag) == canonTag("runbook") { + runbook = &clusters[i] + break + } + } + if runbook == nil { + t.Fatalf("expected a folded runbook cluster at cluster-min 3, got clusters=%+v", clusters) + } + if len(runbook.Nodes) != 3 { + t.Fatalf("folded runbook cluster should span all 3 nodes, got %d: %+v", len(runbook.Nodes), runbook.Nodes) + } +} + +// Case folding already merged Wine/wine before this change; that behavior must +// survive the fold swap (regression guard for the analyze path). +func TestAnalyzeClusters_CaseVariantsStillMerge(t *testing.T) { + b := mkLintBundle(t, map[string]string{ + "index.md": "---\ntype: Index\ntitle: Index\n---\n\n# Index\n\n- [A](a.md)\n- [B](b.md)\n- [C](c.md)\n", + "a.md": lintDocTags("Concept", "A", []string{"Wine"}, "Body."), + "b.md": lintDocTags("Concept", "B", []string{"wine"}, "Body."), + "c.md": lintDocTags("Concept", "C", []string{"WINE"}, "Body."), + }) + clusters := analyzeClusters(b, DefaultAnalyzeOptions()) + found := false + for _, c := range clusters { + if canonTag(c.Tag) == canonTag("wine") && len(c.Nodes) == 3 { + found = true + } + } + if !found { + t.Fatalf("Wine/wine/WINE must still merge into one 3-node cluster, got %+v", clusters) + } +} + +// Distinct tags must not be merged by the fold (negative control for analyze). +func TestAnalyzeClusters_DistinctTagsNotMerged(t *testing.T) { + b := mkLintBundle(t, map[string]string{ + "index.md": "---\ntype: Index\ntitle: Index\n---\n\n# Index\n\n- [A](a.md)\n- [B](b.md)\n- [C](c.md)\n", + "a.md": lintDocTags("Concept", "A", []string{"oauth1"}, "Body."), + "b.md": lintDocTags("Concept", "B", []string{"oauth2"}, "Body."), + "c.md": lintDocTags("Concept", "C", []string{"incident"}, "Body."), + }) + clusters := analyzeClusters(b, DefaultAnalyzeOptions()) + for _, c := range clusters { + if len(c.Nodes) >= 3 { + t.Fatalf("distinct tags must not be folded into a cluster, got %+v", c) + } + } +} diff --git a/internal/okf/lint.go b/internal/okf/lint.go index 0080a1e..7298399 100644 --- a/internal/okf/lint.go +++ b/internal/okf/lint.go @@ -27,7 +27,7 @@ import ( // validate Finding (a spec-floor violation), a lint finding is curation // guidance — never a format failure. type LintFinding struct { - Check string `json:"check"` // "orphan" | "missing-xref" | "coverage-gap" | "type-hygiene" | "broken-link" | "status-lifecycle" | "spec-version" + Check string `json:"check"` // "orphan" | "missing-xref" | "coverage-gap" | "type-hygiene" | "tag-hygiene" | "broken-link" | "status-lifecycle" | "spec-version" Path string `json:"path"` // node path the finding is about ("" for bundle-level findings) Message string `json:"message"` } @@ -56,6 +56,7 @@ func Lint(b *Bundle, opts LintOptions) []LintFinding { findings = append(findings, lintBrokenLinks(b)...) findings = append(findings, lintCoverageGaps(b, threshold)...) findings = append(findings, lintTypeHygiene(b)...) + findings = append(findings, lintTagHygiene(b)...) findings = append(findings, lintStatusLifecycle(b)...) findings = append(findings, lintSpecVersion(b)...) @@ -655,12 +656,108 @@ func lintTypeHygiene(b *Bundle) []LintFinding { return out } -// canonType folds a type value to case-insensitive + singular (drop a single -// trailing 's') for near-duplicate grouping. -func canonType(s string) string { +// lintTagHygiene warns when two or more distinct `tags` values fold to the same +// canonical form, which usually signals accidental drift on the other §4.1 +// cross-cutting field every consumer routes and filters on. The `--tag` scope +// filter and the /api/v1/search `tag` parameter match exactly and +// case-sensitively, so one tag spelled three ways is three disjoint result sets; +// this surfaces that drift the same way type-hygiene does for `type`. +// +// The fold is the shared canonTag: the base fold (case, trim, single trailing +// 's') plus tag-only separator-insensitivity (-, _, space). Anti-taxonomy stands +// (PRD §7.4): it flags only spellings that fold to ONE value, never two genuinely +// distinct values, and it is a warning class — never a validate rejection. The +// message lists each variant with its per-node count, variants sorted. +func lintTagHygiene(b *Bundle) []LintFinding { + // canonical -> raw tag value -> set of node paths carrying it. + groups := map[string]map[string]map[string]bool{} + for _, n := range b.Nodes { + seen := map[string]bool{} // dedupe a repeated tag within one node + for _, raw := range n.Tags() { + raw = strings.TrimSpace(raw) + if raw == "" || seen[raw] { + continue + } + seen[raw] = true + c := canonTag(raw) + if c == "" { + continue + } + if groups[c] == nil { + groups[c] = map[string]map[string]bool{} + } + if groups[c][raw] == nil { + groups[c][raw] = map[string]bool{} + } + groups[c][raw][n.Path] = true + } + } + + var out []LintFinding + canons := make([]string, 0, len(groups)) + for c := range groups { + canons = append(canons, c) + } + sort.Strings(canons) + for _, c := range canons { + if len(groups[c]) < 2 { + continue + } + variants := make([]string, 0, len(groups[c])) + for v := range groups[c] { + variants = append(variants, v) + } + sort.Strings(variants) + parts := make([]string, 0, len(variants)) + for _, v := range variants { + n := len(groups[c][v]) + parts = append(parts, fmt.Sprintf("%s (%d %s)", v, n, pluralNodes(n))) + } + out = append(out, LintFinding{ + Check: "tag-hygiene", + Path: "", + Message: fmt.Sprintf("tag-hygiene: near-duplicate tag values likely refer to one tag: %s", strings.Join(parts, ", ")), + }) + } + return out +} + +// pluralNodes returns "node" for a count of 1, "nodes" otherwise. +func pluralNodes(n int) string { + if n == 1 { + return "node" + } + return "nodes" +} + +// canonFold is the shared base fold: case-insensitive, trimmed, and singular +// (drop a single trailing 's'). It is the one place `type` and `tags` +// near-duplicate grouping agree on, so the tool can never apply two different +// folds to the same kind of §4.1 value. It is separator-SENSITIVE by design — +// separator-insensitivity is a tag-only layer (see canonTag) and must not leak +// into the type path. +func canonFold(s string) string { c := strings.ToLower(strings.TrimSpace(s)) if len(c) > 1 && strings.HasSuffix(c, "s") { c = c[:len(c)-1] } return c } + +// canonType folds a `type` value for near-duplicate grouping. It is exactly the +// shared base fold (case + trim + single trailing 's'); it deliberately does NOT +// add tag's separator rule, so type-hygiene behavior is unchanged by the shared +// extraction. +func canonType(s string) string { return canonFold(s) } + +// tagSeparators are the intra-tag separators (§4.1 tags are free-form): a hyphen, +// underscore, or space. Two tags that differ only in how a compound is joined +// (home-lab vs homelab, run book vs runbook) are one value spelled two ways. +var tagSeparators = strings.NewReplacer("-", "", "_", "", " ", "") + +// canonTag folds a `tags` value: the shared base fold, then separator-insensitive +// (-, _, space collapsed). The base fold runs first so a trailing 's' is dropped +// before separators are removed (design-patterns -> design-pattern -> +// designpattern), matching design-pattern's fold. Tags get this extra layer; +// types do not. +func canonTag(s string) string { return tagSeparators.Replace(canonFold(s)) } diff --git a/internal/okf/lint_taghygiene_test.go b/internal/okf/lint_taghygiene_test.go new file mode 100644 index 0000000..5789df7 --- /dev/null +++ b/internal/okf/lint_taghygiene_test.go @@ -0,0 +1,244 @@ +// 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 okf + +import ( + "strings" + "testing" +) + +// lintDocTags builds a node with a type, title, and a YAML tags list, so tests +// can exercise the tag-hygiene fold the way the real corpus declares tags. +func lintDocTags(typ, title string, tags []string, body string) string { + tl := "[" + strings.Join(tags, ", ") + "]" + return "---\ntype: " + typ + "\ntitle: " + title + "\ntags: " + tl + "\n---\n\n# " + title + "\n\n" + body + "\n" +} + +// The fold table is the contract. canonFold is the shared base fold used by both +// type-hygiene and tag-hygiene (case, trim, single trailing 's'). canonTag layers +// separator-insensitivity (-, _, space) on top of canonFold, for TAGS ONLY. +func TestCanonFold_SharedBaseFold(t *testing.T) { + cases := []struct{ in, want string }{ + {"Concept", "concept"}, + {"concept", "concept"}, + {"Concepts", "concept"}, // single trailing 's' dropped + {" Wine ", "wine"}, // trim + {"WINE", "wine"}, // case + {"runbooks", "runbook"}, // trailing 's' + {"run-book", "run-book"}, // base fold does NOT strip separators + {"s", "s"}, // len==1 guard: don't strip the only char + {"gas", "ga"}, // trailing 's' dropped even mid-word (existing type behavior) + {"", ""}, + } + for _, c := range cases { + if got := canonFold(c.in); got != c.want { + t.Errorf("canonFold(%q) = %q, want %q", c.in, got, c.want) + } + } +} + +func TestCanonTag_SeparatorInsensitive(t *testing.T) { + cases := []struct{ in, want string }{ + {"Wine", "wine"}, + {"wine", "wine"}, + {"runbook", "runbook"}, + {"runbooks", "runbook"}, // trailing 's' + {"run-book", "runbook"}, // hyphen stripped + {"run_book", "runbook"}, // underscore stripped + {"Run Book", "runbook"}, // space stripped + case + {"Play Book", "playbook"}, // space stripped + case + {"playbook", "playbook"}, + {"home-lab", "homelab"}, // separator-only collision + {"homelab", "homelab"}, + {"design-patterns", "designpattern"}, // separator + trailing 's' + {"design-pattern", "designpattern"}, + // The -is / -us / -ss class must NOT lose its trailing letters: only a + // single trailing 's' is dropped, and none of these have a bare one. + {"hormesis", "hormesi"}, // -is: 's' dropped once, still distinct from any sibling + {"hysteresis", "hysteresi"}, + {"css", "cs"}, + {"gpt-oss", "gptos"}, + {"blast-radius", "blastradiu"}, + {"freshness", "freshnes"}, + } + for _, c := range cases { + if got := canonTag(c.in); got != c.want { + t.Errorf("canonTag(%q) = %q, want %q", c.in, got, c.want) + } + } +} + +// canonTag must NOT change the type path. Types still fold with canonType +// (== canonFold), which is separator-SENSITIVE. Proven by table: a hyphenated +// and an unhyphenated type do NOT collapse under the type fold. +func TestCanonType_UnchangedBySeparatorRule(t *testing.T) { + if canonType("run-book") == canonType("runbook") { + t.Fatalf("type fold must stay separator-sensitive: run-book and runbook must NOT collapse") + } + if canonType("Concepts") != canonType("concept") { + t.Fatalf("type fold must still be case+plural: Concepts and concept must collapse") + } +} + +// POSITIVE controls: each fires exactly one tag-hygiene finding. +func TestLint_TagHygiene_Positive(t *testing.T) { + cases := []struct { + name string + tagA string + tagB string + }{ + {"case", "Wine", "wine"}, + {"plural", "runbook", "runbooks"}, + {"separator-hyphen", "run-book", "runbook"}, + {"separator-space", "Play Book", "playbook"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + b := mkLintBundle(t, map[string]string{ + "index.md": "---\ntype: Index\ntitle: Index\n---\n\n# Index\n\n- [A](a.md)\n- [B](b.md)\n", + "a.md": lintDocTags("Concept", "A", []string{c.tagA}, "Body."), + "b.md": lintDocTags("Concept", "B", []string{c.tagB}, "Body."), + }) + th := findingsFor(Lint(b, LintOptions{}), "tag-hygiene") + if len(th) != 1 { + t.Fatalf("%s: expected one tag-hygiene finding for %q/%q, got %+v", c.name, c.tagA, c.tagB, th) + } + // Message lists both variants with node counts, and is bundle-level. + if th[0].Path != "" { + t.Fatalf("%s: tag-hygiene must be bundle-level (Path==\"\"), got %q", c.name, th[0].Path) + } + m := lc(th[0].Message) + if !strings.Contains(m, lc(c.tagA)) || !strings.Contains(m, lc(c.tagB)) { + t.Fatalf("%s: message must name both variants: %q", c.name, th[0].Message) + } + }) + } +} + +// The message carries per-node counts and sorts the variants. +func TestLint_TagHygiene_MessageCountsAndSort(t *testing.T) { + b := mkLintBundle(t, map[string]string{ + "index.md": "---\ntype: Index\ntitle: Index\n---\n\n# Index\n\n- [A](a.md)\n- [B](b.md)\n- [C](c.md)\n", + // runbook x1 (a), runbooks x1 (b), run-book x1 (c) -> one folded group. + "a.md": lintDocTags("Concept", "A", []string{"runbook"}, "Body."), + "b.md": lintDocTags("Concept", "B", []string{"runbooks"}, "Body."), + "c.md": lintDocTags("Concept", "C", []string{"run-book"}, "Body."), + }) + th := findingsFor(Lint(b, LintOptions{}), "tag-hygiene") + if len(th) != 1 { + t.Fatalf("expected one folded tag-hygiene finding, got %+v", th) + } + msg := th[0].Message + // Variants sorted ascending: run-book, runbook, runbooks. + iRunBook := strings.Index(msg, "run-book") + iRunbook := strings.Index(msg, "runbook ") // trailing space or paren after + iRunbooks := strings.Index(msg, "runbooks") + if iRunBook < 0 || iRunbook < 0 || iRunbooks < 0 { + t.Fatalf("message must name all three variants: %q", msg) + } + if iRunBook >= iRunbook || iRunbook >= iRunbooks { + t.Fatalf("variants must be sorted (run-book, runbook, runbooks): %q", msg) + } + // Per-node counts present: each variant is on exactly one node. + if !strings.Contains(msg, "(1 node)") && !strings.Contains(msg, "1 node") { + t.Fatalf("message must carry per-node counts: %q", msg) + } +} + +// NEGATIVE controls: legitimately similar-looking tags stay silent. +func TestLint_TagHygiene_Negative(t *testing.T) { + cases := []struct { + name string + tagA string + tagB string + }{ + {"version-digit", "v1", "v2"}, + {"oauth-digit", "oauth1", "oauth2"}, + {"distinct-words", "oncall", "incident"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + b := mkLintBundle(t, map[string]string{ + "index.md": "---\ntype: Index\ntitle: Index\n---\n\n# Index\n\n- [A](a.md)\n- [B](b.md)\n", + "a.md": lintDocTags("Concept", "A", []string{c.tagA}, "Body."), + "b.md": lintDocTags("Concept", "B", []string{c.tagB}, "Body."), + }) + if n := len(findingsFor(Lint(b, LintOptions{}), "tag-hygiene")); n != 0 { + t.Fatalf("%s: %q/%q are distinct; expected 0 tag-hygiene findings, got %d", c.name, c.tagA, c.tagB, n) + } + }) + } +} + +// A single tag spread over many nodes is not drift — it must stay silent. +func TestLint_TagHygiene_SingleTagManyNodesNoFinding(t *testing.T) { + b := mkLintBundle(t, map[string]string{ + "index.md": "---\ntype: Index\ntitle: Index\n---\n\n# Index\n\n- [A](a.md)\n- [B](b.md)\n- [C](c.md)\n", + "a.md": lintDocTags("Concept", "A", []string{"wine"}, "Body."), + "b.md": lintDocTags("Concept", "B", []string{"wine"}, "Body."), + "c.md": lintDocTags("Concept", "C", []string{"wine"}, "Body."), + }) + if n := len(findingsFor(Lint(b, LintOptions{}), "tag-hygiene")); n != 0 { + t.Fatalf("one tag on many nodes is not drift; expected 0 tag-hygiene findings, got %d", n) + } +} + +// The -is/-us/-ss digraph class (real-corpus measurement: 65 such tags, zero +// collisions) must each be silent — guards the trailing-'s' rule without needing +// a stop-list. Each planted on a distinct node with an unrelated sibling. +func TestLint_TagHygiene_DigraphClassSilent(t *testing.T) { + digraphs := []string{"hormesis", "hysteresis", "css", "freshness", "blast-radius", "gpt-oss"} + for _, d := range digraphs { + t.Run(d, func(t *testing.T) { + b := mkLintBundle(t, map[string]string{ + "index.md": "---\ntype: Index\ntitle: Index\n---\n\n# Index\n\n- [A](a.md)\n- [B](b.md)\n", + "a.md": lintDocTags("Concept", "A", []string{d}, "Body."), + "b.md": lintDocTags("Concept", "B", []string{"kubernetes"}, "Body."), + }) + if n := len(findingsFor(Lint(b, LintOptions{}), "tag-hygiene")); n != 0 { + t.Fatalf("digraph tag %q must not collide with an unrelated sibling; got %d findings", d, n) + } + }) + } +} + +// The shared-fold extraction must leave type-hygiene byte-identical. This pins +// the exact message string the check emitted before the refactor, proving the +// type path did not move when canonType became a thin canonFold wrapper. +func TestLint_TypeHygiene_MessageByteIdenticalAfterFoldExtraction(t *testing.T) { + b := mkLintBundle(t, map[string]string{ + "index.md": "---\ntype: Index\ntitle: Index\n---\n\n# Index\n\n- [A](a.md)\n- [B](b.md)\n", + "a.md": lintDoc("Concept", "A", "Body."), + "b.md": lintDoc("Concepts", "B", "Body."), + }) + th := findingsFor(Lint(b, LintOptions{}), "type-hygiene") + if len(th) != 1 { + t.Fatalf("expected one type-hygiene finding, got %+v", th) + } + const want = "type-hygiene: near-duplicate type values likely refer to one type: Concept, Concepts" + if th[0].Message != want { + t.Fatalf("type-hygiene message changed by fold extraction:\n got: %q\nwant: %q", th[0].Message, want) + } + // And a separator-only type pair must NOT collapse (types stay + // separator-sensitive; the tag-only rule must not leak into the type path). + b2 := mkLintBundle(t, map[string]string{ + "index.md": "---\ntype: Index\ntitle: Index\n---\n\n# Index\n\n- [A](a.md)\n- [B](b.md)\n", + "a.md": lintDoc("run-book", "A", "Body."), + "b.md": lintDoc("runbook", "B", "Body."), + }) + if n := len(findingsFor(Lint(b2, LintOptions{}), "type-hygiene")); n != 0 { + t.Fatalf("type-hygiene must stay separator-sensitive: run-book/runbook types must NOT fold, got %d findings", n) + } +} From 9827da4e1ab9b718a01c2504592d19ce7e023d6f Mon Sep 17 00:00:00 2001 From: LGuichet Date: Fri, 2 Oct 2026 16:17:22 +0200 Subject: [PATCH 02/28] =?UTF-8?q?=F0=9F=90=9B=20fix(lint):=20guard=20the?= =?UTF-8?q?=20tag=20fold=20with=20KStem=20plural=20rules=20and=20keep=20an?= =?UTF-8?q?alyze=20labels?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The bare trailing-'s' fold merged distinct short tags (new/news, op/ops, aws/aw, js/j, k8s/k8) and missed real variants (-es and -ies plurals, ci/cd, node.js). Fold tags instead through tagSurface (case, trim, and -, _, space, / separators, plus a full stop between letters per UAX #29) and tagKeys, which applies KStem's plural rules (Lucene KStemmer.java, derived from the UMass CIIR KStemmer): letters-only, more than two letters, a plain 's' dropped only after more than three letters and not after 'ss' or 'ous', and the Snowball English invariant forms (news, atlas, ...). KStem's dictionary lookup is stood in for by the bundle's own tag vocabulary: a spelling folds onto a candidate only when that candidate is itself a tag, so non-word stems never become keys. The partition depends only on the tag set, never its order. The type path (canonType) is unchanged. analyze labels clusters with the lower-cased variant and orders them by label, so case-only and separator-only clusters read exactly as before the fold swap (main labelled Wine/wine as "wine"; the raw variant made it "Wine"). lint's long help now describes the fold as a heuristic instead of claiming it never flags distinct tags. Tests: the negative controls are pairs that folded under the old rule (each fails against it), positive controls cover the new merges, the tag-hygiene message and cluster labels are pinned exactly, and the digraph control that could not fail is replaced. --- cmd/lint.go | 13 ++- docs/commands/README.md | 2 +- internal/okf/analyze.go | 24 ++-- internal/okf/analyze_clusters_test.go | 51 ++++---- internal/okf/lint.go | 38 +++--- internal/okf/lint_taghygiene_test.go | 162 ++++++++++++++++---------- internal/okf/tagfold.go | 158 +++++++++++++++++++++++++ 7 files changed, 326 insertions(+), 122 deletions(-) create mode 100644 internal/okf/tagfold.go diff --git a/cmd/lint.go b/cmd/lint.go index babb357..07d8783 100644 --- a/cmd/lint.go +++ b/cmd/lint.go @@ -80,11 +80,14 @@ func newLintCmd() *cobra.Command { "node with the same basename exists elsewhere — a moved or mistyped path (a defect), " + "distinct from a genuinely unwritten concept (a coverage gap, which analyze reports " + "advisorily and lint stays quiet on).\n\n" + - "tag-hygiene reports two or more `tags` spellings that fold to one canonical form " + - "(case, trimmed, a single trailing 's', and — for tags — separator-insensitive so " + - "run-book, run_book and runbook are one value). Like type-hygiene, it never rejects a " + - "value: it only reports spellings that fold together, so a curator can pick one. It " + - "never flags two genuinely distinct tags.\n\n" + + "tag-hygiene reports two or more `tags` spellings that fold to one canonical form: " + + "case and surrounding space are ignored, as are separators (run-book, run_book, " + + "run book, ci/cd, and node.js match runbook, cicd, and nodejs), and a plural folds " + + "onto its singular only when that singular is itself a tag in the bundle, using " + + "KStem's plural rules (short tags such as aws, ops, and js are never stemmed). The " + + "fold is a heuristic, so review a finding before normalizing. Like type-hygiene, it " + + "never rejects a value: it only reports spellings that fold together, so a curator " + + "can pick one.\n\n" + "--semantic adds similarity-driven checks (similar-but-unlinked pairs, nodes with " + "no semantic neighbors) by reading the index built by 'okfctl-search index build'. " + "Core only reads that index, so no embedding model is needed to lint.", diff --git a/docs/commands/README.md b/docs/commands/README.md index c41656b..9a06a15 100644 --- a/docs/commands/README.md +++ b/docs/commands/README.md @@ -408,7 +408,7 @@ lint surfaces judgment-worthy curation findings, not spec-floor violations (use A broken-link finding reports an internal .md link that resolves to no node when a node with the same basename exists elsewhere — a moved or mistyped path (a defect), distinct from a genuinely unwritten concept (a coverage gap, which analyze reports advisorily and lint stays quiet on). -tag-hygiene reports two or more `tags` spellings that fold to one canonical form (case, trimmed, a single trailing 's', and — for tags — separator-insensitive so run-book, run_book and runbook are one value). Like type-hygiene, it never rejects a value: it only reports spellings that fold together, so a curator can pick one. It never flags two genuinely distinct tags. +tag-hygiene reports two or more `tags` spellings that fold to one canonical form: case and surrounding space are ignored, as are separators (run-book, run_book, run book, ci/cd, and node.js match runbook, cicd, and nodejs), and a plural folds onto its singular only when that singular is itself a tag in the bundle, using KStem's plural rules (short tags such as aws, ops, and js are never stemmed). The fold is a heuristic, so review a finding before normalizing. Like type-hygiene, it never rejects a value: it only reports spellings that fold together, so a curator can pick one. --semantic adds similarity-driven checks (similar-but-unlinked pairs, nodes with no semantic neighbors) by reading the index built by 'okfctl-search index build'. Core only reads that index, so no embedding model is needed to lint. diff --git a/internal/okf/analyze.go b/internal/okf/analyze.go index 999fc2a..d5bea39 100644 --- a/internal/okf/analyze.go +++ b/internal/okf/analyze.go @@ -589,11 +589,12 @@ func analyzeConnectivity(b *Bundle) ConnectivityReport { } func analyzeClusters(b *Bundle, opts AnalyzeOptions) []ClusterFinding { - // Adopt lint's shared tag fold (canonTag: case + trim + single trailing 's' - // + separator-insensitive) so analyze and lint agree on when two spellings - // are one tag. Group by canonical key; within a key, keep the DISTINCT node - // set (a node tagged both `wine` and `Wine` counts once) and the raw variants - // so the reported tag is a real spelling, not the fold key. + // Adopt lint's tag fold (tagKeys) so analyze and lint agree on when two + // spellings are one tag. Group by canonical key; within a key, keep the + // DISTINCT node set (a node tagged both `wine` and `Wine` counts once) and the + // lower-cased variants, so the reported tag is a real spelling rather than the + // fold key, and a case-only cluster keeps the lower-cased label it always had. + tagKey := bundleTagKeys(b) type cluster struct { nodes map[string]bool variants map[string]bool @@ -601,7 +602,7 @@ func analyzeClusters(b *Bundle, opts AnalyzeOptions) []ClusterFinding { byKey := map[string]*cluster{} for _, p := range sortedNodePaths(b) { for _, tag := range nodeTags(b.Nodes[p]) { - key := canonTag(tag) + key := tagKey[strings.TrimSpace(tag)] if key == "" { continue } @@ -611,7 +612,7 @@ func analyzeClusters(b *Bundle, opts AnalyzeOptions) []ClusterFinding { byKey[key] = c } c.nodes[p] = true - c.variants[strings.TrimSpace(tag)] = true + c.variants[strings.ToLower(strings.TrimSpace(tag))] = true } } var out []ClusterFinding @@ -630,8 +631,8 @@ func analyzeClusters(b *Bundle, opts AnalyzeOptions) []ClusterFinding { members = append(members, p) } sort.Strings(members) - // Report the lexicographically-first raw variant as the cluster tag: a - // real spelling from the corpus, deterministic across runs. + // Report the lexicographically-first lower-cased variant as the cluster + // tag: a real spelling from the corpus, deterministic across runs. variants := make([]string, 0, len(c.variants)) for v := range c.variants { variants = append(variants, v) @@ -639,6 +640,11 @@ func analyzeClusters(b *Bundle, opts AnalyzeOptions) []ClusterFinding { sort.Strings(variants) out = append(out, ClusterFinding{Tag: variants[0], Nodes: members}) } + // Order by the reported label, not the fold key: the key drops separators + // (e-reporting -> ereporting), and sorting on it would reorder clusters + // relative to a case-only fold even when no spelling was merged. Labels are + // unique across clusters, since each lower-cased variant has exactly one key. + sort.Slice(out, func(i, j int) bool { return out[i].Tag < out[j].Tag }) return out } diff --git a/internal/okf/analyze_clusters_test.go b/internal/okf/analyze_clusters_test.go index 5f5d8bf..6328bb2 100644 --- a/internal/okf/analyze_clusters_test.go +++ b/internal/okf/analyze_clusters_test.go @@ -17,8 +17,9 @@ package okf import "testing" // analyze adopts the shared tag fold, so three spellings of one tag over three -// nodes form a single cluster that reaches the default --cluster-min 3 — where -// today's case-only fold leaves them as three 1-node tags, all invisible. +// nodes form a single cluster that reaches the default --cluster-min 3—where a +// case-only fold leaves them as three 1-node tags, all invisible. The label is +// the lexicographically-first lower-cased spelling, pinned exactly. func TestAnalyzeClusters_FoldedVariantsFormOneCluster(t *testing.T) { b := mkLintBundle(t, map[string]string{ "index.md": "---\ntype: Index\ntitle: Index\n---\n\n# Index\n\n- [A](a.md)\n- [B](b.md)\n- [C](c.md)\n", @@ -27,23 +28,17 @@ func TestAnalyzeClusters_FoldedVariantsFormOneCluster(t *testing.T) { "c.md": lintDocTags("Concept", "C", []string{"run-book"}, "Body."), }) clusters := analyzeClusters(b, DefaultAnalyzeOptions()) - var runbook *ClusterFinding - for i := range clusters { - if canonTag(clusters[i].Tag) == canonTag("runbook") { - runbook = &clusters[i] - break - } - } - if runbook == nil { - t.Fatalf("expected a folded runbook cluster at cluster-min 3, got clusters=%+v", clusters) + if len(clusters) != 1 { + t.Fatalf("expected one folded runbook cluster at cluster-min 3, got clusters=%+v", clusters) } - if len(runbook.Nodes) != 3 { - t.Fatalf("folded runbook cluster should span all 3 nodes, got %d: %+v", len(runbook.Nodes), runbook.Nodes) + if clusters[0].Tag != "run-book" || len(clusters[0].Nodes) != 3 { + t.Fatalf("folded runbook cluster should be labelled \"run-book\" over 3 nodes, got %+v", clusters[0]) } } -// Case folding already merged Wine/wine before this change; that behavior must -// survive the fold swap (regression guard for the analyze path). +// Case folding already merged Wine/wine before this change; that behavior and +// its lower-cased label must survive the fold swap (regression guard for the +// analyze path: an upper-case spelling sorting first must not relabel it). func TestAnalyzeClusters_CaseVariantsStillMerge(t *testing.T) { b := mkLintBundle(t, map[string]string{ "index.md": "---\ntype: Index\ntitle: Index\n---\n\n# Index\n\n- [A](a.md)\n- [B](b.md)\n- [C](c.md)\n", @@ -52,14 +47,8 @@ func TestAnalyzeClusters_CaseVariantsStillMerge(t *testing.T) { "c.md": lintDocTags("Concept", "C", []string{"WINE"}, "Body."), }) clusters := analyzeClusters(b, DefaultAnalyzeOptions()) - found := false - for _, c := range clusters { - if canonTag(c.Tag) == canonTag("wine") && len(c.Nodes) == 3 { - found = true - } - } - if !found { - t.Fatalf("Wine/wine/WINE must still merge into one 3-node cluster, got %+v", clusters) + if len(clusters) != 1 || clusters[0].Tag != "wine" || len(clusters[0].Nodes) != 3 { + t.Fatalf("Wine/wine/WINE must still merge into one 3-node cluster labelled \"wine\", got %+v", clusters) } } @@ -78,3 +67,19 @@ func TestAnalyzeClusters_DistinctTagsNotMerged(t *testing.T) { } } } + +// Clusters are ordered by their reported label. The fold key drops separators +// (e-reporting -> ereporting), so ordering by key would move e-reporting after +// earmark even though nothing was merged. +func TestAnalyzeClusters_OrderedByLabel(t *testing.T) { + b := mkLintBundle(t, map[string]string{ + "index.md": "---\ntype: Index\ntitle: Index\n---\n\n# Index\n\n- [A](a.md)\n- [B](b.md)\n- [C](c.md)\n", + "a.md": lintDocTags("Concept", "A", []string{"e-reporting", "earmark"}, "Body."), + "b.md": lintDocTags("Concept", "B", []string{"e-reporting", "earmark"}, "Body."), + "c.md": lintDocTags("Concept", "C", []string{"e-reporting", "earmark"}, "Body."), + }) + clusters := analyzeClusters(b, DefaultAnalyzeOptions()) + if len(clusters) != 2 || clusters[0].Tag != "e-reporting" || clusters[1].Tag != "earmark" { + t.Fatalf("clusters must be ordered by label (e-reporting, earmark), got %+v", clusters) + } +} diff --git a/internal/okf/lint.go b/internal/okf/lint.go index 7298399..1cff55d 100644 --- a/internal/okf/lint.go +++ b/internal/okf/lint.go @@ -663,12 +663,14 @@ func lintTypeHygiene(b *Bundle) []LintFinding { // case-sensitively, so one tag spelled three ways is three disjoint result sets; // this surfaces that drift the same way type-hygiene does for `type`. // -// The fold is the shared canonTag: the base fold (case, trim, single trailing -// 's') plus tag-only separator-insensitivity (-, _, space). Anti-taxonomy stands -// (PRD §7.4): it flags only spellings that fold to ONE value, never two genuinely -// distinct values, and it is a warning class — never a validate rejection. The -// message lists each variant with its per-node count, variants sorted. +// The fold is tagKeys: case, trim, and separator-insensitive surface forms, +// with KStem's guarded plural rules folding a spelling onto another only when +// that other spelling is itself a tag in the bundle. The fold is a heuristic; +// anti-taxonomy stands (PRD §7.4): it reports spellings that fold together and +// never rejects a value, a warning class—never a validate rejection. The message +// lists each variant with its per-node count, variants sorted. func lintTagHygiene(b *Bundle) []LintFinding { + keys := bundleTagKeys(b) // canonical -> raw tag value -> set of node paths carrying it. groups := map[string]map[string]map[string]bool{} for _, n := range b.Nodes { @@ -679,7 +681,7 @@ func lintTagHygiene(b *Bundle) []LintFinding { continue } seen[raw] = true - c := canonTag(raw) + c := keys[raw] if c == "" { continue } @@ -730,12 +732,12 @@ func pluralNodes(n int) string { return "nodes" } -// canonFold is the shared base fold: case-insensitive, trimmed, and singular -// (drop a single trailing 's'). It is the one place `type` and `tags` -// near-duplicate grouping agree on, so the tool can never apply two different -// folds to the same kind of §4.1 value. It is separator-SENSITIVE by design — -// separator-insensitivity is a tag-only layer (see canonTag) and must not leak -// into the type path. +// canonFold is the type fold: case-insensitive, trimmed, and singular (drop a +// single trailing 's'). It is separator-SENSITIVE by design. Tags fold +// differently (see tagKeys): short slug-like tag values (aws, ops, news) are +// exactly where an unguarded trailing-'s' rule merges distinct values, so the +// tag path uses KStem's guarded plural rules instead. Both paths share the case +// and trim steps. func canonFold(s string) string { c := strings.ToLower(strings.TrimSpace(s)) if len(c) > 1 && strings.HasSuffix(c, "s") { @@ -749,15 +751,3 @@ func canonFold(s string) string { // add tag's separator rule, so type-hygiene behavior is unchanged by the shared // extraction. func canonType(s string) string { return canonFold(s) } - -// tagSeparators are the intra-tag separators (§4.1 tags are free-form): a hyphen, -// underscore, or space. Two tags that differ only in how a compound is joined -// (home-lab vs homelab, run book vs runbook) are one value spelled two ways. -var tagSeparators = strings.NewReplacer("-", "", "_", "", " ", "") - -// canonTag folds a `tags` value: the shared base fold, then separator-insensitive -// (-, _, space collapsed). The base fold runs first so a trailing 's' is dropped -// before separators are removed (design-patterns -> design-pattern -> -// designpattern), matching design-pattern's fold. Tags get this extra layer; -// types do not. -func canonTag(s string) string { return tagSeparators.Replace(canonFold(s)) } diff --git a/internal/okf/lint_taghygiene_test.go b/internal/okf/lint_taghygiene_test.go index 5789df7..e43768e 100644 --- a/internal/okf/lint_taghygiene_test.go +++ b/internal/okf/lint_taghygiene_test.go @@ -15,6 +15,7 @@ package okf import ( + "reflect" "strings" "testing" ) @@ -26,9 +27,10 @@ func lintDocTags(typ, title string, tags []string, body string) string { return "---\ntype: " + typ + "\ntitle: " + title + "\ntags: " + tl + "\n---\n\n# " + title + "\n\n" + body + "\n" } -// The fold table is the contract. canonFold is the shared base fold used by both -// type-hygiene and tag-hygiene (case, trim, single trailing 's'). canonTag layers -// separator-insensitivity (-, _, space) on top of canonFold, for TAGS ONLY. +// The fold tables are the contract. canonFold is the type fold (case, trim, +// single trailing 's'). Tags fold through tagSurface (case, trim, separators) +// and tagKeys (KStem's guarded plural rules, validated against the bundle's own +// tag vocabulary). func TestCanonFold_SharedBaseFold(t *testing.T) { cases := []struct{ in, want string }{ {"Concept", "concept"}, @@ -49,38 +51,91 @@ func TestCanonFold_SharedBaseFold(t *testing.T) { } } -func TestCanonTag_SeparatorInsensitive(t *testing.T) { +func TestTagSurface_SeparatorInsensitive(t *testing.T) { cases := []struct{ in, want string }{ {"Wine", "wine"}, - {"wine", "wine"}, - {"runbook", "runbook"}, - {"runbooks", "runbook"}, // trailing 's' - {"run-book", "runbook"}, // hyphen stripped - {"run_book", "runbook"}, // underscore stripped - {"Run Book", "runbook"}, // space stripped + case - {"Play Book", "playbook"}, // space stripped + case - {"playbook", "playbook"}, - {"home-lab", "homelab"}, // separator-only collision - {"homelab", "homelab"}, - {"design-patterns", "designpattern"}, // separator + trailing 's' - {"design-pattern", "designpattern"}, - // The -is / -us / -ss class must NOT lose its trailing letters: only a - // single trailing 's' is dropped, and none of these have a bare one. - {"hormesis", "hormesi"}, // -is: 's' dropped once, still distinct from any sibling - {"hysteresis", "hysteresi"}, - {"css", "cs"}, - {"gpt-oss", "gptos"}, - {"blast-radius", "blastradiu"}, - {"freshness", "freshnes"}, + {" wine ", "wine"}, + {"runbooks", "runbooks"}, // no suffix is touched at this layer + {"run-book", "runbook"}, // hyphen + {"run_book", "runbook"}, // underscore + {"Run Book", "runbook"}, // space + case + {"ci/cd", "cicd"}, // slash + {"node.js", "nodejs"}, // full stop between letters (UAX #29) + {"asp.net", "aspnet"}, + {".net", ".net"}, // a leading full stop is kept: .net is not net + {"v1.2", "v1.2"}, // a full stop between digits is kept: v1.2 is not v12 + {"c++", "c++"}, + {"-", ""}, } for _, c := range cases { - if got := canonTag(c.in); got != c.want { - t.Errorf("canonTag(%q) = %q, want %q", c.in, got, c.want) + if got := tagSurface(c.in); got != c.want { + t.Errorf("tagSurface(%q) = %q, want %q", c.in, got, c.want) } } } -// canonTag must NOT change the type path. Types still fold with canonType +// KStem's plural candidates, in order, with its guards: not letters-only, two +// letters or fewer, invariant forms, and a plain 's' after <= 3 letters, a double +// 's', or 'ous' produce no candidate. +func TestTagPluralCandidates_KStemRules(t *testing.T) { + cases := []struct { + in string + want []string + }{ + {"policies", []string{"policie", "policy"}}, + {"patches", []string{"patche", "patch"}}, + {"processes", []string{"process"}}, // double 's' before "es": no "-e" candidate + {"caches", []string{"cache", "cach"}}, + {"runbooks", []string{"runbook"}}, + {"nodejs", []string{"nodej"}}, // only ever used if "nodej" is itself a tag + {"aws", nil}, // plain 's' after <= 3 letters + {"ops", nil}, + {"ios", nil}, + {"js", nil}, // two letters + {"k8s", nil}, // not letters-only + {"news", nil}, // Porter2 invariant form + {"atlas", nil}, // Porter2 invariant form + {"class", nil}, // double 's' + {"famous", nil}, // 'ous' + {"wine", nil}, // no final 's' + } + for _, c := range cases { + if got := tagPluralCandidates(c.in); !reflect.DeepEqual(got, c.want) { + t.Errorf("tagPluralCandidates(%q) = %q, want %q", c.in, got, c.want) + } + } +} + +// tagKeys folds only onto an attested spelling, groups by connected component, +// and is independent of input order. +func TestTagKeys_AttestedFold(t *testing.T) { + raws := []string{"policies", "policy", "caches", "cache", "nodejs", "node.js", "news", "new", "aws", "aw", "Wine", "wine", "lonely-plurals"} + keys := tagKeys(raws) + for _, p := range [][2]string{{"policies", "policy"}, {"caches", "cache"}, {"nodejs", "node.js"}, {"Wine", "wine"}} { + if keys[p[0]] != keys[p[1]] { + t.Errorf("%q and %q must share a key; got %q / %q", p[0], p[1], keys[p[0]], keys[p[1]]) + } + } + for _, p := range [][2]string{{"news", "new"}, {"aws", "aw"}} { + if keys[p[0]] == keys[p[1]] { + t.Errorf("%q and %q must NOT share a key; both got %q", p[0], p[1], keys[p[0]]) + } + } + // No attested singular: the plural keeps its own surface form. + if keys["lonely-plurals"] != "lonelyplurals" { + t.Errorf("unattested plural must not be stemmed; got %q", keys["lonely-plurals"]) + } + // Order independence: reversed input, identical keys. + rev := make([]string, len(raws)) + for i, r := range raws { + rev[len(raws)-1-i] = r + } + if got := tagKeys(rev); !reflect.DeepEqual(got, keys) { + t.Errorf("tagKeys must not depend on input order:\n%v\n%v", keys, got) + } +} + +// The tag fold must NOT change the type path. Types still fold with canonType // (== canonFold), which is separator-SENSITIVE. Proven by table: a hyphenated // and an unhyphenated type do NOT collapse under the type fold. func TestCanonType_UnchangedBySeparatorRule(t *testing.T) { @@ -103,6 +158,11 @@ func TestLint_TagHygiene_Positive(t *testing.T) { {"plural", "runbook", "runbooks"}, {"separator-hyphen", "run-book", "runbook"}, {"separator-space", "Play Book", "playbook"}, + {"plural-es", "patch", "patches"}, + {"plural-sibilant-es", "process", "processes"}, + {"plural-ies", "policy", "policies"}, + {"separator-slash", "ci/cd", "cicd"}, + {"separator-dot", "node.js", "nodejs"}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { @@ -140,20 +200,9 @@ func TestLint_TagHygiene_MessageCountsAndSort(t *testing.T) { if len(th) != 1 { t.Fatalf("expected one folded tag-hygiene finding, got %+v", th) } - msg := th[0].Message - // Variants sorted ascending: run-book, runbook, runbooks. - iRunBook := strings.Index(msg, "run-book") - iRunbook := strings.Index(msg, "runbook ") // trailing space or paren after - iRunbooks := strings.Index(msg, "runbooks") - if iRunBook < 0 || iRunbook < 0 || iRunbooks < 0 { - t.Fatalf("message must name all three variants: %q", msg) - } - if iRunBook >= iRunbook || iRunbook >= iRunbooks { - t.Fatalf("variants must be sorted (run-book, runbook, runbooks): %q", msg) - } - // Per-node counts present: each variant is on exactly one node. - if !strings.Contains(msg, "(1 node)") && !strings.Contains(msg, "1 node") { - t.Fatalf("message must carry per-node counts: %q", msg) + const want = "tag-hygiene: near-duplicate tag values likely refer to one tag: run-book (1 node), runbook (1 node), runbooks (1 node)" + if th[0].Message != want { + t.Fatalf("tag-hygiene message:\n got: %q\nwant: %q", th[0].Message, want) } } @@ -167,6 +216,18 @@ func TestLint_TagHygiene_Negative(t *testing.T) { {"version-digit", "v1", "v2"}, {"oauth-digit", "oauth1", "oauth2"}, {"distinct-words", "oncall", "incident"}, + {"leading-dot", ".net", "net"}, // a leading full stop is not a word-internal separator + // Each pair below folded together under the previous bare trailing-'s' + // rule; KStem's guards keep them apart. + {"invariant-news", "new", "news"}, + {"short-ops", "op", "ops"}, + {"short-aws", "aw", "aws"}, + {"short-ios", "io", "ios"}, + {"short-dns", "dn", "dns"}, + {"short-bus", "bu", "bus"}, + {"two-letter-js", "j", "js"}, + {"digit-k8s", "k8", "k8s"}, + {"invariant-atlas", "atla", "atlas"}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { @@ -195,25 +256,6 @@ func TestLint_TagHygiene_SingleTagManyNodesNoFinding(t *testing.T) { } } -// The -is/-us/-ss digraph class (real-corpus measurement: 65 such tags, zero -// collisions) must each be silent — guards the trailing-'s' rule without needing -// a stop-list. Each planted on a distinct node with an unrelated sibling. -func TestLint_TagHygiene_DigraphClassSilent(t *testing.T) { - digraphs := []string{"hormesis", "hysteresis", "css", "freshness", "blast-radius", "gpt-oss"} - for _, d := range digraphs { - t.Run(d, func(t *testing.T) { - b := mkLintBundle(t, map[string]string{ - "index.md": "---\ntype: Index\ntitle: Index\n---\n\n# Index\n\n- [A](a.md)\n- [B](b.md)\n", - "a.md": lintDocTags("Concept", "A", []string{d}, "Body."), - "b.md": lintDocTags("Concept", "B", []string{"kubernetes"}, "Body."), - }) - if n := len(findingsFor(Lint(b, LintOptions{}), "tag-hygiene")); n != 0 { - t.Fatalf("digraph tag %q must not collide with an unrelated sibling; got %d findings", d, n) - } - }) - } -} - // The shared-fold extraction must leave type-hygiene byte-identical. This pins // the exact message string the check emitted before the refactor, proving the // type path did not move when canonType became a thin canonFold wrapper. diff --git a/internal/okf/tagfold.go b/internal/okf/tagfold.go new file mode 100644 index 0000000..12aa59c --- /dev/null +++ b/internal/okf/tagfold.go @@ -0,0 +1,158 @@ +// 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 okf + +import ( + "strings" + "unicode" +) + +// tagSurface is the context-free half of the tag fold: lower-cased, trimmed, +// and separator-insensitive. A hyphen, underscore, space, or slash is dropped +// wherever it appears (home-lab = homelab, ci/cd = cicd). A full stop is dropped +// only between two letters, where Unicode UAX #29 treats it as word-internal +// (node.js = nodejs); elsewhere it is kept, so `.net` stays apart from `net` and +// `v1.2` from `v12`. No suffix is touched here—plural folding needs the bundle's +// vocabulary (see tagKeys). +func tagSurface(s string) string { + r := []rune(strings.ToLower(strings.TrimSpace(s))) + var b strings.Builder + for i, c := range r { + switch c { + case '-', '_', ' ', '/': + continue + case '.': + if i > 0 && i < len(r)-1 && unicode.IsLetter(r[i-1]) && unicode.IsLetter(r[i+1]) { + continue + } + } + b.WriteRune(c) + } + return b.String() +} + +// tagInvariant is the Snowball English (Porter2) stemmer's list of invariant +// exceptional forms: words that look inflected but are left as-is. It is what +// keeps `news` from folding onto `new`. +var tagInvariant = map[string]bool{ + "sky": true, "news": true, "howe": true, "atlas": true, "cosmos": true, "bias": true, "andes": true, +} + +// tagPluralCandidates returns the singular forms KStem's plural() would try for +// a surface form, in KStem's order (Lucene KStemmer.java, derived from the UMass +// CIIR KStemmer). Its guards are what short tags need: +// +// - a word that is not letters-only is never stemmed (k8s, v1, oauth2); +// - a word of two letters or fewer is never stemmed (js); +// - `-ies` tries `-ie`, then `-y`; +// - `-es` tries dropping the `s` (unless a double `s` precedes it), then `es`; +// - a plain final `s` is dropped only when the word is longer than three +// letters and does not end in `ss` or `ous` (aws, ops, ios, dns stay whole). +// +// KStem chooses among candidates with a dictionary lookup; tagKeys uses the +// bundle's own tag vocabulary for that. +func tagPluralCandidates(w string) []string { + n := len(w) + if n <= 2 || tagInvariant[w] || !strings.HasSuffix(w, "s") { + return nil + } + for _, c := range w { + if !unicode.IsLetter(c) { + return nil + } + } + switch { + case strings.HasSuffix(w, "ies"): + return []string{w[:n-1], w[:n-3] + "y"} + case strings.HasSuffix(w, "es"): + j := n - 3 // the letter before "es" + var out []string + if j > 0 && !(w[j] == 's' && w[j-1] == 's') { + out = append(out, w[:n-1]) + } + return append(out, w[:n-2]) + case n > 3 && w[n-2] != 's' && !strings.HasSuffix(w, "ous"): + return []string{w[:n-1]} + } + return nil +} + +// tagKeys maps every raw tag value in raws to its canonical key. Two values +// share a key when their surface forms are equal, or when one's surface form +// is a KStem plural candidate of the other's AND that candidate is itself a +// surface form in raws. Requiring the candidate to be attested in the bundle +// stands in for KStem's dictionary: a non-word stem (cach, nodej) can never +// become a key, and nothing is folded unless both spellings are present—which +// a near-duplicate finding needs anyway. +// +// Classes are connected components (lenses → lens → len joins all three when +// all three are tags), so the result depends only on the SET of values, never +// their order. The key is the component's shortest surface form, ties broken +// byte-wise; it is a grouping handle, not a display spelling. A value whose +// surface form is empty maps to "". +func tagKeys(raws []string) map[string]string { + parent := map[string]string{} + for _, r := range raws { + if s := tagSurface(r); s != "" { + parent[s] = s + } + } + find := func(x string) string { + for parent[x] != x { + x = parent[x] + } + return x + } + for s := range parent { + for _, c := range tagPluralCandidates(s) { + if _, ok := parent[c]; !ok { + continue + } + a, b := find(s), find(c) + if a != b { + if len(b) < len(a) || (len(b) == len(a) && b < a) { + a, b = b, a + } + parent[b] = a // the shorter, then byte-wise smaller, root wins + } + break + } + } + out := make(map[string]string, len(raws)) + for _, r := range raws { + if s := tagSurface(r); s != "" { + out[r] = find(s) + } else { + out[r] = "" + } + } + return out +} + +// bundleTagKeys is tagKeys over every tag value in the bundle (trimmed), the +// vocabulary both lint's tag-hygiene and analyze's clusters fold against. +func bundleTagKeys(b *Bundle) map[string]string { + seen := map[string]bool{} + var raws []string + for _, n := range b.Nodes { + for _, t := range nodeTags(n) { + if t = strings.TrimSpace(t); t != "" && !seen[t] { + seen[t] = true + raws = append(raws, t) + } + } + } + return tagKeys(raws) +} From 2ca0898ba02b125f423037d74463bf33b605558f Mon Sep 17 00:00:00 2001 From: LGuichet Date: Sun, 4 Oct 2026 23:08:40 +0200 Subject: [PATCH 03/28] =?UTF-8?q?=F0=9F=90=9B=20fix(index):=20tolerate=20C?= =?UTF-8?q?RLF=20index.md=20in=20check=20and=20build?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On Windows with core.autocrlf=true a fresh clone checks index.md out as CRLF, and `index check` reported every index stale although the content was identical, because it compared bytes with the LF render. - index check compares with CRLF folded to LF; any other difference is still drift. - index build keeps the line endings of the index.md it replaces: an all-CRLF file stays CRLF, a new or mixed-ending file is written LF. The choice depends only on that file, so it is deterministic and git sees no whole-file ending flip. - the subdirectory-description parser strips CR before matching, so a CRLF index no longer captures the old shape suffix into the curator description (which made check fail and build double the suffix). Co-Authored-By: Claude Opus 5.5 --- internal/okf/index_eol_test.go | 175 +++++++++++++++++++++++++++++ internal/okf/reserved_lifecycle.go | 30 ++++- 2 files changed, 202 insertions(+), 3 deletions(-) create mode 100644 internal/okf/index_eol_test.go diff --git a/internal/okf/index_eol_test.go b/internal/okf/index_eol_test.go new file mode 100644 index 0000000..d4647e4 --- /dev/null +++ b/internal/okf/index_eol_test.go @@ -0,0 +1,175 @@ +// 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 okf + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// toCRLF rewrites a file with CRLF endings, as a Windows checkout with +// core.autocrlf=true would materialise it. +func toCRLF(t *testing.T, p string) { + t.Helper() + raw, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + crlf := strings.ReplaceAll(strings.ReplaceAll(string(raw), "\r\n", "\n"), "\n", "\r\n") + if err := os.WriteFile(p, []byte(crlf), 0o644); err != nil { + t.Fatal(err) + } +} + +func readFile(t *testing.T, p string) string { + t.Helper() + raw, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + return string(raw) +} + +func buildAndReload(t *testing.T, dir string) *Bundle { + t.Helper() + b, err := Load(dir) + if err != nil { + t.Fatal(err) + } + if err := WriteIndex(b); err != nil { + t.Fatal(err) + } + b, err = Load(dir) + if err != nil { + t.Fatal(err) + } + return b +} + +func TestUsesCRLF(t *testing.T) { + cases := []struct { + in string + want bool + }{ + {"", false}, + {"no newline", false}, + {"a\nb\n", false}, + {"a\r\nb\r\n", true}, + {"a\r\nb", true}, + {"a\r\nb\n", false}, // mixed falls back to LF + {"a\rb\r", false}, // bare CR is not a line ending we emit + } + for _, c := range cases { + if got := usesCRLF([]byte(c.in)); got != c.want { + t.Errorf("usesCRLF(%q) = %v, want %v", c.in, got, c.want) + } + } +} + +// A CRLF checkout of an LF-built index carries the same content, so index check +// must report it in sync — and must still catch real drift. +func TestIndexInSync_CRLFCheckoutIsInSync(t *testing.T) { + dir := t.TempDir() + _ = Scaffold(dir) + writeNode(t, dir, "wine/tannin.md", "Reference", "Tannin") + _ = buildAndReload(t, dir) + toCRLF(t, filepath.Join(dir, "index.md")) + toCRLF(t, filepath.Join(dir, "wine", "index.md")) + + b, _ := Load(dir) + if ok, diff := IndexInSync(b); !ok { + t.Errorf("CRLF checkout of a current index must be in sync; got: %s", diff) + } + writeNode(t, dir, "wine/acidity.md", "Reference", "Acidity") + b, _ = Load(dir) + if ok, _ := IndexInSync(b); ok { + t.Error("a CRLF index must still be reported stale after adding a node") + } +} + +// index build keeps a CRLF index CRLF, writes a brand-new index LF, and +// normalises a mixed-ending index to LF. +func TestWriteIndex_PreservesExistingLineEndings(t *testing.T) { + dir := t.TempDir() + _ = Scaffold(dir) + writeNode(t, dir, "wine/tannin.md", "Reference", "Tannin") + writeNode(t, dir, "beer/hops.md", "Reference", "Hops") + _ = buildAndReload(t, dir) + + root := filepath.Join(dir, "index.md") + wine := filepath.Join(dir, "wine", "index.md") + beer := filepath.Join(dir, "beer", "index.md") + toCRLF(t, root) + toCRLF(t, wine) + // beer/index.md: mixed — one CRLF line, the rest LF. + if err := os.WriteFile(beer, []byte(strings.Replace(readFile(t, beer), "\n", "\r\n", 1)), 0o644); err != nil { + t.Fatal(err) + } + writeNode(t, dir, "wine/acidity.md", "Reference", "Acidity") // forces a real wine/ change + writeNode(t, dir, "cider/apple.md", "Reference", "Apple") // a brand-new index + + b := buildAndReload(t, dir) + if ok, diff := IndexInSync(b); !ok { + t.Fatalf("index must be in sync right after build; got: %s", diff) + } + for _, p := range []string{root, wine} { + if got := readFile(t, p); !usesCRLF([]byte(got)) { + t.Errorf("%s: CRLF index must stay CRLF after build; got %q", p, got) + } + } + if got := readFile(t, wine); !strings.Contains(got, "acidity.md") { + t.Errorf("wine/index.md must list the new node; got %q", got) + } + for _, p := range []string{beer, filepath.Join(dir, "cider", "index.md")} { + if got := readFile(t, p); strings.Contains(got, "\r") { + t.Errorf("%s: new or mixed-ending index must be written LF; got %q", p, got) + } + } +} + +// A curator-authored subdirectory description in a CRLF index survives a +// rebuild intact: the trailing CR must not defeat the shape-suffix strip, which +// would capture the old suffix into the description and double it. +func TestWriteIndex_CRLFKeepsSubdirDescriptionIdempotent(t *testing.T) { + dir := t.TempDir() + _ = Scaffold(dir) + writeNode(t, dir, "wine/tannin.md", "Reference", "Tannin") + _ = buildAndReload(t, dir) + + root := filepath.Join(dir, "index.md") + withDesc := strings.Replace(readFile(t, root), "](wine/)", "](wine/) - Grapes and more.", 1) + if err := os.WriteFile(root, []byte(withDesc), 0o644); err != nil { + t.Fatal(err) + } + toCRLF(t, root) + + b, _ := Load(dir) + if ok, diff := IndexInSync(b); !ok { + t.Fatalf("CRLF index with a curator description must be in sync; got: %s", diff) + } + b = buildAndReload(t, dir) + got := readFile(t, root) + if strings.Count(got, "(1 concept") != 1 { + t.Errorf("shape suffix must appear exactly once after rebuilding a CRLF index; got %q", got) + } + if !strings.Contains(got, " - Grapes and more. (1 concept") { + t.Errorf("curator description must be preserved; got %q", got) + } + if ok, diff := IndexInSync(b); !ok { + t.Errorf("index must be in sync after rebuild; got: %s", diff) + } +} diff --git a/internal/okf/reserved_lifecycle.go b/internal/okf/reserved_lifecycle.go index 4ac88cc..a81198a 100644 --- a/internal/okf/reserved_lifecycle.go +++ b/internal/okf/reserved_lifecycle.go @@ -15,6 +15,7 @@ package okf import ( + "bytes" "fmt" "os" "path" @@ -320,7 +321,7 @@ func preservedSubdirDescriptions(b *Bundle, dir string, opts IndexShapeOptions) if !ok || idx == nil { return out } - for _, line := range strings.Split(idx.Body, "\n") { + for _, line := range strings.Split(normalizeEOL(idx.Body), "\n") { m := subdirBulletRE.FindStringSubmatch(line) if m == nil { continue @@ -464,7 +465,14 @@ func WriteIndexWithOptions(b *Bundle, opts IndexShapeOptions) error { if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { //nolint:gosec // G301: shareable bundle content dir; 0o755 is intended return err } - if err := os.WriteFile(p, []byte(RenderDirIndexWithOptions(b, dir, opts)), 0o644); err != nil { //nolint:gosec // G306: a bundle index file is shareable content; 0o644 is intended + out := RenderDirIndexWithOptions(b, dir, opts) + // Keep the line endings of the index being replaced (see usesCRLF): a CRLF + // checkout (Windows, core.autocrlf=true) stays CRLF instead of flipping + // every line. A new or mixed-ending index gets the canonical LF. + if existing, err := os.ReadFile(p); err == nil && usesCRLF(existing) { //nolint:gosec // G304: reading the tool's own generated index file + out = strings.ReplaceAll(out, "\n", "\r\n") + } + if err := os.WriteFile(p, []byte(out), 0o644); err != nil { //nolint:gosec // G306: a bundle index file is shareable content; 0o644 is intended return err } } @@ -507,7 +515,9 @@ func IndexInSyncWithOptions(b *Bundle, opts IndexShapeOptions) (bool, string) { if err != nil { return false, fmt.Sprintf("%s is missing or unreadable; run `okfctl index build`", filepath.ToSlash(rel(b.Root, p))) } - if string(onDisk) != RenderDirIndexWithOptions(b, dir, opts) { + // Line endings are not content: a CRLF checkout of an LF-built index is + // in sync. Everything else is still compared byte for byte. + if normalizeEOL(string(onDisk)) != RenderDirIndexWithOptions(b, dir, opts) { return false, fmt.Sprintf("%s is out of date; run `okfctl index build` to regenerate", filepath.ToSlash(rel(b.Root, p))) } } @@ -524,6 +534,20 @@ func IndexInSyncWithOptions(b *Bundle, opts IndexShapeOptions) (bool, string) { return true, "" } +// normalizeEOL folds CRLF line endings to LF, the form RenderDirIndex emits. +func normalizeEOL(s string) string { + return strings.ReplaceAll(s, "\r\n", "\n") +} + +// usesCRLF reports whether every line break in src is CRLF (and there is at +// least one). Mixed endings, or none, report false so the writer falls back to +// LF. The decision depends only on the file being replaced, never on other +// files or on the machine running the tool. +func usesCRLF(src []byte) bool { + crlf := bytes.Count(src, []byte("\r\n")) + return crlf > 0 && crlf == bytes.Count(src, []byte("\n")) +} + // rel returns the bundle-relative form of an absolute path, best-effort (the // absolute path is used verbatim on failure, which only affects a report string). func rel(root, abs string) string { From 56384c8b2ab5da508cd5297d6ac1f5e87dcdb5cb Mon Sep 17 00:00:00 2001 From: LGuichet Date: Fri, 9 Oct 2026 11:44:45 +0200 Subject: [PATCH 04/28] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor(index):=20e?= =?UTF-8?q?xpose=20directory=20shape=20as=20a=20DirShape=20struct=20behind?= =?UTF-8?q?=20the=20=C2=A78=20index=20suffix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Lift the per-directory aggregation that `index build` renders as the subdirectory shape suffix (OKF §8 progressive disclosure) out of dirShape into a structured DirShape: own and subtree concept counts, the sorted distinct `type` values (§7.4 open vocabulary, kept as written), and the §4.1 shared tags with a truncation flag. Shape computes it for one directory and Shapes for every IndexDirs entry. dirShape now renders FROM the struct, so the index suffix and any other consumer (the PRD §6.1 "neighborhoods" view of `bundle info`) cannot drift apart. No behavior change to the rendered suffix. Tests cover own-vs-subtree counting, own-concept-only types and tags, tag-cap truncation, byte-equality between Shape and the rendered suffix, a build→validate round trip, and Shapes covering every index dir. --- internal/okf/index_shape.go | 46 +++------ internal/okf/neighborhoods.go | 81 +++++++++++++++ internal/okf/neighborhoods_test.go | 154 +++++++++++++++++++++++++++++ 3 files changed, 248 insertions(+), 33 deletions(-) create mode 100644 internal/okf/neighborhoods.go create mode 100644 internal/okf/neighborhoods_test.go diff --git a/internal/okf/index_shape.go b/internal/okf/index_shape.go index 17b1742..569a1b9 100644 --- a/internal/okf/index_shape.go +++ b/internal/okf/index_shape.go @@ -144,9 +144,10 @@ func sharedTagList(folded map[string]foldedTag, min, max int) ([]string, bool) { // dirShape returns the tool-owned shape suffix for a subdirectory entry (OKF §8 // progressive disclosure), as trailing parenthesised text with a leading space, // e.g. ` (37 concepts · Application, Concept, Map · shared tags: ux, layout) · 46 in subtree`. -// It aggregates over the child directory's OWN IMMEDIATE concept nodes (not the -// whole subtree): the count, the distinct types in full (sorted, §7.4 leaves the -// type vocabulary open so every type prints as-is), and the shared tags (§4.1). +// It renders the child's DirShape (see Shape), which aggregates over the child +// directory's OWN IMMEDIATE concept nodes (not the whole subtree): the count, +// the distinct types in full (sorted, §7.4 leaves the type vocabulary open so +// every type prints as-is), and the shared tags (§4.1). // The `· N in subtree` total is appended only when the child has content-bearing // descendants (subtree count > own count). Returns "" when disabled. // @@ -158,41 +159,20 @@ func dirShape(b *Bundle, childDir string, opts IndexShapeOptions) string { if !opts.Enabled { return "" } - - // Own immediate concepts of childDir. - ownPaths := conceptsIn(b, childDir) // sorted, deterministic - own := len(ownPaths) - - typeSet := map[string]bool{} - perNodeTags := make([][]string, 0, own) - for _, p := range ownPaths { - n := b.Nodes[p] - if t := strings.TrimSpace(n.Type()); t != "" { - typeSet[t] = true - } - perNodeTags = append(perNodeTags, nodeTags(n)) - } + s := Shape(b, childDir, opts) // Segment 1: the concept count (pluralized). - var segs []string - segs = append(segs, fmt.Sprintf("%d %s", own, pluralConcepts(own))) + segs := []string{fmt.Sprintf("%d %s", s.Own, pluralConcepts(s.Own))} // Segment 2: types in full, sorted, deduped. - if len(typeSet) > 0 { - types := make([]string, 0, len(typeSet)) - for t := range typeSet { - types = append(types, t) - } - sort.Strings(types) - segs = append(segs, strings.Join(types, ", ")) + if len(s.Types) > 0 { + segs = append(segs, strings.Join(s.Types, ", ")) } // Segment 3: shared tags (omitted entirely when none qualifies). - folded := foldTags(perNodeTags) - tags, truncated := sharedTagList(folded, opts.TagMin, opts.TagMax) - if len(tags) > 0 { - seg := "shared tags: " + strings.Join(tags, ", ") - if truncated { + if len(s.SharedTags) > 0 { + seg := "shared tags: " + strings.Join(s.SharedTags, ", ") + if s.TagsTruncated { seg += ", …" } segs = append(segs, seg) @@ -201,8 +181,8 @@ func dirShape(b *Bundle, childDir string, opts IndexShapeOptions) string { suffix := " (" + strings.Join(segs, " · ") + ")" // Subtree total: only when the child has deeper content-bearing dirs. - if sub := subtreeConceptCount(b, childDir); sub > own { - suffix += fmt.Sprintf(" · %d in subtree", sub) + if s.Subtree > s.Own { + suffix += fmt.Sprintf(" · %d in subtree", s.Subtree) } return suffix } diff --git a/internal/okf/neighborhoods.go b/internal/okf/neighborhoods.go new file mode 100644 index 0000000..7066459 --- /dev/null +++ b/internal/okf/neighborhoods.go @@ -0,0 +1,81 @@ +// 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 okf + +import ( + "sort" + "strings" +) + +// DirShape is the structured form of what lives under a bundle directory: how +// many concept nodes it holds directly and in its whole subtree, which `type` +// values its own concepts use, and which tags recur across them. It is the data +// behind the subdirectory shape suffix that `index build` writes (OKF §8 +// progressive disclosure; see dirShape), exposed so a summary command can print +// per-neighborhood counts and vocabulary (PRD §6.1 lists "neighborhoods" as part +// of `bundle info`) without re-walking the tree or re-deriving the rules. Because +// dirShape renders FROM this struct, the index suffix and any other consumer +// cannot drift apart. +type DirShape struct { + Dir string // bundle-relative slash path; "" is the bundle root + Own int // concept nodes directly in Dir + Subtree int // concept nodes in Dir and every descendant (>= Own) + // Types are the distinct `type` values of Dir's own concepts, sorted. §7.4 + // leaves the vocabulary open, so every value is kept exactly as written. + Types []string + // SharedTags are the §4.1 tags carried by >= opts.TagMin of Dir's own + // concepts, folded case-insensitively and shown in their dominant casing, + // most-shared-first with an alphabetical tie-break, capped at opts.TagMax. + SharedTags []string + // TagsTruncated reports that more tags qualified than opts.TagMax allowed. + TagsTruncated bool +} + +// Shape computes the DirShape of dir over the loaded bundle, using opts' tag +// threshold and cap (opts.Enabled is ignored: the data exists whether or not an +// index renders it). Output is deterministic. +func Shape(b *Bundle, dir string, opts IndexShapeOptions) DirShape { + ownPaths := conceptsIn(b, dir) // sorted, deterministic + s := DirShape{Dir: dir, Own: len(ownPaths), Subtree: subtreeConceptCount(b, dir)} + + typeSet := map[string]bool{} + perNodeTags := make([][]string, 0, len(ownPaths)) + for _, p := range ownPaths { + n := b.Nodes[p] + if t := strings.TrimSpace(n.Type()); t != "" { + typeSet[t] = true + } + perNodeTags = append(perNodeTags, nodeTags(n)) + } + for t := range typeSet { + s.Types = append(s.Types, t) + } + sort.Strings(s.Types) + + s.SharedTags, s.TagsTruncated = sharedTagList(foldTags(perNodeTags), opts.TagMin, opts.TagMax) + return s +} + +// Shapes returns the DirShape of every directory that carries an index.md +// (IndexDirs), in the same sorted order: the bundle-wide "index of indices" +// view. +func Shapes(b *Bundle, opts IndexShapeOptions) []DirShape { + dirs := IndexDirs(b) + out := make([]DirShape, 0, len(dirs)) + for _, d := range dirs { + out = append(out, Shape(b, d, opts)) + } + return out +} diff --git a/internal/okf/neighborhoods_test.go b/internal/okf/neighborhoods_test.go new file mode 100644 index 0000000..e3b6e39 --- /dev/null +++ b/internal/okf/neighborhoods_test.go @@ -0,0 +1,154 @@ +// 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 okf + +import ( + "reflect" + "strings" + "testing" +) + +// shapeFixture builds the bundle every test here reads: +// +// wine/tannin.md Reference tags: tannin, structure +// wine/oak.md Reference tags: oak, structure +// wine/red/nebbiolo.md Grape tags: grape, tannin +// wine/red/barolo.md Reference tags: grape +// lifting/squat.md Playbook (no tags) +// +// so `wine` has 2 own concepts and 4 in its subtree; among wine's OWN concepts +// only `structure` is shared, while `tannin` reaches two nodes only by counting +// the subtree. +func shapeFixture(t *testing.T) *Bundle { + t.Helper() + dir := t.TempDir() + _ = Scaffold(dir) + writeNodeTags(t, dir, "wine/tannin.md", "Reference", "Tannin", []string{"tannin", "structure"}) + writeNodeTags(t, dir, "wine/oak.md", "Reference", "Oak", []string{"oak", "structure"}) + writeNodeTags(t, dir, "wine/red/nebbiolo.md", "Grape", "Nebbiolo", []string{"grape", "tannin"}) + writeNodeTags(t, dir, "wine/red/barolo.md", "Reference", "Barolo", []string{"grape"}) + writeNodeTags(t, dir, "lifting/squat.md", "Playbook", "Squat", nil) + b, err := Load(dir) + if err != nil { + t.Fatal(err) + } + return b +} + +// TestShape_CountsOwnAndSubtree pins the two counts: Own is the directory's +// direct concepts, Subtree includes every descendant; a leaf directory has both +// equal; the root's subtree is the whole bundle. +func TestShape_CountsOwnAndSubtree(t *testing.T) { + b := shapeFixture(t) + opts := DefaultShapeOptions() + if s := Shape(b, "wine", opts); s.Own != 2 || s.Subtree != 4 { + t.Errorf("wine: own=%d subtree=%d, want 2/4", s.Own, s.Subtree) + } + if s := Shape(b, "wine/red", opts); s.Own != 2 || s.Subtree != 2 { + t.Errorf("wine/red (leaf): own=%d subtree=%d, want 2/2", s.Own, s.Subtree) + } + if s := Shape(b, "", opts); s.Own != 0 || s.Subtree != 5 { + t.Errorf("root: own=%d subtree=%d, want 0/5", s.Own, s.Subtree) + } +} + +// TestShape_TypesAndSharedTagsAreOwnConcepts pins the vocabulary rules, which +// are the index suffix's (§8): types and tags come from the directory's OWN +// concepts. Positive control: `structure`, on both own concepts, is shared. +// Negative controls: `oak` (one node) is not; `tannin` and the `Grape` type, +// which only the subtree carries, do not leak up. +func TestShape_TypesAndSharedTagsAreOwnConcepts(t *testing.T) { + s := Shape(shapeFixture(t), "wine", DefaultShapeOptions()) + if want := []string{"Reference"}; !reflect.DeepEqual(s.Types, want) { + t.Errorf("types = %v, want %v", s.Types, want) + } + if want := []string{"structure"}; !reflect.DeepEqual(s.SharedTags, want) { + t.Errorf("shared tags = %v, want %v", s.SharedTags, want) + } + if s.TagsTruncated { + t.Errorf("one qualifying tag under the default cap must not report truncation") + } +} + +// TestShape_TagCapReportsTruncation pins that TagMax caps SharedTags +// most-shared-first and that the cut is reported, so a consumer can mark it +// the way the index suffix does with its ellipsis. +func TestShape_TagCapReportsTruncation(t *testing.T) { + b := shapeFixture(t) + opts := DefaultShapeOptions() + opts.TagMax = 1 + // wine/red's own concepts share only `grape`; widen the pool by lowering + // the threshold so two tags qualify and the cap of 1 must cut one. + opts.TagMin = 1 + s := Shape(b, "wine/red", opts) + if want := []string{"grape"}; !reflect.DeepEqual(s.SharedTags, want) { + t.Errorf("shared tags = %v, want %v (most-shared first)", s.SharedTags, want) + } + if !s.TagsTruncated { + t.Errorf("cap below the qualifying count must report truncation") + } +} + +// TestShape_IsTheIndexSuffixData pins parity with the §8 index: the suffix +// `index build` writes for a subdirectory is rendered from Shape, so the data a +// summary command reads and the text a reader sees cannot disagree. +func TestShape_IsTheIndexSuffixData(t *testing.T) { + b := shapeFixture(t) + opts := DefaultShapeOptions() + if got, want := dirShape(b, "wine", opts), " (2 concepts · Reference · shared tags: structure) · 4 in subtree"; got != want { + t.Errorf("wine suffix\n got: %q\nwant: %q", got, want) + } + root := RenderDirIndex(b, "") + if !strings.Contains(root, "* [Wine](wine/) (2 concepts · Reference · shared tags: structure) · 4 in subtree\n") { + t.Errorf("root index must carry wine's shape; got:\n%s", root) + } +} + +// TestWriteIndex_WithShape_ValidatesAndStaysInSync pins the two properties the +// shape must not break: the generated tree still passes the spec floor (§8 index +// rules are untouched—the shape lives in entry text), and `index check` is +// clean immediately after `index build` (deterministic output). +func TestWriteIndex_WithShape_ValidatesAndStaysInSync(t *testing.T) { + b := shapeFixture(t) + if err := WriteIndex(b); err != nil { + t.Fatal(err) + } + b2, err := Load(b.Root) + if err != nil { + t.Fatal(err) + } + if f := Validate(b2); len(f) != 0 { + t.Errorf("index tree with shapes must validate clean; findings: %v", f) + } + if ok, report := IndexInSync(b2); !ok { + t.Errorf("index check must be clean right after build; report: %s", report) + } +} + +// TestShapes_CoversEveryIndexDir pins that Shapes enumerates exactly IndexDirs, +// in order—the contract a summary command relies on. +func TestShapes_CoversEveryIndexDir(t *testing.T) { + b := shapeFixture(t) + got := Shapes(b, DefaultShapeOptions()) + dirs := IndexDirs(b) + if len(got) != len(dirs) { + t.Fatalf("Shapes returned %d entries for %d index dirs", len(got), len(dirs)) + } + for i, d := range dirs { + if got[i].Dir != d { + t.Errorf("Shapes[%d].Dir = %q, want %q", i, got[i].Dir, d) + } + } +} From 946fad261e6e2c7112bb629fa5ab1d21f1fc2626 Mon Sep 17 00:00:00 2001 From: LGuichet Date: Fri, 9 Oct 2026 12:26:51 +0200 Subject: [PATCH 05/28] =?UTF-8?q?=F0=9F=90=9B=20fix(bundle):=20read=20the?= =?UTF-8?q?=20=C2=A712=20okf=5Fversion=20marker=20on=20the=20bundle-root?= =?UTF-8?q?=20index.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OKF §12 defines where a bundle declares the version it targets: an `okf_version` key in the bundle-root index.md frontmatter block. Load read the version only from the .okf sidecar, which is okfctl's own pin and not part of the spec, so a spec-conforming bundle carrying the marker and no sidecar was reported as SpecVersion whatever it declared. index build already resolved the marker first (bundleRootOkfVersion); load and build disagreed about the same bundle. Resolve Bundle.OkfVersion in the order index build writes the marker: the root-index marker, else the sidecar, else SpecVersion. Only the root index counts (§12 permits the marker nowhere else). The declared string is reported as declared: per §12 an unrecognised version is consumed best-effort, never rejected. Tests pin both directions: marker-only, marker-over-sidecar, bare scalar and unrecognised values are read (positive); a nested index.md marker, a blank marker and a sidecar-only bundle leave the result unchanged (negative). The conformance suite gains the consumer half of the §12 round trip: the marker index build preserves is the one Load reads back. --- internal/okf/bundle.go | 41 +++++++++++---- internal/okf/bundle_test.go | 88 ++++++++++++++++++++++++++++++++ internal/okf/conformance_test.go | 74 +++++++++++++++++++++++++++ internal/okf/sidecar_test.go | 5 +- 4 files changed, 195 insertions(+), 13 deletions(-) diff --git a/internal/okf/bundle.go b/internal/okf/bundle.go index f117e65..b0354ae 100644 --- a/internal/okf/bundle.go +++ b/internal/okf/bundle.go @@ -84,7 +84,7 @@ type Bundle struct { Root string Nodes map[string]*Node // concept nodes only (excludes reserved) Reserved map[string]*Node // index.md, log.md - OkfVersion string // okf_version from the bundle's .okf, or SpecVersion if absent + OkfVersion string // the declared version: §12 root-index marker, else .okf sidecar, else SpecVersion // SkippedDirs holds the bundle-relative slash paths of directories pruned // from the walk by the default skip list (see DefaultSkipDirs), sorted. // Empty when WithNoIgnore was passed or nothing matched. The CLI announces @@ -184,20 +184,39 @@ func Load(root string, opts ...LoadOption) (*Bundle, error) { } sort.Strings(b.SkippedDirs) } - b.OkfVersion = readOkfVersion(root) + b.OkfVersion = b.readOkfVersion() b.buildEdges() return b, nil } -// readOkfVersion returns the okf_version declared in the bundle's .okf file, or -// SpecVersion if the file is absent or carries no (non-empty) okf_version key. -// The .okf is a small YAML document (e.g. "okf_version: 0.1"); a missing or -// unreadable file is not an error here — Load stays lenient and falls back to -// the build's version. It reads through the generalized sidecar parser -// (readOkfSidecar) so a bundle carrying other sidecar keys — e.g. a §9.2 -// `templates` reference — does not change the version read. -func readOkfVersion(root string) string { - if v := strings.TrimSpace(readOkfSidecar(root)["okf_version"]); v != "" { +// readOkfVersion resolves the OKF version the loaded bundle declares, in the +// same order `index build` writes the marker (bundleRootOkfVersion), so load +// and build never disagree about which version a bundle targets: +// +// 1. `okf_version` in the bundle-ROOT index.md frontmatter — the declaration +// §12 defines: "Bundles MAY declare the version they target with +// okf_version: "0.2" in a bundle-root index.md frontmatter block". Only +// the root index counts; §12 permits the marker nowhere else, so a nested +// index.md carrying the key is not consulted. +// 2. Else `okf_version` in the .okf sidecar, okfctl's own pin (not part of +// the spec). Read through the generalized sidecar parser (readOkfSidecar) +// so other sidecar keys — e.g. a §9.2 `templates` reference — do not +// change the version read. +// 3. Else SpecVersion. A missing or unreadable sidecar is not an error here — +// Load stays lenient and falls back to the build's version. +// +// Whatever is declared is reported as declared: per §12 a consumer that does +// not understand the version attempts best-effort consumption, it never +// refuses the bundle, so nothing here validates the string. +func (b *Bundle) readOkfVersion() string { + if idx, ok := b.Reserved["index.md"]; ok && idx != nil { + if v, ok := idx.Frontmatter["okf_version"]; ok { + if s := strings.TrimSpace(scalarString(v)); s != "" { + return s + } + } + } + if v := strings.TrimSpace(readOkfSidecar(b.Root)["okf_version"]); v != "" { return v } return SpecVersion diff --git a/internal/okf/bundle_test.go b/internal/okf/bundle_test.go index 2d8198d..dd5de0b 100644 --- a/internal/okf/bundle_test.go +++ b/internal/okf/bundle_test.go @@ -111,6 +111,94 @@ func TestLoad_MissingDotOkfFallsBackToSpecVersion(t *testing.T) { } } +// TestLoad_RootIndexOkfVersionMarker pins §12: "Bundles MAY declare the version +// they target with okf_version: "0.2" in a bundle-root index.md frontmatter +// block". That marker is the spec's declaration; the .okf sidecar is okfctl's +// own pin. Load resolves marker, then sidecar, then SpecVersion — the order +// index build already uses when it writes the marker (bundleRootOkfVersion). +func TestLoad_RootIndexOkfVersionMarker(t *testing.T) { + load := func(t *testing.T, files map[string]string) *Bundle { + t.Helper() + dir := t.TempDir() + for rel, content := range files { + writeFile(t, dir, rel, content) + } + if _, ok := files["log.md"]; !ok { + writeFile(t, dir, "log.md", "# Log\n") + } + b, err := Load(dir) + if err != nil { + t.Fatalf("Load: %v", err) + } + return b + } + + // Positive controls: the §12 marker is read, and it wins. + t.Run("marker only, no sidecar", func(t *testing.T) { + b := load(t, map[string]string{ + "index.md": "---\nokf_version: \"0.1\"\n---\n# KB\n", + }) + if b.OkfVersion != "0.1" { + t.Errorf("§12: OkfVersion = %q, want 0.1 (the root index marker)", b.OkfVersion) + } + }) + t.Run("marker and sidecar disagree: marker wins", func(t *testing.T) { + b := load(t, map[string]string{ + ".okf": "okf_version: 0.9\n", + "index.md": "---\nokf_version: \"0.1\"\n---\n# KB\n", + }) + if b.OkfVersion != "0.1" { + t.Errorf("§12: OkfVersion = %q, want 0.1 (marker over sidecar)", b.OkfVersion) + } + }) + t.Run("bare scalar marker reads as its text", func(t *testing.T) { + b := load(t, map[string]string{ + "index.md": "---\nokf_version: 0.1\n---\n# KB\n", + }) + if b.OkfVersion != "0.1" { + t.Errorf("OkfVersion = %q, want 0.1 (YAML float rendered as declared)", b.OkfVersion) + } + }) + t.Run("unrecognised declared version is reported, not rejected", func(t *testing.T) { + b := load(t, map[string]string{ + "index.md": "---\nokf_version: \"7.3\"\n---\n# KB\n", + }) + if b.OkfVersion != "7.3" { + t.Errorf("§12 best-effort: OkfVersion = %q, want 7.3", b.OkfVersion) + } + }) + + // Negative controls: nothing that is not the §12 marker is promoted. + t.Run("nested index marker is not the bundle version", func(t *testing.T) { + b := load(t, map[string]string{ + "index.md": "# KB\n", + "wine/index.md": "---\nokf_version: \"0.1\"\n---\n# Wine\n", + "wine/a.md": "---\ntype: Reference\ntitle: A\n---\nbody\n", + }) + if b.OkfVersion != SpecVersion { + t.Errorf("§12 permits the marker only on the bundle root; OkfVersion = %q, want %q", b.OkfVersion, SpecVersion) + } + }) + t.Run("empty marker falls through to the sidecar", func(t *testing.T) { + b := load(t, map[string]string{ + ".okf": "okf_version: 0.9\n", + "index.md": "---\nokf_version: \"\"\n---\n# KB\n", + }) + if b.OkfVersion != "0.9" { + t.Errorf("OkfVersion = %q, want 0.9 (sidecar when the marker is blank)", b.OkfVersion) + } + }) + t.Run("sidecar only is unchanged", func(t *testing.T) { + b := load(t, map[string]string{ + ".okf": "okf_version: 0.9\n", + "index.md": "# KB\n", + }) + if b.OkfVersion != "0.9" { + t.Errorf("OkfVersion = %q, want 0.9 (the sidecar pin)", b.OkfVersion) + } + }) +} + func writeFile(t *testing.T, dir, rel, content string) { t.Helper() p := filepath.Join(dir, filepath.FromSlash(rel)) diff --git a/internal/okf/conformance_test.go b/internal/okf/conformance_test.go index d5c230f..2ff79e2 100644 --- a/internal/okf/conformance_test.go +++ b/internal/okf/conformance_test.go @@ -219,6 +219,80 @@ func TestConformance_GeneratedIndexPreservesOkfVersionMarker(t *testing.T) { } } +// TestConformance_LoadReadsRootIndexOkfVersionMarker closes the §12 loop from +// the consumer side: the marker that TestConformance_GeneratedIndexPreservesOkfVersionMarker +// proves `index build` preserves must also be what Load reports, with or +// without okfctl's .okf sidecar — otherwise the tool writes a declaration it +// then ignores when reading the same bundle back. +func TestConformance_LoadReadsRootIndexOkfVersionMarker(t *testing.T) { + mk := func(t *testing.T, sidecar bool, marker string) string { + t.Helper() + dir := t.TempDir() + if sidecar { + if err := os.WriteFile(filepath.Join(dir, ".okf"), []byte("okf_version: "+SpecVersion+"\n"), 0o644); err != nil { + t.Fatal(err) + } + } + index := "# Knowledge Base\n" + if marker != "" { + index = "---\nokf_version: \"" + marker + "\"\n---\n\n" + index + } + if err := os.WriteFile(filepath.Join(dir, "index.md"), []byte(index), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "log.md"), []byte(logHeader+logPlaceholder), 0o644); err != nil { + t.Fatal(err) + } + writeNode(t, dir, "wine/tannin.md", "Reference", "Tannin") + return dir + } + + // Positive: a spec-only bundle (marker, no sidecar) reports what it declares + // and still validates clean — §12 says consume best-effort, never refuse. + dir := mk(t, false, "0.1") + b, err := Load(dir) + if err != nil { + t.Fatal(err) + } + if b.OkfVersion != "0.1" { + t.Errorf("§12: marker-only bundle OkfVersion = %q, want 0.1", b.OkfVersion) + } + if f := Validate(b); len(f) != 0 { + t.Errorf("§12: marker-only bundle must validate clean; got findings: %v", f) + } + + // Round trip: after index build the marker survives (§12) and Load still + // reads the same value — producer and consumer agree. + if err := WriteIndex(b); err != nil { + t.Fatalf("WriteIndex: %v", err) + } + b2, err := Load(dir) + if err != nil { + t.Fatal(err) + } + if b2.OkfVersion != "0.1" { + t.Errorf("§12: after index build OkfVersion = %q, want 0.1", b2.OkfVersion) + } + + // Negative: a sidecar-only bundle (okfctl's own pin, no §12 marker) keeps + // reporting the sidecar, and a bundle with neither keeps SpecVersion — the + // change adds a source, it does not move the existing ones. + b3, err := Load(mk(t, true, "")) + if err != nil { + t.Fatal(err) + } + if b3.OkfVersion != SpecVersion { + t.Errorf("sidecar-only bundle OkfVersion = %q, want %q", b3.OkfVersion, SpecVersion) + } + b4, err := Load(mk(t, false, "")) + if err != nil { + t.Fatal(err) + } + if b4.OkfVersion != SpecVersion { + t.Errorf("no declaration: OkfVersion = %q, want fallback %q", b4.OkfVersion, SpecVersion) + } +} + // TestConformance_ValidateFlagsGeneratedIndexRegression is the guard the parent // defect lacked, expressed at the Validate seam: the exact non-conformant shape // the old generator emitted (`type: Index`) must be FLAGGED by validate. This diff --git a/internal/okf/sidecar_test.go b/internal/okf/sidecar_test.go index c1ccb44..e187dbf 100644 --- a/internal/okf/sidecar_test.go +++ b/internal/okf/sidecar_test.go @@ -25,7 +25,8 @@ import ( func TestReadOkfVersion_UnchangedWithBothKeys(t *testing.T) { dir := t.TempDir() writeFile(t, dir, ".okf", "okf_version: 0.9\ntemplates: ../tpl\n") - if got := readOkfVersion(dir); got != "0.9" { + // No root index loaded, so only the sidecar leg of readOkfVersion is exercised. + if got := (&Bundle{Root: dir}).readOkfVersion(); got != "0.9" { t.Errorf("readOkfVersion = %q, want 0.9 (version read must survive a templates key)", got) } } @@ -36,7 +37,7 @@ func TestReadOkfVersion_UnchangedWithBothKeys(t *testing.T) { func TestReadOkfVersion_TemplatesKeyOnlyStillFallsBack(t *testing.T) { dir := t.TempDir() writeFile(t, dir, ".okf", "templates: ../tpl\n") - if got := readOkfVersion(dir); got != SpecVersion { + if got := (&Bundle{Root: dir}).readOkfVersion(); got != SpecVersion { t.Errorf("readOkfVersion = %q, want fallback %q", got, SpecVersion) } } From 27324e2091541bb36cf0b04d9073c6f6e04f3744 Mon Sep 17 00:00:00 2001 From: LGuichet Date: Mon, 12 Oct 2026 02:03:50 +0200 Subject: [PATCH 06/28] =?UTF-8?q?=F0=9F=93=9D=20docs(spec):=20write-safety?= =?UTF-8?q?=20audit=E2=80=94atomic,=20confined,=20injection-free=20writes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/specs/2026-10-12-write-safety-audit.md | 156 ++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 docs/specs/2026-10-12-write-safety-audit.md diff --git a/docs/specs/2026-10-12-write-safety-audit.md b/docs/specs/2026-10-12-write-safety-audit.md new file mode 100644 index 0000000..9ea13f7 --- /dev/null +++ b/docs/specs/2026-10-12-write-safety-audit.md @@ -0,0 +1,156 @@ +# fix(write)—write-safety audit: atomic, confined, injection-free writes + +**Status:** Approved (design) · **Owner:** Casey West · **License:** Apache-2.0 +**Source of truth:** OKF `SPEC.md` **v0.2** (upstream +`GoogleCloudPlatform/knowledge-catalog`, header confirmed `**Version 0.2**`)—§3 +(a bundle is a directory tree), §3.1 (reserved filenames), §4 / §4.1 (the +frontmatter block is delimited by `---` on its own line; unknown keys are +preserved), §6.1 (a `/`-leading link is bundle-root-relative), §8 (index +files), §9 (log files), §12 (versioning, `okf_version`). No new spec +behavior—this hardens how okfctl writes, it adds no `validate` rule. +**Base:** `next` @ `634eeb1` **Branch:** `fix/write-safety-audit` + +## Problem + +okfctl writes bundle content—nodes, indexes, the log, the `.okf` sidecar—plus +its own state (the search vector store, the user config, the migration plan). +Three properties are each assumed somewhere and enforced nowhere in one place: + +- **Atomic:** a write lands whole or not at all. A crash (or a full disk) + mid-`os.WriteFile` truncates the target and leaves a half-written node, + index, log, or vector store behind. +- **Confined:** a user-supplied path resolves inside the bundle root (§3: a + bundle *is* its directory tree). `..`, an OS-absolute path, and a symlink + that points out of the root are refused. +- **No frontmatter injection:** a value written into a YAML (or line-keyed) + block goes through an encoder, so a value carrying `\n---\n` or a newline + cannot close the §4 block early or open a new key. + +## Audit—path × property + +Every non-test call to `os.WriteFile` / `os.Create` / `os.Rename` / +`os.CreateTemp`, plus the user-path entry points that reach them. "Safe" means +the property holds today and the code is left alone; "gap" is fixed by this +change, one commit per gap. + +| write path (entry point → writer) | atomic | confined | no injection | +|---|---|---|---| +| `node new` → `okf.NewNodeFromTemplate` (`authoring.go`) | **gap**—`os.WriteFile` | `..` safe (lexical check); **gap**—a symlinked directory inside the root that points outside is followed | safe—`yaml.Marshal` of a `yaml.Node`; heading cut at the first newline (body, not frontmatter) | +| `node edit` → `$EDITOR` + `okf.TouchModifiedFile` (`cmd/node.go`, `frontmatter_edit.go`) | **gap**—`os.WriteFile` (both branches) | **gap**—`filepath.Join(bundle, p)` with no check: `node edit ../x` opens and rewrites a file outside the root | safe—re-encodes through `yaml.Encoder`; the no-frontmatter branch writes a fixed-shape RFC3339 stamp | +| `node refresh` → `okf.RefreshApply` → `TouchModifiedFile` | gap (shared with `node edit`, one fix) | safe—path comes from `b.Nodes` (loader-enumerated) | safe (as above) | +| `node mv` → `okf.ApplyMove` (`mutate.go`) | the move is one `os.Rename` (safe); **gap**—inbound link rewrites use `os.WriteFile` | **gap**—`new` is never confined: `node mv a ../../evil` moves the node out of the root | **gap**—the rewritten link text is the destination path verbatim; a destination containing a line break lands raw in the file (and a link inside a frontmatter value is rewritten too) | +| `node rm` → `os.Remove` (`cmd/node.go`) | safe—a single unlink | safe—only a path `PlanRemoveOrphans` found in `b.Nodes` is removed | n/a | +| `node promote --name` → `okf.PromotePlan` / `PromoteApply` (`promote.go`) | **gap**—link rewrites and the new concept file use `os.WriteFile` | **gap**—`--name ../../x` escapes; `--name a/b` targets a directory that does not exist; `--name log` would create a reserved `log.md` concept (§3.1) | **gap**—the basename flows into rewritten link text (same vector as `node mv`) | +| `migrate apply` → `okf.MigrateApply` (`migrate.go`) | **gap**—node writes use `os.WriteFile` | **gap**—`plan.nodes[].path` is read from the hand-editable JSON plan and joined unchecked | safe—`renderMigratedNode` edits a `yaml.Node` and re-encodes | +| `migrate apply` → `bumpOkfSidecar` (`.okf`) | **gap**—`os.WriteFile` | safe—fixed `/.okf` | **gap**—`"okf_version: " + plan.target_version` is concatenated into the line-keyed sidecar; a target containing a newline smuggles extra sidecar keys (e.g. `templates:`) | +| `migrate apply` → `bumpRootIndexMarker` (root `index.md`, §8/§12) | **gap**—`os.WriteFile` | safe—fixed `/index.md` | safe—`setScalar` + `yaml.Encoder` | +| `migrate` (plan phase) → plan JSON (`cmd/migrate.go`) | **gap**—`os.WriteFile` | n/a—`--plan` is an explicit output path the user names, not bundle content | safe—`json.MarshalIndent` | +| `init` → `okf.Scaffold` (`reserved.go`) | **gap**—`os.WriteFile` per file | n/a—`dir` *is* the root being created | safe—fixed content (`SpecVersion` is a constant) | +| `index build` / auto-maintenance → `okf.WriteIndexWithOptions` (`reserved_lifecycle.go`) | **gap**—`os.WriteFile` | safe—every path derives from `IndexDirs(b)` | safe—the only frontmatter is the §12 `okf_version` marker, emitted with `%q` (a double-quoted, fully escaped scalar that YAML reads back as one string); pinned by a new fuzz target | +| `log append` / auto-maintenance → `okf.AppendLog` (§9) | **gap**—`os.WriteFile` | safe—fixed `/log.md` | **gap**—the message is flattened at the first `\n` only; a lone `\r` is a CommonMark line ending, so `msg\r## 1999-01-01` forges a §9 date heading | +| `config set` → `okfconfig.Save` | **gap**—`os.WriteFile` | n/a—fixed user-config path | safe—`json.MarshalIndent` | +| `plugin install` → `plugin.copyExecutable` | safe—`CreateTemp` in the destination dir + `Rename` | safe—the installed name is `filepath.Base(source)`, so it cannot leave the plugin dir | n/a | +| `okfctl-search index` → `search.(*Store).Save` | **gap**—`os.WriteFile` | n/a—fixed `indexPath(dir)` | safe—`json.MarshalIndent` | +| `connect` → `git clone` (`gitsource.go`) | n/a—git owns the checkout | n/a—the destination is the user's explicit target | n/a | +| `cmd/gendocs` (dev tool) | noted, not hardened | noted | noted | + +The roadmap names `--section` targets; no such flag exists on `next`, so there +is nothing to confine yet. `node link` (Increment 4) is the first planned +consumer and reuses the helpers below. + +## Design + +### Two helpers in one neutral package—`internal/fsutil` + +The vector store (`internal/search`), the user config (`internal/okfconfig`), +and `cmd` all need the atomic writer, and none should import `internal/okf` for +it, so both helpers live in a tiny leaf package with no okfctl imports. + +```go +// internal/fsutil/atomicwrite.go +func WriteFileAtomic(path string, data []byte, perm os.FileMode) error + +// internal/fsutil/confine.go +var ErrEscapesRoot = errors.New("path escapes the bundle root") +func ResolveInRoot(root, rel string) (string, error) +``` + +**`WriteFileAtomic`** writes `data` to a temp file created in the target's own +directory (same filesystem, so the rename is atomic), `Sync`s it, sets the +mode, closes it, and `Rename`s it over `path`. Any failure removes the temp +file and leaves `path` untouched. It mirrors `os.WriteFile` semantics where they +matter: an existing target keeps its permission bits (`perm` applies only on +create), and a target that is a symlink is written *through* (the link's target +is replaced; the link survives). The temp name is `..tmp-`—it +never ends in `.md`, so a crash-orphaned temp is never loaded as a node. + +**`ResolveInRoot`** turns a user-supplied bundle-relative path into an absolute +path inside `root`, or refuses it: + +- empty, or the root itself (`.`) → refused; +- a control character (C0 or DEL) anywhere → refused. A path is written into + link text by `node mv` / `node promote`; a line break there is the + injection vector in the table above; +- an OS-absolute path with a volume (`C:\x`, `\\server\share`) → refused; +- a leading `/` is **kept as bundle-root-relative**, matching §6.1's + `/`-absolute link form and the behavior `node new` already pins + (`TestNewNode_RejectsPathEscape`): `/deep/x.md` resolves to `/deep/x.md`; +- after `Clean`, any `..` that climbs above the root → `ErrEscapesRoot`; +- the deepest *existing* ancestor of the result is `EvalSymlinks`-resolved and + must still sit inside the resolved root, so a symlinked directory pointing out + of the bundle is refused while an in-bundle symlink is fine. + +It returns the lexical absolute path (not the symlink-resolved one), so callers +write where the user pointed. The check is a pre-write gate, not a kernel-level +`openat` confinement: a symlink swapped in between the check and the write is +out of scope for a local, single-user CLI. + +### Call-site swaps (one commit per gap) + +- `WriteFileAtomic` replaces every `os.WriteFile` marked **gap** above. +- `ResolveInRoot` gates `NewNodeFromTemplate` (replacing its lexical check), + `node edit` (before the editor launches), `ApplyMove` (`old` and `new`), + `PromotePlan` / `PromoteApply` (the destination), and `MigrateApply` + (each `plan.nodes[].path`). +- `PromotePlan` additionally refuses a `--name` that is not a single path + segment, or that would produce a reserved filename (§3.1). +- `bumpOkfSidecar` refuses a `target_version` containing a control character + (the sidecar is line-keyed; there is no encoder to route through). +- `AppendLog` flattens the message at the first CommonMark line ending + (`\n` or `\r`), not just `\n` (§9 date headings stay unforgeable). + +### Fuzz targets—write paths that round-trip through a parser + +Extending `2026-08-08-fuzz-untrusted-parsers.md`: each target writes through the +real writer, reads the result back through the real parser, and asserts the +injection invariant. All are registered in the CI `fuzz` job. + +| target | writer → parser | invariants | +|---|---|---| +| `FuzzNewNodeFrontmatter` | `NewNode(type, title)` → `ParseFrontmatter` | never panics; on success the frontmatter keys are exactly `type`, `created`, `modified` (+ `title` when non-blank)—no smuggled key | +| `FuzzTouchModifiedRoundTrip` | `TouchModifiedFile` → `ParseFrontmatter` | never panics; on error the file is byte-identical (atomicity); on success `modified` is present, every pre-existing key survives (§4.1 preserve unknown keys), and the body is unchanged | +| `FuzzRootIndexMarker` | `rootFrontmatter` (§12 marker) → `ParseFrontmatter` | the block holds exactly one key, `okf_version`; for valid UTF-8 its value round-trips exactly | +| `FuzzAppendLog` | `AppendLog` → CommonMark line split | a fresh log has exactly one `## ` heading—today's (§9) | + +## Controls + +- **Positive:** `node new ../x`, `node edit ../x`, `node mv a ../../x`, + `node promote --name ../x`, a plan node path `../x`, a symlinked directory + escaping the root, and a destination with a newline are each refused with + nothing written outside the root; a plan `target_version` of + `0.2\ntemplates: evil` is refused; a log message `a\r## 1999-01-01` forges no + heading; an interrupted atomic write leaves the original bytes. +- **Negative:** `a/b/c.md` writes at `/a/b/c.md`; `/deep/x.md` stays + bundle-root-relative; an in-bundle symlinked directory is accepted; a title + containing `---` in prose (`Before --- after`, and one with a real + `\n---\n`) writes a node whose frontmatter has only the expected keys and + whose title round-trips; a v0.1 fixture (legacy `timestamp`, body + `# Citations`) migrates and touches exactly as before. + +## Non-goals + +- No new `validate` or `lint` rule; no change to what a bundle may contain. +- No `openat2`/`os.Root`-style kernel confinement (residual TOCTOU is noted + above). +- `Scaffold` overwriting an existing `index.md`/`log.md` in a non-empty dir is + pre-existing `init` behavior, not a write-safety property; left alone. From 329f2d395863bf4d79e5453d779766aa1600a61c Mon Sep 17 00:00:00 2001 From: LGuichet Date: Mon, 12 Oct 2026 02:08:55 +0200 Subject: [PATCH 07/28] =?UTF-8?q?=E2=9C=A8=20feat(fsutil):=20atomic=20file?= =?UTF-8?q?=20writer=20and=20bundle-root=20confinement=20helper?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/fsutil/atomicwrite.go | 102 ++++++++++++++ internal/fsutil/confine.go | 153 +++++++++++++++++++++ internal/fsutil/fsutil_test.go | 236 +++++++++++++++++++++++++++++++++ 3 files changed, 491 insertions(+) create mode 100644 internal/fsutil/atomicwrite.go create mode 100644 internal/fsutil/confine.go create mode 100644 internal/fsutil/fsutil_test.go diff --git a/internal/fsutil/atomicwrite.go b/internal/fsutil/atomicwrite.go new file mode 100644 index 0000000..23d6122 --- /dev/null +++ b/internal/fsutil/atomicwrite.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 +// +// 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 holds okfctl's write-safety primitives: an atomic file +// writer and a bundle-root confinement check. It is a leaf package (standard +// library only) so every writer—bundle content in internal/okf, the vector +// store in internal/search, the user config in internal/okfconfig, and cmd—can +// share one implementation without importing each other. +package fsutil + +import ( + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" +) + +// rename is the final step of WriteFileAtomic; a variable only so a test can +// inject a failure and prove the target is left untouched. +var rename = os.Rename + +// WriteFileAtomic writes data to path so that a reader (or a crash) observes +// either the old content or the new content, never a truncated mix. It writes +// a temp file in path's own directory (same filesystem, so the rename is +// atomic), syncs and closes it, then renames it over path. On any error the +// temp file is removed and path is left exactly as it was. +// +// It keeps os.WriteFile's observable semantics where they matter: +// - perm applies only when path does not exist; an existing file keeps its +// permission bits. +// - a path that is a symlink is written through: the link's target is +// replaced and the link itself survives. +// +// The temp name is "..tmp-"—it never ends in ".md", so an +// orphan left by a hard crash is never loaded as a bundle node. +func WriteFileAtomic(path string, data []byte, perm os.FileMode) error { + target := path + if fi, err := os.Lstat(path); err == nil && fi.Mode()&fs.ModeSymlink != 0 { + resolved, rerr := filepath.EvalSymlinks(path) + if rerr != nil { + return fmt.Errorf("resolve symlink %s: %w", path, rerr) + } + target = resolved + } + mode := perm + if fi, err := os.Stat(target); err == nil { + if !fi.Mode().IsRegular() { + return fmt.Errorf("write %s: not a regular file", path) + } + mode = fi.Mode().Perm() + } else if !errors.Is(err, fs.ErrNotExist) { + return fmt.Errorf("stat %s: %w", path, err) + } + + dir, base := filepath.Split(target) + if dir == "" { + dir = "." + } + tmp, err := os.CreateTemp(dir, "."+base+".tmp-*") + if err != nil { + return fmt.Errorf("write %s: %w", path, err) + } + tmpName := tmp.Name() + committed := false + defer func() { + if !committed { + _ = os.Remove(tmpName) + } + }() + + if _, err := tmp.Write(data); err != nil { + _ = tmp.Close() + return fmt.Errorf("write %s: %w", path, err) + } + if err := tmp.Sync(); err != nil { + _ = tmp.Close() + return fmt.Errorf("sync %s: %w", path, err) + } + if err := tmp.Close(); err != nil { + return fmt.Errorf("close %s: %w", path, err) + } + if err := os.Chmod(tmpName, mode); err != nil { + return fmt.Errorf("chmod %s: %w", path, err) + } + if err := rename(tmpName, target); err != nil { + return fmt.Errorf("write %s: %w", path, err) + } + committed = true + return nil +} diff --git a/internal/fsutil/confine.go b/internal/fsutil/confine.go new file mode 100644 index 0000000..535e83f --- /dev/null +++ b/internal/fsutil/confine.go @@ -0,0 +1,153 @@ +// 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" + "fmt" + "os" + "path/filepath" + "strings" +) + +// ErrEscapesRoot reports a path that would resolve outside the bundle root: +// a ".." that climbs above it, an OS-absolute path with a volume, or a +// symlinked directory that points out of it. +var ErrEscapesRoot = errors.New("path escapes the bundle root") + +// ErrInvalidPath reports a path that names no writable location in the bundle: +// empty, the root itself, or one carrying a control character. +var ErrInvalidPath = errors.New("invalid bundle path") + +// ResolveInRoot confines a user-supplied, bundle-relative path to root and +// returns its absolute location, or refuses it. It is the single confinement +// gate for every command that writes to a path the user typed (node new, node +// edit, node mv, node promote, migrate apply) and is meant to be reused by any +// future one. +// +// OKF §3 defines a bundle as its directory tree, so a write must land inside +// it. rel is refused when it: +// - is empty or cleans to the root itself (ErrInvalidPath); +// - contains a control character—C0 or DEL (ErrInvalidPath). Paths are +// echoed into link text by node mv / node promote, so a line break here +// would be written raw into a node; +// - carries a volume name, e.g. `C:\x` or `\\server\share` (ErrEscapesRoot); +// - climbs above root with ".." after cleaning (ErrEscapesRoot); +// - passes, via its deepest existing ancestor, through a symlink that +// resolves outside root (ErrEscapesRoot). A symlink that stays inside +// the bundle is fine. +// +// A leading "/" (or, on Windows, "\") is bundle-root-relative, matching the +// §6.1 "/"-absolute link form: "/a/b.md" resolves to /a/b.md. +// +// The returned path is the lexical one (root joined with the cleaned rel), +// not the symlink-resolved one, so callers write where the user pointed. The +// check runs before the write; a symlink swapped in between check and write +// is outside the threat model of a local, single-user CLI. +func ResolveInRoot(root, rel string) (string, error) { + if rel == "" { + return "", fmt.Errorf("%w: empty path", ErrInvalidPath) + } + for _, r := range rel { + if r < 0x20 || r == 0x7f { + return "", fmt.Errorf("%w: %q contains a control character", ErrInvalidPath, rel) + } + } + native := filepath.FromSlash(rel) + if filepath.VolumeName(native) != "" { + return "", fmt.Errorf("%w: %s", ErrEscapesRoot, rel) + } + native = strings.TrimLeft(native, string(filepath.Separator)+"/") + clean := filepath.Clean(native) + if clean == "." || native == "" { + return "", fmt.Errorf("%w: %q names the bundle root", ErrInvalidPath, rel) + } + if clean == ".." || strings.HasPrefix(clean, ".."+string(filepath.Separator)) { + return "", fmt.Errorf("%w: %s", ErrEscapesRoot, rel) + } + + absRoot, err := filepath.Abs(root) + if err != nil { + return "", fmt.Errorf("resolve bundle root %s: %w", root, err) + } + joined := filepath.Join(absRoot, clean) + + realRoot, err := filepath.EvalSymlinks(absRoot) + if err != nil { + return "", fmt.Errorf("resolve bundle root %s: %w", root, err) + } + // Resolve the deepest ancestor that exists; everything below it is new + // and, being ".."-free after Clean, cannot climb back out. + existing := joined + for { + if _, err := os.Lstat(existing); err == nil { + break + } + parent := filepath.Dir(existing) + if parent == existing { + break + } + existing = parent + } + realExisting, err := filepath.EvalSymlinks(existing) + if err != nil { + return "", fmt.Errorf("%w: %s (%v)", ErrEscapesRoot, rel, err) + } + if !within(realRoot, realExisting) { + return "", fmt.Errorf("%w: %s resolves through a symlink to %s", ErrEscapesRoot, rel, realExisting) + } + // filepath.EvalSymlinks does not follow Windows directory junctions (mount + // points), which an unprivileged user can create, so also check every + // existing component below the root: any link-like entry (symlink or other + // reparse point) must itself resolve inside the bundle. + if existing != absRoot { + suffix, err := filepath.Rel(absRoot, existing) + if err != nil { + return "", fmt.Errorf("%w: %s", ErrEscapesRoot, rel) + } + cur := absRoot + for _, part := range strings.Split(suffix, string(filepath.Separator)) { + cur = filepath.Join(cur, part) + fi, err := os.Lstat(cur) + if err != nil { + return "", fmt.Errorf("%w: %s (%v)", ErrEscapesRoot, rel, err) + } + if fi.Mode()&(os.ModeSymlink|os.ModeIrregular) == 0 { + continue + } + target, err := os.Readlink(cur) + if err != nil { + return "", fmt.Errorf("%w: %s passes through an unresolvable link %s", ErrEscapesRoot, rel, cur) + } + if !filepath.IsAbs(target) { + target = filepath.Join(filepath.Dir(cur), target) + } + realTarget, err := filepath.EvalSymlinks(target) + if err != nil || !within(realRoot, realTarget) { + return "", fmt.Errorf("%w: %s passes through a link to %s", ErrEscapesRoot, rel, target) + } + } + } + return joined, nil +} + +// within reports whether path (already link-resolved) is root or below it. +func within(root, path string) bool { + inside, err := filepath.Rel(root, path) + if err != nil || filepath.IsAbs(inside) { + return false + } + return inside != ".." && !strings.HasPrefix(inside, ".."+string(filepath.Separator)) +} diff --git a/internal/fsutil/fsutil_test.go b/internal/fsutil/fsutil_test.go new file mode 100644 index 0000000..62becba --- /dev/null +++ b/internal/fsutil/fsutil_test.go @@ -0,0 +1,236 @@ +// 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" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func noTemps(t *testing.T, dir string) { + t.Helper() + ents, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + for _, e := range ents { + if strings.Contains(e.Name(), ".tmp-") { + t.Errorf("leftover temp file %s", e.Name()) + } + } +} + +func TestWriteFileAtomic_CreatesAndReplaces(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "a.md") + if err := WriteFileAtomic(p, []byte("one"), 0o644); err != nil { + t.Fatal(err) + } + if err := WriteFileAtomic(p, []byte("two"), 0o644); err != nil { + t.Fatal(err) + } + got, _ := os.ReadFile(p) + if string(got) != "two" { + t.Fatalf("content = %q, want two", got) + } + noTemps(t, dir) +} + +// The defining property: the write replaces the file by rename, so a reader +// holding the old inode (here, a hard link) never sees a partial or new body. +func TestWriteFileAtomic_ReplacesByRename(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "a.md") + if err := os.WriteFile(p, []byte("old"), 0o644); err != nil { + t.Fatal(err) + } + link := filepath.Join(dir, "held") + if err := os.Link(p, link); err != nil { + t.Skipf("hard links unsupported: %v", err) + } + if err := WriteFileAtomic(p, []byte("new"), 0o644); err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(link); string(got) != "old" { + t.Fatalf("old inode was written in place: %q", got) + } + if got, _ := os.ReadFile(p); string(got) != "new" { + t.Fatalf("target = %q, want new", got) + } +} + +func TestWriteFileAtomic_FailureLeavesTargetIntact(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "a.md") + if err := os.WriteFile(p, []byte("original"), 0o644); err != nil { + t.Fatal(err) + } + rename = func(string, string) error { return errors.New("injected") } + t.Cleanup(func() { rename = os.Rename }) + if err := WriteFileAtomic(p, []byte("replacement"), 0o644); err == nil { + t.Fatal("expected the injected failure") + } + if got, _ := os.ReadFile(p); string(got) != "original" { + t.Fatalf("target changed on failure: %q", got) + } + noTemps(t, dir) +} + +func TestWriteFileAtomic_MissingDirFails(t *testing.T) { + p := filepath.Join(t.TempDir(), "nope", "a.md") + if err := WriteFileAtomic(p, []byte("x"), 0o644); err == nil { + t.Fatal("expected an error writing into a missing directory") + } +} + +func TestWriteFileAtomic_KeepsExistingMode(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("POSIX permission bits are not modelled on Windows") + } + p := filepath.Join(t.TempDir(), "cfg.json") + if err := os.WriteFile(p, []byte("{}"), 0o600); err != nil { + t.Fatal(err) + } + if err := WriteFileAtomic(p, []byte("{1}"), 0o644); err != nil { + t.Fatal(err) + } + fi, _ := os.Stat(p) + if fi.Mode().Perm() != 0o600 { + t.Fatalf("mode = %v, want 0600 kept", fi.Mode().Perm()) + } +} + +func TestWriteFileAtomic_WritesThroughSymlink(t *testing.T) { + dir := t.TempDir() + real := filepath.Join(dir, "real.md") + if err := os.WriteFile(real, []byte("old"), 0o644); err != nil { + t.Fatal(err) + } + link := filepath.Join(dir, "link.md") + if err := os.Symlink(real, link); err != nil { + t.Skipf("symlinks unsupported: %v", err) + } + if err := WriteFileAtomic(link, []byte("new"), 0o644); err != nil { + t.Fatal(err) + } + if fi, _ := os.Lstat(link); fi.Mode()&os.ModeSymlink == 0 { + t.Fatal("symlink was replaced by a regular file") + } + if got, _ := os.ReadFile(real); string(got) != "new" { + t.Fatalf("link target = %q, want new", got) + } +} + +func TestResolveInRoot_Accepts(t *testing.T) { + root := t.TempDir() + if err := os.MkdirAll(filepath.Join(root, "a", "b"), 0o755); err != nil { + t.Fatal(err) + } + for in, want := range map[string]string{ + "a/b/c.md": filepath.Join(root, "a", "b", "c.md"), + "new/dir/x.md": filepath.Join(root, "new", "dir", "x.md"), + "/deep/x.md": filepath.Join(root, "deep", "x.md"), // §6.1 "/" = bundle root + "a/../a/b/c.md": filepath.Join(root, "a", "b", "c.md"), + "./a/b/c.md": filepath.Join(root, "a", "b", "c.md"), + "a/b/--- note.md": filepath.Join(root, "a", "b", "--- note.md"), + } { + got, err := ResolveInRoot(root, in) + if err != nil { + t.Errorf("ResolveInRoot(%q): %v", in, err) + continue + } + if got != want { + t.Errorf("ResolveInRoot(%q) = %q, want %q", in, got, want) + } + } +} + +func TestResolveInRoot_Refuses(t *testing.T) { + root := t.TempDir() + cases := map[string]error{ + "": ErrInvalidPath, + ".": ErrInvalidPath, + "/": ErrInvalidPath, + "a/..": ErrInvalidPath, + "a\nb.md": ErrInvalidPath, + "a\rb.md": ErrInvalidPath, + "a\x7fb.md": ErrInvalidPath, + "..": ErrEscapesRoot, + "../x.md": ErrEscapesRoot, + "../../x.md": ErrEscapesRoot, + "sub/../../x.md": ErrEscapesRoot, + "/../x.md": ErrEscapesRoot, + "a/b/../../../x": ErrEscapesRoot, + } + for in, want := range cases { + _, err := ResolveInRoot(root, in) + if !errors.Is(err, want) { + t.Errorf("ResolveInRoot(%q) err = %v, want %v", in, err, want) + } + } + if runtime.GOOS == "windows" { + for _, in := range []string{`..\x.md`, `C:\Windows\x`, `\\srv\share\x`, `C:x.md`} { + if _, err := ResolveInRoot(root, in); !errors.Is(err, ErrEscapesRoot) { + t.Errorf("ResolveInRoot(%q) err = %v, want ErrEscapesRoot", in, err) + } + } + } +} + +func TestResolveInRoot_SymlinkEscapeRefused(t *testing.T) { + outside := t.TempDir() + root := t.TempDir() + if err := linkDir(outside, filepath.Join(root, "out")); err != nil { + t.Skipf("symlinks unsupported: %v", err) + } + for _, in := range []string{"out/x.md", "out/new/dir/x.md", "out"} { + if _, err := ResolveInRoot(root, in); !errors.Is(err, ErrEscapesRoot) { + t.Errorf("ResolveInRoot(%q) err = %v, want ErrEscapesRoot", in, err) + } + } +} + +func TestResolveInRoot_InBundleSymlinkAccepted(t *testing.T) { + root := t.TempDir() + if err := os.MkdirAll(filepath.Join(root, "real"), 0o755); err != nil { + t.Fatal(err) + } + if err := linkDir(filepath.Join(root, "real"), filepath.Join(root, "alias")); err != nil { + t.Skipf("symlinks unsupported: %v", err) + } + got, err := ResolveInRoot(root, "alias/x.md") + if err != nil { + t.Fatalf("in-bundle symlink refused: %v", err) + } + if want := filepath.Join(root, "alias", "x.md"); got != want { + t.Fatalf("got %q, want lexical %q", got, want) + } +} + +// linkDir links a directory: a symlink where the OS allows it, otherwise (an +// unprivileged Windows account) a directory junction, which needs no +// privilege and is followed by filepath.EvalSymlinks just the same. +func linkDir(target, link string) error { + err := os.Symlink(target, link) + if err == nil || runtime.GOOS != "windows" { + return err + } + return exec.Command("cmd", "/c", "mklink", "/J", link, target).Run() //nolint:gosec // G204: test-only fixture setup +} From 2f43dbb1ac26d5426948b46df9ee97721c4bb896 Mon Sep 17 00:00:00 2001 From: LGuichet Date: Mon, 12 Oct 2026 02:16:46 +0200 Subject: [PATCH 08/28] =?UTF-8?q?=F0=9F=90=9B=20fix(okf):=20write=20nodes,?= =?UTF-8?q?=20indexes,=20the=20log=20and=20the=20.okf=20sidecar=20atomical?= =?UTF-8?q?ly?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every bundle writer in internal/okf (node new, TouchModifiedFile, node mv and node promote link rewrites, migrate apply, Scaffold, index build, log append) used os.WriteFile, which truncates the target in place: a crash or a full disk mid-write left a half-written node behind. They now go through fsutil.WriteFileAtomic (temp file in the same directory, sync, rename). Each rewrite path is pinned by a hard-link test that fails on an in-place write; a v0.1 node (legacy timestamp, body # Citations) still migrates and touches as before. --- internal/okf/authoring.go | 3 +- internal/okf/frontmatter_edit.go | 5 +- internal/okf/migrate.go | 7 +- internal/okf/mutate.go | 4 +- internal/okf/promote.go | 6 +- internal/okf/reserved.go | 4 +- internal/okf/reserved_lifecycle.go | 8 +- internal/okf/writesafety_test.go | 213 +++++++++++++++++++++++++++++ 8 files changed, 237 insertions(+), 13 deletions(-) create mode 100644 internal/okf/writesafety_test.go diff --git a/internal/okf/authoring.go b/internal/okf/authoring.go index 11bb921..3aa19cb 100644 --- a/internal/okf/authoring.go +++ b/internal/okf/authoring.go @@ -20,6 +20,7 @@ import ( "path/filepath" "strings" + "github.com/cwest/okfctl/internal/fsutil" "gopkg.in/yaml.v3" ) @@ -134,7 +135,7 @@ func NewNodeFromTemplate(root, relPath, typ, title string, t Template) (string, } // A bundle node is a shareable knowledge document (committed to git, read by // others); 0o644 is the intended, conventional mode for content files. - if err := os.WriteFile(abs, []byte(sb.String()), 0o644); err != nil { //nolint:gosec // G306: shareable bundle content file + if err := fsutil.WriteFileAtomic(abs, []byte(sb.String()), 0o644); err != nil { //nolint:gosec // G306: shareable bundle content file return "", err } return abs, nil diff --git a/internal/okf/frontmatter_edit.go b/internal/okf/frontmatter_edit.go index d884303..34c4a09 100644 --- a/internal/okf/frontmatter_edit.go +++ b/internal/okf/frontmatter_edit.go @@ -20,6 +20,7 @@ import ( "os" "time" + "github.com/cwest/okfctl/internal/fsutil" "gopkg.in/yaml.v3" ) @@ -51,7 +52,7 @@ func TouchModifiedFile(abs string, at time.Time) error { out.WriteString("---\nmodified: " + stamp + "\n---\n") out.Write(raw) // A bundle node is a shareable knowledge document; 0o644 is intended. - return os.WriteFile(abs, out.Bytes(), 0o644) //nolint:gosec // G306: shareable bundle content file + return fsutil.WriteFileAtomic(abs, out.Bytes(), 0o644) //nolint:gosec // G306: shareable bundle content file } var doc yaml.Node @@ -80,7 +81,7 @@ func TouchModifiedFile(abs string, at time.Time) error { // so the only bytes that change are inside the frontmatter block. out.Write(rawAfter) // A bundle node is a shareable knowledge document; 0o644 is intended. - return os.WriteFile(abs, out.Bytes(), 0o644) //nolint:gosec // G306: shareable bundle content file + return fsutil.WriteFileAtomic(abs, out.Bytes(), 0o644) //nolint:gosec // G306: shareable bundle content file } // frontmatterMapping unwraps a decoded yaml document to its top-level mapping diff --git a/internal/okf/migrate.go b/internal/okf/migrate.go index 88dfaca..8218658 100644 --- a/internal/okf/migrate.go +++ b/internal/okf/migrate.go @@ -23,6 +23,7 @@ import ( "strings" "time" + "github.com/cwest/okfctl/internal/fsutil" "gopkg.in/yaml.v3" ) @@ -263,7 +264,7 @@ func MigrateApply(root string, b *Bundle, plan MigratePlan) error { if bytes.Equal(out, raw) { continue } - if err := os.WriteFile(abs, out, 0o644); err != nil { //nolint:gosec // G306: a bundle node is a shareable knowledge document; 0o644 is intended + 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) } } @@ -493,7 +494,7 @@ func bumpOkfSidecar(root, target string) error { if !changed { return nil } - return os.WriteFile(abs, []byte(strings.Join(lines, "\n")), 0o644) //nolint:gosec // G306: the .okf sidecar is a shareable bundle artifact; 0o644 is intended + return fsutil.WriteFileAtomic(abs, []byte(strings.Join(lines, "\n")), 0o644) //nolint:gosec // G306: the .okf sidecar is a shareable bundle artifact; 0o644 is intended } // bumpRootIndexMarker rewrites the bundle-root index.md okf_version marker to @@ -542,7 +543,7 @@ func bumpRootIndexMarker(root, target string) error { if bytes.Equal(out.Bytes(), raw) { return nil } - return os.WriteFile(abs, out.Bytes(), 0o644) //nolint:gosec // G306: a bundle node is a shareable knowledge document; 0o644 is intended + return fsutil.WriteFileAtomic(abs, out.Bytes(), 0o644) //nolint:gosec // G306: a bundle node is a shareable knowledge document; 0o644 is intended } // findScalar returns the scalar value of key in a mapping, or "". diff --git a/internal/okf/mutate.go b/internal/okf/mutate.go index 3dc844d..09574cc 100644 --- a/internal/okf/mutate.go +++ b/internal/okf/mutate.go @@ -20,6 +20,8 @@ import ( "path/filepath" "sort" "strings" + + "github.com/cwest/okfctl/internal/fsutil" ) // LinkRewrite is a single planned edit to a node's body: replace the link @@ -217,7 +219,7 @@ func ApplyMove(root string, b *Bundle, old, new string, rewrites []LinkRewrite) } for path, content := range edited { abs := filepath.Join(root, filepath.FromSlash(path)) - if err := os.WriteFile(abs, []byte(content), 0o644); err != nil { //nolint:gosec // G306: a bundle node is a shareable knowledge document; 0o644 is intended + if err := fsutil.WriteFileAtomic(abs, []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) } } diff --git a/internal/okf/promote.go b/internal/okf/promote.go index e072fd0..220caa0 100644 --- a/internal/okf/promote.go +++ b/internal/okf/promote.go @@ -21,6 +21,8 @@ import ( "path/filepath" "sort" "strings" + + "github.com/cwest/okfctl/internal/fsutil" ) // PromoteChange is a single planned promotion of one directory-as-concept @@ -317,7 +319,7 @@ func PromoteApply(root string, b *Bundle, changes []PromoteChange) error { } for p, content := range edited { abs := filepath.Join(root, filepath.FromSlash(p)) - if err := os.WriteFile(abs, []byte(content), 0o644); err != nil { //nolint:gosec // G306: a bundle node is a shareable knowledge document; 0o644 is intended + if err := fsutil.WriteFileAtomic(abs, []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", p, err) } } @@ -340,7 +342,7 @@ func PromoteApply(root string, b *Bundle, changes []PromoteChange) error { // frontmatter (created untouched) and the same verbatim body. Only its // PATH changes; that alone flips it from an illegal directory index to a // legal concept node. - if err := os.WriteFile(newAbs, raw, 0o644); err != nil { //nolint:gosec // G306: a bundle node is a shareable knowledge document; 0o644 is intended + if err := fsutil.WriteFileAtomic(newAbs, raw, 0o644); err != nil { //nolint:gosec // G306: a bundle node is a shareable knowledge document; 0o644 is intended return fmt.Errorf("write %s: %w", ch.NewPath, err) } if err := os.Remove(oldAbs); err != nil { diff --git a/internal/okf/reserved.go b/internal/okf/reserved.go index 4803c14..4b4978c 100644 --- a/internal/okf/reserved.go +++ b/internal/okf/reserved.go @@ -17,6 +17,8 @@ package okf import ( "os" "path/filepath" + + "github.com/cwest/okfctl/internal/fsutil" ) // SpecVersion is the OKF spec version this build targets. @@ -49,7 +51,7 @@ func Scaffold(dir string) error { ".okf": "okf_version: " + SpecVersion + "\n", } for name, body := range files { - if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil { //nolint:gosec // G306: a scaffolded reserved file is shareable bundle content; 0o644 is intended + if err := fsutil.WriteFileAtomic(filepath.Join(dir, name), []byte(body), 0o644); err != nil { //nolint:gosec // G306: a scaffolded reserved file is shareable bundle content; 0o644 is intended return err } } diff --git a/internal/okf/reserved_lifecycle.go b/internal/okf/reserved_lifecycle.go index a81198a..4a9e90f 100644 --- a/internal/okf/reserved_lifecycle.go +++ b/internal/okf/reserved_lifecycle.go @@ -23,6 +23,8 @@ import ( "regexp" "sort" "strings" + + "github.com/cwest/okfctl/internal/fsutil" ) // neighborhood returns the top-level directory of a bundle-relative slash path, @@ -472,7 +474,7 @@ func WriteIndexWithOptions(b *Bundle, opts IndexShapeOptions) error { if existing, err := os.ReadFile(p); err == nil && usesCRLF(existing) { //nolint:gosec // G304: reading the tool's own generated index file out = strings.ReplaceAll(out, "\n", "\r\n") } - if err := os.WriteFile(p, []byte(out), 0o644); err != nil { //nolint:gosec // G306: a bundle index file is shareable content; 0o644 is intended + if err := fsutil.WriteFileAtomic(p, []byte(out), 0o644); err != nil { //nolint:gosec // G306: a bundle index file is shareable content; 0o644 is intended return err } } @@ -591,12 +593,12 @@ func AppendLog(root, message string) error { if err != nil { // Create a fresh §9 log with the default title. out := logHeader + "## " + today + "\n* " + message + "\n" - return os.WriteFile(p, []byte(out), 0o644) //nolint:gosec // G306: log.md is shareable bundle content; 0o644 is intended + return fsutil.WriteFileAtomic(p, []byte(out), 0o644) //nolint:gosec // G306: log.md is shareable bundle content; 0o644 is intended } lg := parseLog(string(existing)) lg.addEntry(today, message) - return os.WriteFile(p, []byte(lg.render()), 0o644) //nolint:gosec // G306: log.md is shareable bundle content; 0o644 is intended + return fsutil.WriteFileAtomic(p, []byte(lg.render()), 0o644) //nolint:gosec // G306: log.md is shareable bundle content; 0o644 is intended } // ReadLog returns the log.md body (empty string if the file is absent). diff --git a/internal/okf/writesafety_test.go b/internal/okf/writesafety_test.go new file mode 100644 index 0000000..0efe774 --- /dev/null +++ b/internal/okf/writesafety_test.go @@ -0,0 +1,213 @@ +// 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 okf + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// holdInode hard-links path into a directory outside the bundle and returns a +// check that the held copy still has the old bytes, i.e. that the writer +// replaced path by rename (atomic) rather than truncating it in place. +func holdInode(t *testing.T, path string) func() { + t.Helper() + before, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + held := filepath.Join(t.TempDir(), "held") + if err := os.Link(path, held); err != nil { + t.Skipf("hard links unsupported: %v", err) + } + return func() { + t.Helper() + got, err := os.ReadFile(held) + if err != nil { + t.Fatal(err) + } + if string(got) != string(before) { + t.Errorf("%s was rewritten in place (not by atomic rename)", filepath.Base(path)) + } + after, _ := os.ReadFile(path) + if string(after) == string(before) { + t.Errorf("%s was not rewritten at all", filepath.Base(path)) + } + ents, _ := os.ReadDir(filepath.Dir(path)) + for _, e := range ents { + if strings.Contains(e.Name(), ".tmp-") { + t.Errorf("leftover temp file %s", e.Name()) + } + } + } +} + +// nestedRoot returns (parent, root) where root is a bundle dir inside parent, +// so a write that escapes root by one ".." lands somewhere the test can see. +func nestedRoot(t *testing.T) (string, string) { + t.Helper() + parent := t.TempDir() + root := filepath.Join(parent, "bundle") + if err := os.MkdirAll(root, 0o755); err != nil { + t.Fatal(err) + } + return parent, root +} + +func writeTestFile(t *testing.T, root, rel, body string) { + t.Helper() + p := filepath.Join(root, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { + t.Fatal(err) + } +} + +// ---- atomic ----------------------------------------------------------------- + +func TestWriteSafety_TouchModifiedIsAtomic(t *testing.T) { + root := t.TempDir() + writeTestFile(t, root, "a.md", nodeSrc("A")+"body\n") + writeTestFile(t, root, "plain.md", "no frontmatter\n") + at := time.Date(2026, 10, 12, 0, 0, 0, 0, time.UTC) + for _, rel := range []string{"a.md", "plain.md"} { + p := filepath.Join(root, rel) + check := holdInode(t, p) + if err := TouchModifiedFile(p, at); err != nil { + t.Fatal(err) + } + check() + } +} + +// v0.1 negative control: legacy `timestamp` survives a touch (§13 fallback). +func TestWriteSafety_TouchModifiedKeepsV01Provenance(t *testing.T) { + root := t.TempDir() + writeLegacyV01Node(t, root, "legacy.md", "Concept", "Legacy", nil) + p := filepath.Join(root, "legacy.md") + if err := TouchModifiedFile(p, time.Date(2026, 10, 12, 0, 0, 0, 0, time.UTC)); err != nil { + t.Fatal(err) + } + raw, _ := os.ReadFile(p) + fm, body, err := ParseFrontmatter(raw) + if err != nil { + t.Fatal(err) + } + if fm["timestamp"] == nil || fm["modified"] == nil { + t.Fatalf("legacy timestamp or modified missing: %v", fm) + } + if !strings.Contains(body, "# Citations") { + t.Fatalf("legacy body citations lost: %q", body) + } +} + +func TestWriteSafety_ApplyMoveRewriteIsAtomic(t *testing.T) { + root, b := mkMoveBundle(t, map[string]string{ + "a.md": nodeSrc("A"), + "b.md": nodeSrc("B") + "See [A](a.md).\n", + }) + rw, err := PlanMove(b, "a.md", "c.md") + if err != nil { + t.Fatal(err) + } + check := holdInode(t, filepath.Join(root, "b.md")) + if err := ApplyMove(root, b, "a.md", "c.md", rw); err != nil { + t.Fatal(err) + } + check() +} + +func TestWriteSafety_PromoteApplyRewriteIsAtomic(t *testing.T) { + root, b := mkPromoteBundle(t, map[string]string{ + "foo/index.md": dirConceptIndex("Foo", "2026-01-01", "# Foo\n"), + "a.md": nodeSrc("A") + "See [Foo](foo/index.md).\n", + }) + changes, err := PromotePlan(b, "") + if err != nil { + t.Fatal(err) + } + check := holdInode(t, filepath.Join(root, "a.md")) + if err := PromoteApply(root, b, changes); err != nil { + t.Fatal(err) + } + check() +} + +// Also the v0.1 control: a legacy node migrates through the atomic writer. +func TestWriteSafety_MigrateApplyIsAtomic(t *testing.T) { + root := t.TempDir() + writeLegacyV01Node(t, root, "legacy.md", "Concept", "Legacy", nil) + writeTestFile(t, root, ".okf", "okf_version: 0.1\n") + writeTestFile(t, root, "index.md", "---\nokf_version: \"0.1\"\n---\n\n# KB\n") + b, err := Load(root) + if err != nil { + t.Fatal(err) + } + plan, err := PlanMigration(b, "okfctl-test") + if err != nil { + t.Fatal(err) + } + if len(plan.Nodes) == 0 { + t.Fatal("expected the v0.1 node to be planned") + } + checks := []func(){ + holdInode(t, filepath.Join(root, "legacy.md")), + holdInode(t, filepath.Join(root, ".okf")), + holdInode(t, filepath.Join(root, "index.md")), + } + if err := MigrateApply(root, b, plan); err != nil { + t.Fatal(err) + } + for _, c := range checks { + c() + } + raw, _ := os.ReadFile(filepath.Join(root, "legacy.md")) + fm, _, _ := ParseFrontmatter(raw) + if fm["timestamp"] != nil || fm["generated"] == nil { + t.Fatalf("v0.1 timestamp not migrated to generated.at: %v", fm) + } +} + +func TestWriteSafety_WriteIndexIsAtomic(t *testing.T) { + root := t.TempDir() + writeTestFile(t, root, "index.md", "# stale\n") + writeTestFile(t, root, "a.md", nodeSrc("A")) + b, err := Load(root) + if err != nil { + t.Fatal(err) + } + check := holdInode(t, filepath.Join(root, "index.md")) + if err := WriteIndex(b); err != nil { + t.Fatal(err) + } + check() +} + +func TestWriteSafety_AppendLogIsAtomic(t *testing.T) { + root := t.TempDir() + if err := Scaffold(root); err != nil { + t.Fatal(err) + } + check := holdInode(t, filepath.Join(root, "log.md")) + if err := AppendLog(root, "an entry"); err != nil { + t.Fatal(err) + } + check() +} From 0dd4c3baf6301715613dc3784ffad0508bbcbe6e Mon Sep 17 00:00:00 2001 From: LGuichet Date: Mon, 12 Oct 2026 02:20:50 +0200 Subject: [PATCH 09/28] =?UTF-8?q?=F0=9F=90=9B=20fix(write):=20save=20the?= =?UTF-8?q?=20user=20config,=20search=20store=20and=20migration=20plan=20a?= =?UTF-8?q?tomically?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit okfconfig.Save, search.(*Store).Save and the migrate --plan writer used os.WriteFile, which truncates in place; a crash or a concurrent reader could observe a partial file. Route them through fsutil.WriteFileAtomic (temp file plus rename). Each swap is pinned by a hard-link test that fails against the in-place writer. --- cmd/migrate.go | 3 +- cmd/migrate_plan_atomic_test.go | 43 ++++++++++++++++++++++++ internal/okfconfig/config.go | 4 ++- internal/okfconfig/save_atomic_test.go | 46 ++++++++++++++++++++++++++ internal/search/store.go | 3 +- internal/search/store_atomic_test.go | 45 +++++++++++++++++++++++++ 6 files changed, 141 insertions(+), 3 deletions(-) create mode 100644 cmd/migrate_plan_atomic_test.go create mode 100644 internal/okfconfig/save_atomic_test.go create mode 100644 internal/search/store_atomic_test.go diff --git a/cmd/migrate.go b/cmd/migrate.go index 25fd1c3..67680ca 100644 --- a/cmd/migrate.go +++ b/cmd/migrate.go @@ -19,6 +19,7 @@ import ( "fmt" "os" + "github.com/cwest/okfctl/internal/fsutil" "github.com/cwest/okfctl/internal/okf" "github.com/spf13/cobra" ) @@ -97,7 +98,7 @@ func runMigratePlan(cmd *cobra.Command, dir, planPath, generatedBy string) error return fmt.Errorf("encode plan: %w", err) } data = append(data, '\n') - if err := os.WriteFile(planPath, data, 0o644); err != nil { //nolint:gosec // G306: migration plan is a shareable bundle artifact; 0o644 is intended + if err := fsutil.WriteFileAtomic(planPath, data, 0o644); err != nil { //nolint:gosec // G306: migration plan is a shareable bundle artifact; 0o644 is intended return fmt.Errorf("write plan %s: %w", planPath, err) } out := cmd.OutOrStdout() diff --git a/cmd/migrate_plan_atomic_test.go b/cmd/migrate_plan_atomic_test.go new file mode 100644 index 0000000..429b4fb --- /dev/null +++ b/cmd/migrate_plan_atomic_test.go @@ -0,0 +1,43 @@ +// 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 cmd + +import ( + "os" + "path/filepath" + "testing" +) + +// `migrate --plan` over an existing plan file replaces it by rename. +func TestMigrate_PlanWriteIsAtomic(t *testing.T) { + dir := mkPromoteCLIBundle(t, migrateFixtureFiles()) + planPath := filepath.Join(t.TempDir(), "migrate-plan.json") + if err := os.WriteFile(planPath, []byte("stale\n"), 0o644); err != nil { + t.Fatal(err) + } + held := filepath.Join(t.TempDir(), "held") + if err := os.Link(planPath, held); err != nil { + t.Skipf("hard links unsupported: %v", err) + } + if out, err := runOKF(t, "migrate", dir, "--plan", planPath, "--generated-by", "human:casey"); err != nil { + t.Fatalf("migrate --plan: err=%v out=%q", err, out) + } + if got, _ := os.ReadFile(held); string(got) != "stale\n" { + t.Fatal("plan file was rewritten in place (not by atomic rename)") + } + if got, _ := os.ReadFile(planPath); string(got) == "stale\n" { + t.Fatal("plan file was not rewritten") + } +} diff --git a/internal/okfconfig/config.go b/internal/okfconfig/config.go index bd83310..bc3dd0d 100644 --- a/internal/okfconfig/config.go +++ b/internal/okfconfig/config.go @@ -23,6 +23,8 @@ import ( "encoding/json" "os" "path/filepath" + + "github.com/cwest/okfctl/internal/fsutil" ) // Path returns the config file location: $OKFCTL_CONFIG_HOME/config.json, else @@ -66,5 +68,5 @@ func Save(m map[string]string) error { if err != nil { return err } - return os.WriteFile(p, data, 0o600) + return fsutil.WriteFileAtomic(p, data, 0o600) } diff --git a/internal/okfconfig/save_atomic_test.go b/internal/okfconfig/save_atomic_test.go new file mode 100644 index 0000000..b807391 --- /dev/null +++ b/internal/okfconfig/save_atomic_test.go @@ -0,0 +1,46 @@ +// 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 okfconfig + +import ( + "os" + "path/filepath" + "testing" +) + +// Save replaces config.json by rename: a reader holding the old file (here, a +// hard link) never sees a truncated or half-written config. +func TestSave_IsAtomic(t *testing.T) { + dir := t.TempDir() + t.Setenv("OKFCTL_CONFIG_HOME", dir) + if err := Save(map[string]string{"k": "old"}); err != nil { + t.Fatal(err) + } + held := filepath.Join(t.TempDir(), "held") + if err := os.Link(Path(), held); err != nil { + t.Skipf("hard links unsupported: %v", err) + } + before, _ := os.ReadFile(held) + if err := Save(map[string]string{"k": "new"}); err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(held); string(got) != string(before) { + t.Fatal("config.json was rewritten in place (not by atomic rename)") + } + m, err := Load() + if err != nil || m["k"] != "new" { + t.Fatalf("Load after Save = %v, %v; want k=new", m, err) + } +} diff --git a/internal/search/store.go b/internal/search/store.go index 21651dc..6b3c482 100644 --- a/internal/search/store.go +++ b/internal/search/store.go @@ -22,6 +22,7 @@ import ( "os" "sort" + "github.com/cwest/okfctl/internal/fsutil" "github.com/cwest/okfctl/internal/okf" ) @@ -191,7 +192,7 @@ func (s *Store) Save(path string) error { if err != nil { return err } - return os.WriteFile(path, append(data, '\n'), 0o644) //nolint:gosec // G306: the search index is a tool-managed cache file; 0o644 is intended + return fsutil.WriteFileAtomic(path, append(data, '\n'), 0o644) //nolint:gosec // G306: the search index is a tool-managed cache file; 0o644 is intended } // Load reads a store from path. diff --git a/internal/search/store_atomic_test.go b/internal/search/store_atomic_test.go new file mode 100644 index 0000000..b857f56 --- /dev/null +++ b/internal/search/store_atomic_test.go @@ -0,0 +1,45 @@ +// 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 search + +import ( + "os" + "path/filepath" + "testing" +) + +// Store.Save replaces the index by rename, so a concurrent `search` never +// loads a truncated JSON file. +func TestStore_SaveIsAtomic(t *testing.T) { + b, _ := fixtureBundle(t) + s := BuildIndex(b, NewHashEmbedder(), nil) + p := filepath.Join(t.TempDir(), "index.json") + if err := os.WriteFile(p, []byte("{}\n"), 0o644); err != nil { + t.Fatal(err) + } + held := filepath.Join(t.TempDir(), "held") + if err := os.Link(p, held); err != nil { + t.Skipf("hard links unsupported: %v", err) + } + if err := s.Save(p); err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(held); string(got) != "{}\n" { + t.Fatal("store was rewritten in place (not by atomic rename)") + } + if _, err := Load(p); err != nil { + t.Fatalf("Load after Save: %v", err) + } +} From 3c4ec15b719201f2c4d2c1bb5172ce4fdb2041c7 Mon Sep 17 00:00:00 2001 From: LGuichet Date: Mon, 12 Oct 2026 02:22:12 +0200 Subject: [PATCH 10/28] =?UTF-8?q?=F0=9F=90=9B=20fix(node):=20confine=20nod?= =?UTF-8?q?e=20new=20and=20node=20edit=20to=20the=20bundle=20root?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OKF §3 defines a bundle as its directory tree. node new checked only the lexical path, so a symlinked or junctioned directory inside the bundle could carry the write outside it; node edit did no check at all and launched the editor on ../outside.md. Both now resolve the user path through fsutil.ResolveInRoot before touching disk. A nested a/b/c path and a title carrying --- in prose still write as before. --- cmd/node.go | 7 +- cmd/node_edit_confine_test.go | 47 ++++++++++++ internal/okf/authoring.go | 15 ++-- internal/okf/writesafety_newnode_test.go | 92 ++++++++++++++++++++++++ 4 files changed, 149 insertions(+), 12 deletions(-) create mode 100644 cmd/node_edit_confine_test.go create mode 100644 internal/okf/writesafety_newnode_test.go diff --git a/cmd/node.go b/cmd/node.go index d3157f5..b20e007 100644 --- a/cmd/node.go +++ b/cmd/node.go @@ -22,6 +22,7 @@ import ( "sort" "strings" + "github.com/cwest/okfctl/internal/fsutil" "github.com/cwest/okfctl/internal/okf" "github.com/spf13/cobra" ) @@ -271,7 +272,11 @@ func newNodeCmd() *cobra.Command { if okf.IsReservedPath(p) { return fmt.Errorf("cannot edit reserved file: %s", p) } - abs := filepath.Join(editBundle, filepath.FromSlash(p)) + // §3: never hand the editor a file outside the bundle root. + abs, err := fsutil.ResolveInRoot(editBundle, p) + if err != nil { + return fmt.Errorf("node edit %s: %w", p, err) + } if _, err := os.Stat(abs); err != nil { return fmt.Errorf("node not found: %s", p) } diff --git a/cmd/node_edit_confine_test.go b/cmd/node_edit_confine_test.go new file mode 100644 index 0000000..66a5db8 --- /dev/null +++ b/cmd/node_edit_confine_test.go @@ -0,0 +1,47 @@ +// 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 cmd + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// §3: a bundle is its directory tree. `node edit ../x` must not open, touch, +// or rewrite a file outside the bundle root. +func TestNodeEdit_RefusesPathOutsideBundle_Section3(t *testing.T) { + parent := t.TempDir() + dir := filepath.Join(parent, "bundle") + writeRaw(t, dir, "a.md", nodeDoc("A")) + writeRaw(t, parent, "outside.md", nodeDoc("Outside")) + before, _ := os.ReadFile(filepath.Join(parent, "outside.md")) + marker := filepath.Join(parent, "ran.marker") + t.Setenv("OKFCTL_EDITOR", fakeEditor(t, parent, "", 0, marker)) + + for _, p := range []string{"../outside", "../outside.md", "sub/../../outside"} { + _, err := runOKF(t, "node", "edit", p, "--bundle", dir) + if err == nil || !strings.Contains(err.Error(), "escapes the bundle root") { + t.Errorf("node edit %s: err = %v, want an escapes-the-bundle-root refusal", p, err) + } + } + if _, err := os.Stat(marker); err == nil { + t.Error("the editor was launched on a path outside the bundle") + } + if after, _ := os.ReadFile(filepath.Join(parent, "outside.md")); string(after) != string(before) { + t.Fatal("a file outside the bundle root was rewritten") + } +} diff --git a/internal/okf/authoring.go b/internal/okf/authoring.go index 3aa19cb..374bafd 100644 --- a/internal/okf/authoring.go +++ b/internal/okf/authoring.go @@ -50,18 +50,11 @@ func NewNodeFromTemplate(root, relPath, typ, title string, t Template) (string, if !strings.HasSuffix(relPath, ".md") { relPath += ".md" } - abs := filepath.Join(root, filepath.FromSlash(relPath)) - rootAbs, err := filepath.Abs(root) + // §3: the bundle is its directory tree, so the node must land inside it— + // lexically and through any symlinked or junctioned directory on the way. + abs, err := fsutil.ResolveInRoot(root, relPath) if err != nil { - return "", err - } - absAbs, err := filepath.Abs(abs) - if err != nil { - return "", err - } - rel, err := filepath.Rel(rootAbs, absAbs) - if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { - return "", fmt.Errorf("node path escapes the bundle root: %s", relPath) + return "", fmt.Errorf("node path %s: %w", relPath, err) } if _, err := os.Stat(abs); err == nil { return "", fmt.Errorf("node already exists: %s", relPath) diff --git a/internal/okf/writesafety_newnode_test.go b/internal/okf/writesafety_newnode_test.go new file mode 100644 index 0000000..5b0b0af --- /dev/null +++ b/internal/okf/writesafety_newnode_test.go @@ -0,0 +1,92 @@ +// 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 okf + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/cwest/okfctl/internal/fsutil" +) + +// linkDirForTest links a directory: a symlink where allowed, else (an +// unprivileged Windows account) a directory junction. +func linkDirForTest(target, link string) error { + err := os.Symlink(target, link) + if err == nil || runtime.GOOS != "windows" { + return err + } + return exec.Command("cmd", "/c", "mklink", "/J", link, target).Run() //nolint:gosec // G204: test-only fixture setup +} + +// ---- confined --------------------------------------------------------------- + +// §3: a bundle is its directory tree. A symlinked (or junctioned) directory +// inside the root that points outside must not carry a new node out. +func TestWriteSafety_NewNodeRefusesLinkEscape(t *testing.T) { + outside := t.TempDir() + root := t.TempDir() + if err := Scaffold(root); err != nil { + t.Fatal(err) + } + if err := linkDirForTest(outside, filepath.Join(root, "out")); err != nil { + t.Skipf("directory links unsupported: %v", err) + } + if _, err := NewNode(root, "out/evil", "Concept", "X"); !errors.Is(err, fsutil.ErrEscapesRoot) { + t.Fatalf("NewNode through an escaping link: err = %v, want ErrEscapesRoot", err) + } + if _, err := os.Stat(filepath.Join(outside, "evil.md")); err == nil { + t.Fatal("a node was written outside the bundle root") + } +} + +// Negative control: an ordinary nested path, and a title carrying `---` in +// prose or a real `\n---\n`, write a node with only the expected keys (§4). +func TestWriteSafety_NewNodeNegativeControls(t *testing.T) { + root := t.TempDir() + if err := Scaffold(root); err != nil { + t.Fatal(err) + } + for rel, title := range map[string]string{ + "a/b/c": "Before --- after", + "a/b/d": "line\n---\ninjected: true", + "/deep/e": "Plain", + } { + abs, err := NewNode(root, rel, "Concept", title) + if err != nil { + t.Fatalf("NewNode(%q): %v", rel, err) + } + want := filepath.Join(root, filepath.FromSlash(strings.TrimPrefix(rel, "/")+".md")) + if abs != want { + t.Errorf("NewNode(%q) wrote %s, want %s", rel, abs, want) + } + raw, _ := os.ReadFile(abs) + fm, _, err := ParseFrontmatter(raw) + if err != nil { + t.Fatalf("parse %s: %v", rel, err) + } + if fm["injected"] != nil { + t.Errorf("%s: title smuggled a frontmatter key: %v", rel, fm) + } + if fm["title"] != title { + t.Errorf("%s: title = %q, want %q", rel, fm["title"], title) + } + } +} From e17785e45fee92c305fbaabb11576d062badbe73 Mon Sep 17 00:00:00 2001 From: LGuichet Date: Mon, 12 Oct 2026 02:23:50 +0200 Subject: [PATCH 11/28] =?UTF-8?q?=F0=9F=90=9B=20fix(node):=20refuse=20a=20?= =?UTF-8?q?node=20mv=20that=20leaves=20the=20bundle=20root?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ApplyMove joined the destination onto the root with no containment check, so node mv a ../x.md renamed the node out of the bundle (OKF §3) after already rewriting its inbound links. Both ends now go through fsutil.ResolveInRoot before any write; a control character in the destination is refused too, since the path is echoed into link text. A nested in-bundle destination still moves. --- internal/okf/mutate.go | 14 ++++++- internal/okf/writesafety_move_test.go | 58 +++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 2 deletions(-) create mode 100644 internal/okf/writesafety_move_test.go diff --git a/internal/okf/mutate.go b/internal/okf/mutate.go index 09574cc..74cf1aa 100644 --- a/internal/okf/mutate.go +++ b/internal/okf/mutate.go @@ -176,8 +176,18 @@ func ApplyMove(root string, b *Bundle, old, new string, rewrites []LinkRewrite) if IsReservedPath(old) || IsReservedPath(new) { return fmt.Errorf("cannot move reserved file (%s -> %s)", old, new) } - oldAbs := filepath.Join(root, filepath.FromSlash(old)) - newAbs := filepath.Join(root, filepath.FromSlash(new)) + // §3: both ends of the move stay inside the bundle root. Checked before + // any rewrite so a refused move leaves every inbound link untouched; the + // control-character refusal also keeps a line break out of the rewritten + // link text. + oldAbs, err := fsutil.ResolveInRoot(root, old) + if err != nil { + return fmt.Errorf("move source %s: %w", old, err) + } + newAbs, err := fsutil.ResolveInRoot(root, new) + if err != nil { + return fmt.Errorf("move destination %s: %w", new, err) + } if _, err := os.Stat(newAbs); err == nil { return fmt.Errorf("destination already exists: %s", new) } else if !os.IsNotExist(err) { diff --git a/internal/okf/writesafety_move_test.go b/internal/okf/writesafety_move_test.go new file mode 100644 index 0000000..e7dccb7 --- /dev/null +++ b/internal/okf/writesafety_move_test.go @@ -0,0 +1,58 @@ +// 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 okf + +import ( + "os" + "path/filepath" + "testing" +) + +func TestWriteSafety_ApplyMoveRefusesEscape(t *testing.T) { + parent, root := nestedRoot(t) + writeTestFile(t, root, "a.md", nodeSrc("A")) + writeTestFile(t, root, "b.md", nodeSrc("B")+"See [A](a.md).\n") + b, err := Load(root) + if err != nil { + t.Fatal(err) + } + for _, dst := range []string{"../x.md", "../../x.md", "sub/../../x.md", "a\nb.md", "a\r## x.md"} { + rw, _ := PlanMove(b, "a.md", dst) + if err := ApplyMove(root, b, "a.md", dst, rw); err == nil { + t.Errorf("ApplyMove(a.md -> %q) must be refused", dst) + } + } + if _, err := os.Stat(filepath.Join(parent, "x.md")); err == nil { + t.Fatal("node moved outside the bundle root") + } + if raw, _ := os.ReadFile(filepath.Join(root, "b.md")); string(raw) != nodeSrc("B")+"See [A](a.md).\n" { + t.Fatalf("inbound link rewritten by a refused move: %q", raw) + } +} + +// Negative control: a nested in-bundle destination still moves. +func TestWriteSafety_ApplyMoveNestedStillWorks(t *testing.T) { + root, b := mkMoveBundle(t, map[string]string{"a.md": nodeSrc("A")}) + rw, err := PlanMove(b, "a.md", "a/b/c.md") + if err != nil { + t.Fatal(err) + } + if err := ApplyMove(root, b, "a.md", "a/b/c.md", rw); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(root, "a", "b", "c.md")); err != nil { + t.Fatal(err) + } +} From 2d3c1e94ece23e8ccfd2fc04270ce765984941bd Mon Sep 17 00:00:00 2001 From: LGuichet Date: Mon, 12 Oct 2026 02:25:18 +0200 Subject: [PATCH 12/28] =?UTF-8?q?=F0=9F=90=9B=20fix(node):=20confine=20nod?= =?UTF-8?q?e=20promote=20to=20the=20bundle=20root=20and=20its=20name=20to?= =?UTF-8?q?=20one=20segment?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PromotePlan accepted any --name, so ../x, a/b or index wrote the promoted concept outside its directory, outside the bundle (OKF §3), or over a §3.1 reserved file; a line break in it landed raw in every rewritten link. --name must now be one ordinary, non-reserved file-name segment. PromoteApply confines every path a plan names (old index, new concept, rewrite targets) through fsutil.ResolveInRoot before any write. The default name, an ordinary name and one with --- in it are still accepted. --- internal/okf/promote.go | 52 ++++++++++++++++++-- internal/okf/writesafety_promote_test.go | 61 ++++++++++++++++++++++++ 2 files changed, 108 insertions(+), 5 deletions(-) create mode 100644 internal/okf/writesafety_promote_test.go diff --git a/internal/okf/promote.go b/internal/okf/promote.go index 220caa0..71e15ab 100644 --- a/internal/okf/promote.go +++ b/internal/okf/promote.go @@ -73,6 +73,9 @@ func PromotableIndexes(b *Bundle) []string { // A destination that already exists as a concept node is a hard error — promote // never overwrites authored content. func PromotePlan(b *Bundle, basename string) ([]PromoteChange, error) { + if err := checkPromoteName(basename); err != nil { + return nil, err + } indexes := PromotableIndexes(b) // Compute each promotion's destination and validate up front. @@ -286,6 +289,22 @@ func newConceptIsRootRel(url, targetDir string) bool { // by WriteIndex at the command layer). root is the bundle root; b is the loaded // bundle the plan was computed against. It is the single writer for a promotion. func PromoteApply(root string, b *Bundle, changes []PromoteChange) error { + // 0) §3: confine every path the plan names to the bundle root before any + // write, so a refused change leaves the bundle exactly as it was. + absOf := map[string]string{} + for _, ch := range changes { + paths := []string{ch.OldPath, ch.NewPath} + for _, rw := range ch.Rewrites { + paths = append(paths, rw.NodePath) + } + for _, p := range paths { + abs, err := fsutil.ResolveInRoot(root, p) + if err != nil { + return fmt.Errorf("promote %s: %w", p, err) + } + absOf[p] = abs + } + } // 1) Apply link rewrites to the FULL on-disk file content, so the YAML // frontmatter block is preserved by construction and the scanner's byte // offsets and content stay in the same coordinate space. @@ -294,7 +313,7 @@ func PromoteApply(root string, b *Bundle, changes []PromoteChange) error { for _, rw := range ch.Rewrites { content, ok := edited[rw.NodePath] if !ok { - raw, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(rw.NodePath))) //nolint:gosec // G304: reading a node from the user's own bundle + raw, err := os.ReadFile(absOf[rw.NodePath]) //nolint:gosec // G304: reading a node from the user's own bundle if err != nil { return fmt.Errorf("read %s: %w", rw.NodePath, err) } @@ -318,8 +337,7 @@ func PromoteApply(root string, b *Bundle, changes []PromoteChange) error { } } for p, content := range edited { - abs := filepath.Join(root, filepath.FromSlash(p)) - if err := fsutil.WriteFileAtomic(abs, []byte(content), 0o644); err != nil { //nolint:gosec // G306: a bundle node is a shareable knowledge document; 0o644 is intended + if err := fsutil.WriteFileAtomic(absOf[p], []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", p, err) } } @@ -327,8 +345,8 @@ func PromoteApply(root string, b *Bundle, changes []PromoteChange) error { // 2) Move each directory-concept index into its new concept file (body // verbatim, created immutable), then remove the old index.md. for _, ch := range changes { - oldAbs := filepath.Join(root, filepath.FromSlash(ch.OldPath)) - newAbs := filepath.Join(root, filepath.FromSlash(ch.NewPath)) + oldAbs := absOf[ch.OldPath] + newAbs := absOf[ch.NewPath] raw, err := os.ReadFile(oldAbs) //nolint:gosec // G304: reading a node from the user's own bundle if err != nil { return fmt.Errorf("read %s: %w", ch.OldPath, err) @@ -363,3 +381,27 @@ func indexOfLink(content, rawTarget string) int { } return -1 } + +// checkPromoteName refuses a --name that is not a single, ordinary path +// segment. The promoted concept is written to /.md, so a separator +// or ".." would move it into another directory or out of the bundle (§3), a +// reserved base name would overwrite a §3.1 index.md or log.md, and a control +// character would land raw in every rewritten inbound link. "" means "use the +// directory's own base name" and is always accepted. +func checkPromoteName(name string) error { + if name == "" { + return nil + } + if name == "." || name == ".." || strings.ContainsAny(name, `/\`) { + return fmt.Errorf("promote --name %q must be a single file name, not a path", name) + } + for _, r := range name { + if r < 0x20 || r == 0x7f { + return fmt.Errorf("promote --name %q contains a control character", name) + } + } + if IsReservedPath(name + ".md") { + return fmt.Errorf("promote --name %q would create a reserved file (§3.1)", name) + } + return nil +} diff --git a/internal/okf/writesafety_promote_test.go b/internal/okf/writesafety_promote_test.go new file mode 100644 index 0000000..7cb350c --- /dev/null +++ b/internal/okf/writesafety_promote_test.go @@ -0,0 +1,61 @@ +// 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 okf + +import ( + "os" + "path/filepath" + "testing" +) + +func TestWriteSafety_PromotePlanRefusesBadName(t *testing.T) { + _, b := mkPromoteBundle(t, map[string]string{ + "foo/index.md": dirConceptIndex("Foo", "2026-01-01", "# Foo\n"), + }) + // "../x" and "a/b" are not one path segment; "log" / "index" would create + // a §3.1 reserved file; a line break would land raw in rewritten links. + for _, name := range []string{"../x", "../../x", "a/b", `a\b`, "..", ".", "log", "index", "a\nb"} { + if _, err := PromotePlan(b, name); err == nil { + t.Errorf("PromotePlan(--name %q) must be refused", name) + } + } + // Negative control: the default and an ordinary name are accepted. + for _, name := range []string{"", "foo-overview", "Before --- after"} { + if _, err := PromotePlan(b, name); err != nil { + t.Errorf("PromotePlan(--name %q): %v", name, err) + } + } +} + +func TestWriteSafety_PromoteApplyRefusesEscape(t *testing.T) { + parent, root := nestedRoot(t) + writeTestFile(t, root, "foo/index.md", dirConceptIndex("Foo", "2026-01-01", "# Foo\n")) + b, err := Load(root) + if err != nil { + t.Fatal(err) + } + changes := []PromoteChange{{OldPath: "foo/index.md", NewPath: "../x.md"}} + if err := PromoteApply(root, b, changes); err == nil { + t.Fatal("PromoteApply to ../x.md must be refused") + } + if _, err := os.Stat(filepath.Join(parent, "x.md")); err == nil { + t.Fatal("promoted concept written outside the bundle root") + } + if _, err := os.Stat(filepath.Join(root, "foo", "index.md")); err != nil { + t.Fatal("old index removed by a refused promotion") + } +} + +// The plan JSON is hand-editable; its node paths are untrusted input. From 20bd7adf8a787100b96e09d823565320ed9b822c Mon Sep 17 00:00:00 2001 From: LGuichet Date: Mon, 12 Oct 2026 02:26:22 +0200 Subject: [PATCH 13/28] =?UTF-8?q?=F0=9F=90=9B=20fix(migrate):=20validate?= =?UTF-8?q?=20an=20edited=20plan=20before=20migrate=20--apply=20writes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The plan file is user-editable between phases. MigrateApply joined each node path onto the root unchecked, so a plan naming ../victim.md rewrote a file outside the bundle (OKF §3), and wrote target_version verbatim into the line-keyed .okf sidecar, so a line break forged a second key (§12). Every plan node path now goes through fsutil.ResolveInRoot and a target carrying a control character is refused, both before any write. --- internal/okf/migrate.go | 22 +++++++- internal/okf/writesafety_migrate_test.go | 66 ++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 internal/okf/writesafety_migrate_test.go diff --git a/internal/okf/migrate.go b/internal/okf/migrate.go index 8218658..faa8ba5 100644 --- a/internal/okf/migrate.go +++ b/internal/okf/migrate.go @@ -251,8 +251,26 @@ func migrateTimeString(v any) string { // version markers (.okf sidecar and bundle-root index.md). It never touches a // judgment item — those stay for the plan's consumer. func MigrateApply(root string, b *Bundle, plan MigratePlan) error { - for _, nm := range plan.Nodes { - abs := filepath.Join(root, filepath.FromSlash(nm.Path)) + // 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) + } + } + // §3: every node the plan names must live inside the bundle root. + abss := make([]string, len(plan.Nodes)) + 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) + } + abss[i] = abs + } + 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) diff --git a/internal/okf/writesafety_migrate_test.go b/internal/okf/writesafety_migrate_test.go new file mode 100644 index 0000000..502c5d3 --- /dev/null +++ b/internal/okf/writesafety_migrate_test.go @@ -0,0 +1,66 @@ +// 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 okf + +import ( + "os" + "path/filepath" + "testing" +) + +func TestWriteSafety_MigrateApplyRefusesPlanPathEscape(t *testing.T) { + parent, root := nestedRoot(t) + writeLegacyV01Node(t, parent, "victim.md", "Concept", "Victim", nil) + before, _ := os.ReadFile(filepath.Join(parent, "victim.md")) + b, err := Load(root) + if err != nil { + t.Fatal(err) + } + plan := MigratePlan{TargetVersion: "0.2", Nodes: []NodeMigration{{ + Path: "../victim.md", + Generated: &GeneratedEdit{By: "x", At: "2026-01-02T03:04:05Z"}, + }}} + if err := MigrateApply(root, b, plan); err == nil { + t.Fatal("MigrateApply with a plan path outside the root must be refused") + } + if after, _ := os.ReadFile(filepath.Join(parent, "victim.md")); string(after) != string(before) { + t.Fatal("a file outside the bundle root was rewritten") + } +} + +// ---- injection -------------------------------------------------------------- + +// §12: the .okf sidecar is line-keyed; a target_version carrying a line break +// would smuggle extra sidecar keys. +func TestWriteSafety_MigrateApplyRefusesTargetInjection(t *testing.T) { + root := t.TempDir() + writeTestFile(t, root, ".okf", "okf_version: 0.1\n") + writeTestFile(t, root, "a.md", nodeSrc("A")) + b, err := Load(root) + if err != nil { + t.Fatal(err) + } + for _, target := range []string{"0.2\ntemplates: evil", "0.2\rtemplates: evil"} { + if err := MigrateApply(root, b, MigratePlan{TargetVersion: target}); err == nil { + t.Errorf("MigrateApply(target %q) must be refused", target) + } + } + if raw, _ := os.ReadFile(filepath.Join(root, ".okf")); string(raw) != "okf_version: 0.1\n" { + t.Fatalf(".okf changed: %q", raw) + } +} + +// §9: a log entry is one `* ` line; a lone `\r` is a CommonMark line ending, +// so it must not forge a `## ` heading. From 52b34e3a1ea382b962e1dbdece65281ebbc0769a Mon Sep 17 00:00:00 2001 From: LGuichet Date: Mon, 12 Oct 2026 02:26:59 +0200 Subject: [PATCH 14/28] =?UTF-8?q?=F0=9F=90=9B=20fix(log):=20cut=20a=20log?= =?UTF-8?q?=20message=20at=20a=20bare=20CR=20as=20well=20as=20LF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AppendLog flattened a message to its first line by cutting at LF only. CommonMark also ends a line at a bare CR, so a message like "a## 1999-01-01" wrote a forged date heading into the §9 log. Cut at the first CR or LF. --- internal/okf/reserved_lifecycle.go | 10 +++--- internal/okf/writesafety_log_test.go | 51 ++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 4 deletions(-) create mode 100644 internal/okf/writesafety_log_test.go diff --git a/internal/okf/reserved_lifecycle.go b/internal/okf/reserved_lifecycle.go index 4a9e90f..e53bbc9 100644 --- a/internal/okf/reserved_lifecycle.go +++ b/internal/okf/reserved_lifecycle.go @@ -576,12 +576,14 @@ func rel(root, abs string) string { // group when the newest heading is today, else under a new `## ` // heading inserted above the first heading. // -// A multi-line message is flattened to its first line; an empty message is -// rejected. +// A multi-line message (LF, CR or CRLF) is flattened to its first line; an +// empty message is rejected. func AppendLog(root, message string) error { message = strings.TrimSpace(message) - if i := strings.IndexByte(message, '\n'); i >= 0 { - message = message[:i] + // CommonMark ends a line at LF, CR or CRLF, so cut at either: a bare CR + // would otherwise start a forged `## ` heading inside the §9 log. + if i := strings.IndexAny(message, "\r\n"); i >= 0 { + message = strings.TrimSpace(message[:i]) } if message == "" { return fmt.Errorf("log message must not be empty") diff --git a/internal/okf/writesafety_log_test.go b/internal/okf/writesafety_log_test.go new file mode 100644 index 0000000..dddfb66 --- /dev/null +++ b/internal/okf/writesafety_log_test.go @@ -0,0 +1,51 @@ +// 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 okf + +import ( + "os" + "path/filepath" + "regexp" + "strings" + "testing" +) + +func TestWriteSafety_AppendLogCannotForgeHeading(t *testing.T) { + heading := regexp.MustCompile(`^## `) + for _, fresh := range []bool{true, false} { + root := t.TempDir() + if !fresh { + if err := Scaffold(root); err != nil { + t.Fatal(err) + } + } + if err := AppendLog(root, "a\r## 1999-01-01\r\n* forged"); err != nil { + t.Fatal(err) + } + raw, _ := os.ReadFile(filepath.Join(root, "log.md")) + n := 0 + for _, line := range regexp.MustCompile(`\r\n|\r|\n`).Split(string(raw), -1) { + if heading.MatchString(line) { + n++ + if strings.Contains(line, "1999") { + t.Errorf("forged heading %q", line) + } + } + } + if n != 1 { + t.Errorf("fresh=%v: %d date headings, want 1:\n%s", fresh, n, raw) + } + } +} From b3c7ab44f44974bc35078df24c5037047fe3a831 Mon Sep 17 00:00:00 2001 From: LGuichet Date: Mon, 12 Oct 2026 02:33:28 +0200 Subject: [PATCH 15/28] =?UTF-8?q?=E2=9C=85=20test(okf):=20fuzz=20the=20nod?= =?UTF-8?q?e,=20touch,=20okf=5Fversion=20marker=20and=20log=20write=20path?= =?UTF-8?q?s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four fuzz targets assert the write-safety properties on untrusted input: no injected frontmatter key from node new, no lost key or body from a modified refresh, a key-stable root index.md okf_version rewrite, and exactly one entry and heading per log append. Registered in the CI fuzz job. --- .github/workflows/ci.yml | 4 + internal/okf/writepath_fuzz_test.go | 264 ++++++++++++++++++++++++++++ 2 files changed, 268 insertions(+) create mode 100644 internal/okf/writepath_fuzz_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e42c754..eb92611 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -91,6 +91,10 @@ jobs: go test ./internal/okf/ -run '^$' -fuzz '^FuzzParseFrontmatter$' -fuzztime=30s go test ./internal/okf/ -run '^$' -fuzz '^FuzzSplitFrontmatterRaw$' -fuzztime=30s go test ./internal/okf/ -run '^$' -fuzz '^FuzzLoadBundle$' -fuzztime=30s + go test ./internal/okf/ -run '^$' -fuzz '^FuzzNewNodeFrontmatter$' -fuzztime=30s + go test ./internal/okf/ -run '^$' -fuzz '^FuzzTouchModifiedRoundTrip$' -fuzztime=30s + go test ./internal/okf/ -run '^$' -fuzz '^FuzzRootIndexMarker$' -fuzztime=30s + go test ./internal/okf/ -run '^$' -fuzz '^FuzzAppendLog$' -fuzztime=30s go test ./internal/apiserver/ -run '^$' -fuzz '^FuzzSearchQueryParams$' -fuzztime=30s go test ./internal/apiserver/ -run '^$' -fuzz '^FuzzCanonicalizeQuery$' -fuzztime=30s - name: positive control — a guaranteed crasher MUST fail the fuzz gate diff --git a/internal/okf/writepath_fuzz_test.go b/internal/okf/writepath_fuzz_test.go new file mode 100644 index 0000000..803e1be --- /dev/null +++ b/internal/okf/writepath_fuzz_test.go @@ -0,0 +1,264 @@ +// 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 okf + +import ( + "bytes" + "os" + "path/filepath" + "sort" + "strings" + "testing" + "time" +) + +// The fuzz targets below drive the WRITE paths, where frontmatter_fuzz_test.go +// drives the read paths. Each one asserts the write-safety property the audit +// fixed or confirmed: an untrusted string handed to a writer can change the +// value it is meant to change and nothing else—no extra §4 frontmatter key, no +// lost key, no rewritten body, no forged §9 log heading, no leftover temp file. + +// sortedKeys returns the keys of a parsed frontmatter map, sorted. +func sortedKeys(m map[string]any) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + sort.Strings(out) + return out +} + +// assertNoTempFiles fails if an atomic write left a `..tmp-*` file behind. +func assertNoTempFiles(t *testing.T, dir string) { + t.Helper() + ents, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + for _, e := range ents { + if strings.Contains(e.Name(), ".tmp-") { + t.Fatalf("atomic write left a temp file behind: %s", e.Name()) + } + } +} + +// FuzzNewNodeFrontmatter: `node new --type --title` hands two user strings to +// the §4 frontmatter writer. Whatever they hold—a `---` fence, a newline +// followed by `key: value`, YAML flow syntax—the written block must parse and +// carry exactly type, title (when non-blank), created and modified: no +// injected key. +func FuzzNewNodeFrontmatter(f *testing.F) { + seeds := [][2]string{ + {"Reference", "Widgets"}, + {"Reference", "Before --- after"}, + {"Reference", "line\n---\ninjected: true"}, + {"Reference", "line\r---\rinjected: true"}, + {"Ref\ninjected: true", "T"}, + {"Reference", "{a: b}"}, + {"Reference", " "}, + {"Reference", "#comment"}, + } + for _, s := range seeds { + f.Add(s[0], s[1]) + } + f.Fuzz(func(t *testing.T, typ, title string) { + if strings.TrimSpace(typ) == "" { + return // refused by design (§4 type is required) + } + root := t.TempDir() + abs, err := NewNode(root, "n.md", typ, title) + if err != nil { + t.Fatalf("NewNode(%q, %q): %v", typ, title, err) + } + raw, err := os.ReadFile(abs) //nolint:gosec // G304: test-owned temp file + if err != nil { + t.Fatal(err) + } + fm, _, err := ParseFrontmatter(raw) + if err != nil { + t.Fatalf("written frontmatter does not parse: %v\n%s", err, raw) + } + want := []string{"created", "modified", "type"} + if strings.TrimSpace(title) != "" { + want = append(want, "title") + } + sort.Strings(want) + if got := sortedKeys(fm); strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("frontmatter keys = %v, want %v\n%s", got, want, raw) + } + assertNoTempFiles(t, root) + }) +} + +// FuzzTouchModifiedRoundTrip: the `modified` refresh rewrites only the §4 +// frontmatter block of an arbitrary node file. Either it refuses and leaves the +// file byte-identical, or it keeps every original key and the body verbatim. +func FuzzTouchModifiedRoundTrip(f *testing.F) { + seeds := []string{ + "---\ntype: Reference\ntitle: Widgets\n---\n\n# Body\n", + "---\ntype: Reference\nmodified: 2020-01-01T00:00:00Z\n---\nbody --- with a rule\n\n---\n", + "# no frontmatter\n", + "---\r\ntype: Reference\r\n---\r\n\r\nCRLF body\r\n", + "---\ntitle: |\n line\n ---\n injected: true\n---\n", + "---\n- a list\n---\n", + "", + } + for _, s := range seeds { + f.Add(s) + } + at := time.Date(2026, 10, 12, 0, 0, 0, 0, time.UTC) + f.Fuzz(func(t *testing.T, src string) { + dir := t.TempDir() + abs := filepath.Join(dir, "n.md") + if err := os.WriteFile(abs, []byte(src), 0o644); err != nil { //nolint:gosec // G306: test fixture + t.Fatal(err) + } + werr := TouchModifiedFile(abs, at) + got, err := os.ReadFile(abs) //nolint:gosec // G304: test-owned temp file + if err != nil { + t.Fatal(err) + } + assertNoTempFiles(t, dir) + if werr != nil { + if !bytes.Equal(got, []byte(src)) { + t.Fatalf("refused touch still changed the file: %v", werr) + } + return + } + _, after, ok := splitFrontmatterRaw(got) + if !ok { + t.Fatalf("touched file has no frontmatter block:\n%q", got) + } + if _, origAfter, had := splitFrontmatterRaw([]byte(src)); had { + if !bytes.Equal(after, origAfter) { + t.Fatalf("body changed:\nwas %q\nnow %q", origAfter, after) + } + } else if !bytes.HasSuffix(got, []byte(src)) { + t.Fatalf("body changed when a block was prepended:\n%q", got) + } + newFM, _, err := ParseFrontmatter(got) + if err != nil { + t.Fatalf("touched frontmatter does not parse: %v\n%q", err, got) + } + if _, ok := newFM["modified"]; !ok { + t.Fatalf("modified missing after touch:\n%q", got) + } + if oldFM, _, err := ParseFrontmatter([]byte(src)); err == nil { + for k := range oldFM { + if _, ok := newFM[k]; !ok { + t.Fatalf("key %q lost by touch:\n%q", k, got) + } + } + if len(newFM) > len(oldFM)+1 { + t.Fatalf("touch added keys: %v -> %v", sortedKeys(oldFM), sortedKeys(newFM)) + } + } + }) +} + +// FuzzRootIndexMarker: `migrate --apply` writes the §12 okf_version marker into +// the bundle-root index.md from a plan the user may edit. Whatever the target +// string, the rewrite keeps the key set and the body, and a target with no +// control character is read back by Load as declared. +func FuzzRootIndexMarker(f *testing.F) { + for _, s := range []string{"0.2", "0.3", "1.0", "0.2\ninjected: true", "0.2\r---\r", "'", "\"", "- x", "{a: b}", " 0.2 "} { + f.Add(s) + } + const body = "\n# Index\n\n---\n\nA rule above.\n" + f.Fuzz(func(t *testing.T, version string) { + root := t.TempDir() + src := "---\nokf_version: \"0.1\"\ntitle: Root\n---\n" + body + p := filepath.Join(root, "index.md") + 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) + } + got, err := os.ReadFile(p) //nolint:gosec // G304: test-owned temp file + if err != nil { + t.Fatal(err) + } + assertNoTempFiles(t, root) + _, after, ok := splitFrontmatterRaw(got) + if !ok || string(after) != body { + t.Fatalf("body not preserved:\n%q", got) + } + fm, _, err := ParseFrontmatter(got) + if err != nil { + t.Fatalf("index.md frontmatter does not parse: %v\n%q", err, got) + } + if keys := strings.Join(sortedKeys(fm), ","); keys != "okf_version,title" { + t.Fatalf("keys = %s, want okf_version,title\n%q", keys, got) + } + if s, isStr := fm["okf_version"].(string); isStr && strings.TrimSpace(version) != "" && + !strings.ContainsFunc(version, func(r rune) bool { return r < 0x20 || r == 0x7f }) { + if s != version { + t.Fatalf("okf_version = %q, want %q", s, version) + } + } + }) +} + +// FuzzAppendLog: `log append` takes a free-text message. It must add exactly +// one `* ` entry and at most one `## ` heading (§9): a message cannot +// forge a heading or a second entry, whatever line breaks it carries. +func FuzzAppendLog(f *testing.F) { + for _, s := range []string{"did a thing", "a\n## 2020-01-01\n* forged", "a\r## 2020-01-01", "a\r\n* b", "## 2020-01-01", " ", "
x"} { + f.Add(s) + } + at := time.Date(2026, 10, 12, 9, 0, 0, 0, time.UTC) + prev := nowUTC + nowUTC = func() time.Time { return at } + f.Cleanup(func() { nowUTC = prev }) + const existing = "# Change Log\n\n## 2026-10-11\n* earlier entry\n" + lines := func(s string) []string { + return strings.FieldsFunc(s, func(r rune) bool { return r == '\n' || r == '\r' }) + } + count := func(s, prefix string) int { + n := 0 + for _, l := range lines(s) { + if strings.HasPrefix(l, prefix) { + n++ + } + } + return n + } + f.Fuzz(func(t *testing.T, msg string) { + root := t.TempDir() + p := filepath.Join(root, "log.md") + if err := os.WriteFile(p, []byte(existing), 0o644); err != nil { //nolint:gosec // G306: test fixture + t.Fatal(err) + } + werr := AppendLog(root, msg) + got, err := os.ReadFile(p) //nolint:gosec // G304: test-owned temp file + if err != nil { + t.Fatal(err) + } + assertNoTempFiles(t, root) + if werr != nil { + if string(got) != existing { + t.Fatalf("refused append still changed the log: %v", werr) + } + return + } + if d := count(string(got), "## ") - count(existing, "## "); d != 1 { + t.Fatalf("heading count changed by %d, want 1:\n%s", d, got) + } + if d := count(string(got), "* ") - count(existing, "* "); d != 1 { + t.Fatalf("entry count changed by %d, want 1:\n%s", d, got) + } + }) +} From 4f95f087e7d1f57421609657d8487a222b8443d9 Mon Sep 17 00:00:00 2001 From: LGuichet Date: Mon, 12 Oct 2026 02:34:51 +0200 Subject: [PATCH 16/28] =?UTF-8?q?=F0=9F=93=9D=20docs(spec):=20record=20the?= =?UTF-8?q?=20write-safety=20audit=20as=20implemented?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Name ErrInvalidPath and the junction check in the ResolveInRoot contract, list the fuzz targets and tests as shipped, and correct the linkDir test comment: EvalSymlinks does not follow a junction. --- docs/specs/2026-10-12-write-safety-audit.md | 71 ++++++++++++++++----- internal/fsutil/fsutil_test.go | 3 +- 2 files changed, 56 insertions(+), 18 deletions(-) diff --git a/docs/specs/2026-10-12-write-safety-audit.md b/docs/specs/2026-10-12-write-safety-audit.md index 9ea13f7..b0b859f 100644 --- a/docs/specs/2026-10-12-write-safety-audit.md +++ b/docs/specs/2026-10-12-write-safety-audit.md @@ -1,6 +1,6 @@ # fix(write)—write-safety audit: atomic, confined, injection-free writes -**Status:** Approved (design) · **Owner:** Casey West · **License:** Apache-2.0 +**Status:** Implemented · **Owner:** Casey West · **License:** Apache-2.0 **Source of truth:** OKF `SPEC.md` **v0.2** (upstream `GoogleCloudPlatform/knowledge-catalog`, header confirmed `**Version 0.2**`)—§3 (a bundle is a directory tree), §3.1 (reserved filenames), §4 / §4.1 (the @@ -46,7 +46,7 @@ change, one commit per gap. | `migrate apply` → `bumpRootIndexMarker` (root `index.md`, §8/§12) | **gap**—`os.WriteFile` | safe—fixed `/index.md` | safe—`setScalar` + `yaml.Encoder` | | `migrate` (plan phase) → plan JSON (`cmd/migrate.go`) | **gap**—`os.WriteFile` | n/a—`--plan` is an explicit output path the user names, not bundle content | safe—`json.MarshalIndent` | | `init` → `okf.Scaffold` (`reserved.go`) | **gap**—`os.WriteFile` per file | n/a—`dir` *is* the root being created | safe—fixed content (`SpecVersion` is a constant) | -| `index build` / auto-maintenance → `okf.WriteIndexWithOptions` (`reserved_lifecycle.go`) | **gap**—`os.WriteFile` | safe—every path derives from `IndexDirs(b)` | safe—the only frontmatter is the §12 `okf_version` marker, emitted with `%q` (a double-quoted, fully escaped scalar that YAML reads back as one string); pinned by a new fuzz target | +| `index build` / auto-maintenance → `okf.WriteIndexWithOptions` (`reserved_lifecycle.go`) | **gap**—`os.WriteFile` | safe—every path derives from `IndexDirs(b)` | safe—the only frontmatter is the §12 `okf_version` marker, emitted with `%q` (a double-quoted, fully escaped scalar that YAML reads back as one string); the migrate rewrite of the same marker is fuzzed by `FuzzRootIndexMarker` | | `log append` / auto-maintenance → `okf.AppendLog` (§9) | **gap**—`os.WriteFile` | safe—fixed `/log.md` | **gap**—the message is flattened at the first `\n` only; a lone `\r` is a CommonMark line ending, so `msg\r## 1999-01-01` forges a §9 date heading | | `config set` → `okfconfig.Save` | **gap**—`os.WriteFile` | n/a—fixed user-config path | safe—`json.MarshalIndent` | | `plugin install` → `plugin.copyExecutable` | safe—`CreateTemp` in the destination dir + `Rename` | safe—the installed name is `filepath.Base(source)`, so it cannot leave the plugin dir | n/a | @@ -64,7 +64,10 @@ consumer and reuses the helpers below. The vector store (`internal/search`), the user config (`internal/okfconfig`), and `cmd` all need the atomic writer, and none should import `internal/okf` for -it, so both helpers live in a tiny leaf package with no okfctl imports. +it, so both helpers live in a tiny leaf package that imports only the standard +library. `internal/okfconfig` imports nothing from okfctl today; hosting the +writer in `internal/okf` would drag the whole bundle model into the config +package just to save a file. ```go // internal/fsutil/atomicwrite.go @@ -72,6 +75,7 @@ func WriteFileAtomic(path string, data []byte, perm os.FileMode) error // internal/fsutil/confine.go var ErrEscapesRoot = errors.New("path escapes the bundle root") +var ErrInvalidPath = errors.New("invalid bundle path") func ResolveInRoot(root, rel string) (string, error) ``` @@ -87,18 +91,28 @@ never ends in `.md`, so a crash-orphaned temp is never loaded as a node. **`ResolveInRoot`** turns a user-supplied bundle-relative path into an absolute path inside `root`, or refuses it: -- empty, or the root itself (`.`) → refused; -- a control character (C0 or DEL) anywhere → refused. A path is written into - link text by `node mv` / `node promote`; a line break there is the - injection vector in the table above; -- an OS-absolute path with a volume (`C:\x`, `\\server\share`) → refused; +- empty, or the root itself (`.`, `/`) → `ErrInvalidPath`; +- a control character (C0 or DEL) anywhere → `ErrInvalidPath`. A path is + written into link text by `node mv` / `node promote`; a line break there is + the injection vector in the table above; +- an OS-absolute path with a volume (`C:\x`, `\\server\share`) → + `ErrEscapesRoot`; - a leading `/` is **kept as bundle-root-relative**, matching §6.1's `/`-absolute link form and the behavior `node new` already pins (`TestNewNode_RejectsPathEscape`): `/deep/x.md` resolves to `/deep/x.md`; - after `Clean`, any `..` that climbs above the root → `ErrEscapesRoot`; - the deepest *existing* ancestor of the result is `EvalSymlinks`-resolved and must still sit inside the resolved root, so a symlinked directory pointing out - of the bundle is refused while an in-bundle symlink is fine. + of the bundle is refused while an in-bundle symlink is fine; +- because `EvalSymlinks` does not follow a Windows directory junction (which an + unprivileged account can create), every existing component below the root is + also `Lstat`ed, and any symlink or reparse point on the way must itself + `Readlink`-resolve inside the root. + +Callers wrap the sentinels with `%w`, so `errors.Is(err, fsutil.ErrEscapesRoot)` +holds at every call site. The tests create a symlink where the OS allows it and +fall back to a junction (`mklink /J`) on an unprivileged Windows account, so the +escape tests run rather than skip on Windows. It returns the lexical absolute path (not the symlink-resolved one), so callers write where the user pointed. The check is a pre-write gate, not a kernel-level @@ -113,9 +127,13 @@ out of scope for a local, single-user CLI. `PromotePlan` / `PromoteApply` (the destination), and `MigrateApply` (each `plan.nodes[].path`). - `PromotePlan` additionally refuses a `--name` that is not a single path - segment, or that would produce a reserved filename (§3.1). -- `bumpOkfSidecar` refuses a `target_version` containing a control character - (the sidecar is line-keyed; there is no encoder to route through). + segment (`.`, `..`, a `/` or `\`, a control character), or that would + produce a reserved filename (§3.1). An empty `--name` keeps its existing + meaning (default basename). +- `MigrateApply` refuses a `target_version` containing a control character + before any write (the `.okf` sidecar is line-keyed; there is no encoder to + route through), and resolves every `plan.nodes[].path` before the first + write, so a bad plan entry leaves the bundle untouched. - `AppendLog` flattens the message at the first CommonMark line ending (`\n` or `\r`), not just `\n` (§9 date headings stay unforgeable). @@ -123,14 +141,33 @@ out of scope for a local, single-user CLI. Extending `2026-08-08-fuzz-untrusted-parsers.md`: each target writes through the real writer, reads the result back through the real parser, and asserts the -injection invariant. All are registered in the CI `fuzz` job. +injection invariant. All four live in `internal/okf/writepath_fuzz_test.go`, are +registered in the CI `fuzz` job at `-fuzztime=30s`, and assert that no +`..tmp-*` file is left behind. | target | writer → parser | invariants | |---|---|---| -| `FuzzNewNodeFrontmatter` | `NewNode(type, title)` → `ParseFrontmatter` | never panics; on success the frontmatter keys are exactly `type`, `created`, `modified` (+ `title` when non-blank)—no smuggled key | -| `FuzzTouchModifiedRoundTrip` | `TouchModifiedFile` → `ParseFrontmatter` | never panics; on error the file is byte-identical (atomicity); on success `modified` is present, every pre-existing key survives (§4.1 preserve unknown keys), and the body is unchanged | -| `FuzzRootIndexMarker` | `rootFrontmatter` (§12 marker) → `ParseFrontmatter` | the block holds exactly one key, `okf_version`; for valid UTF-8 its value round-trips exactly | -| `FuzzAppendLog` | `AppendLog` → CommonMark line split | a fresh log has exactly one `## ` heading—today's (§9) | +| `FuzzNewNodeFrontmatter` | `NewNode(type, title)` → `ParseFrontmatter` | never panics; the frontmatter parses and its keys are exactly `type`, `created`, `modified` (+ `title` when non-blank)—no smuggled key | +| `FuzzTouchModifiedRoundTrip` | `TouchModifiedFile` → `ParseFrontmatter` | on error the file is byte-identical; on success `modified` is present, every pre-existing key survives (§4.1), at most one key is added, and the body after the block is byte-identical | +| `FuzzRootIndexMarker` | `bumpRootIndexMarker` (§12 marker) → `ParseFrontmatter` | the root `index.md` keeps exactly its keys and its body; a control-character-free target that decodes as a string reads back exactly | +| `FuzzAppendLog` | `AppendLog` → CommonMark line split (LF and CR) | one append adds exactly one `* ` entry and one `## ` heading (§9); a refused append leaves the log byte-identical | + +`FuzzAppendLog` is the positive control for the bare-CR fix: with `AppendLog` +reverted to cutting at `\n` only, its seed corpus fails on `a\r## 2020-01-01`. + +### Tests + +| file | covers | +|---|---| +| `internal/fsutil/fsutil_test.go` | the helper contract: replace-by-rename, failure leaves the target, mode kept, write-through symlink; accepted and refused paths, symlink/junction escape, in-bundle link | +| `internal/okf/writesafety_test.go` | touch, move and promote rewrites, migrate, index and log writes replace by rename (hard-link probe); a v0.1 node keeps its legacy provenance through a touch | +| `internal/okf/writesafety_newnode_test.go` | `node new` through an escaping link; `a/b/c.md`, `/deep/x.md`, titles with `---` | +| `internal/okf/writesafety_move_test.go` | `node mv` out of the root or with a line break refused, links untouched | +| `internal/okf/writesafety_promote_test.go` | `--name` escape, multi-segment, reserved and control-character names | +| `internal/okf/writesafety_migrate_test.go` | plan path escape and `target_version` injection refused before any write | +| `internal/okf/writesafety_log_test.go` | bare-CR heading forgery | +| `cmd/node_edit_confine_test.go` | `node edit ../x` refused before the editor runs | +| `internal/okfconfig/save_atomic_test.go`, `internal/search/store_atomic_test.go`, `cmd/migrate_plan_atomic_test.go` | config, vector store and plan writes replace by rename | ## Controls diff --git a/internal/fsutil/fsutil_test.go b/internal/fsutil/fsutil_test.go index 62becba..0f2711d 100644 --- a/internal/fsutil/fsutil_test.go +++ b/internal/fsutil/fsutil_test.go @@ -226,7 +226,8 @@ func TestResolveInRoot_InBundleSymlinkAccepted(t *testing.T) { // linkDir links a directory: a symlink where the OS allows it, otherwise (an // unprivileged Windows account) a directory junction, which needs no -// privilege and is followed by filepath.EvalSymlinks just the same. +// privilege. EvalSymlinks does not follow a junction, so the junction case +// exercises ResolveInRoot's per-component link check. func linkDir(target, link string) error { err := os.Symlink(target, link) if err == nil || runtime.GOOS != "windows" { From e7d044fb7897e8386c388c48696bfd08d0702c46 Mon Sep 17 00:00:00 2001 From: LGuichet Date: Mon, 12 Oct 2026 10:40:20 +0200 Subject: [PATCH 17/28] =?UTF-8?q?=F0=9F=93=9D=20docs(agents):=20keep=20wor?= =?UTF-8?q?k=20on=20the=20fork=20and=20sign=20as=20the=20real=20author?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b1adb07..2178583 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,10 +1,23 @@ -# AGENTS.md—how work flows in this repo (`cwest/okfctl`) +# AGENTS.md—how work flows in this repo (`LGuichet/okfctl`, a fork of `cwest/okfctl`) This file is the operating contract for any agent (or human) making changes to this repo. It is auto-injected as project context whenever a session or job runs with this directory as its working directory. Read it before you touch anything here. +## This is a fork—work stays here + +Upstream (`cwest/okfctl`, the `origin` remote) requires every commit to be signed +as its maintainer, so it does not take outside contributions. Work on this fork +lands on the fork only: + +- **Never open a PR, issue, or review against `cwest/okfctl`.** PRs target + `LGuichet/okfctl` (the `fork` remote). +- **Never push to `origin`.** Treat it as read-only: `git fetch origin` to pick + up upstream changes, then merge them into the fork's `next`/`main`. +- Everything else in this file still applies—the spec, the gate, and the house + style are unchanged. + ## The one fact that governs everything **`okfctl` is a consumer of a spec it does not own. The Open Knowledge Format @@ -150,7 +163,8 @@ decision nobody reviewed. on the checkout that publishes—that breaks a post-merge `git pull --ff-only`. - **Apache headers read `Copyright Google LLC`**—not Casey West. Match the existing files exactly. -- **Commits are SSH-signed** as `Casey West `, Conventional +- **Commits are SSH-signed by their real author**, under that author's own name, + email, and key—never under someone else's identity. Conventional format, no AI attribution and no agent/teammate names in any commit message, PR title/body, issue, review comment, or code comment. - **No CGO, no Python, no ONNX.** Pure Go; `CGO_ENABLED=0` must build. (This @@ -211,4 +225,5 @@ A change is done when all of the following hold—not when the code works: 3. Real-corpus run executed, with before/after counts pinned in the PR body. 4. Both controls proven for any detector change. 5. Spec sections cited for any spec-mandated behavior. -6. Commit signed, Conventional, team-invisible. +6. Commit signed by its real author, Conventional, team-invisible. +7. PR opened on the fork (`LGuichet/okfctl`), never upstream. From ba71a317cffe241afe9ba70bf2a2c69bbe62b6dc Mon Sep 17 00:00:00 2001 From: LGuichet Date: Mon, 12 Oct 2026 15:30:13 +0200 Subject: [PATCH 18/28] =?UTF-8?q?=F0=9F=93=9D=20docs(agents):=20drop=20the?= =?UTF-8?q?=20commit-signing=20requirement=20on=20the=20fork?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2178583..1f4a2b5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -163,8 +163,8 @@ decision nobody reviewed. on the checkout that publishes—that breaks a post-merge `git pull --ff-only`. - **Apache headers read `Copyright Google LLC`**—not Casey West. Match the existing files exactly. -- **Commits are SSH-signed by their real author**, under that author's own name, - email, and key—never under someone else's identity. Conventional +- **Commits carry their real author's name and email**—never someone else's + identity. Signing is not required. Conventional format, no AI attribution and no agent/teammate names in any commit message, PR title/body, issue, review comment, or code comment. - **No CGO, no Python, no ONNX.** Pure Go; `CGO_ENABLED=0` must build. (This @@ -225,5 +225,5 @@ A change is done when all of the following hold—not when the code works: 3. Real-corpus run executed, with before/after counts pinned in the PR body. 4. Both controls proven for any detector change. 5. Spec sections cited for any spec-mandated behavior. -6. Commit signed by its real author, Conventional, team-invisible. +6. Commit by its real author, Conventional, team-invisible. 7. PR opened on the fork (`LGuichet/okfctl`), never upstream. From fba88add5481af19d6558fcafdb9e927b5f7ee48 Mon Sep 17 00:00:00 2001 From: LGuichet Date: Wed, 14 Oct 2026 17:23:59 +0200 Subject: [PATCH 19/28] =?UTF-8?q?=F0=9F=94=A7=20chore(git):=20force=20LF?= =?UTF-8?q?=20line=20endings=20via=20.gitattributes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With core.autocrlf=true (the Windows default) every text file checks out as CRLF, so gofmt -l listed all 218 Go files, the command-reference drift test failed on docs/commands/README.md, and index check saw every index as stale. Pin eol=lf for all text files so a clone is LF regardless of local config. No stored content changes: git add --renormalize is a no-op. --- .gitattributes | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..00e2264 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +# Normalize line endings: every text file is stored and checked out as LF, +# whatever core.autocrlf says locally. gofmt, the command-reference drift +# test and index check all compare against LF content, so a CRLF checkout +# (Windows default) made every file look dirty. +* text=auto eol=lf From f71e4e030f8a8a02132190acc1ff0d004dc933c7 Mon Sep 17 00:00:00 2001 From: LGuichet Date: Tue, 27 Oct 2026 10:45:45 +0100 Subject: [PATCH 20/28] =?UTF-8?q?=F0=9F=90=9B=20fix(fsutil):=20keep=20the?= =?UTF-8?q?=20atomic=20writer=20working=20on=20Windows=20junctions=20and?= =?UTF-8?q?=20honour=20the=20umask?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - On Windows an O_EXCL create under a directory junction fails with "file exists" (os.CreateTemp included), so every write into an in-bundle junctioned directory that ResolveInRoot accepts was refused. Open the temp without O_EXCL there, behind an Lstat check on a 64-bit random name. - Create the temp with perm instead of os.CreateTemp's forced 0600 plus a chmod, so a new file goes through the umask as it did with os.WriteFile. An existing file still keeps its own mode. - Retry a Windows rename briefly on access-denied, when another process holds the target open. - Sync the parent directory after the rename so the replace survives a crash (best effort; not possible on Windows). - Document that a hard-linked target is replaced rather than written through. --- internal/fsutil/atomicwrite.go | 106 +++++++++++++++++++-- internal/fsutil/atomicwrite_review_test.go | 88 +++++++++++++++++ internal/fsutil/atomicwrite_umask_test.go | 51 ++++++++++ internal/fsutil/b.md | 1 + 4 files changed, 236 insertions(+), 10 deletions(-) create mode 100644 internal/fsutil/atomicwrite_review_test.go create mode 100644 internal/fsutil/atomicwrite_umask_test.go create mode 100644 internal/fsutil/b.md diff --git a/internal/fsutil/atomicwrite.go b/internal/fsutil/atomicwrite.go index 23d6122..9d94438 100644 --- a/internal/fsutil/atomicwrite.go +++ b/internal/fsutil/atomicwrite.go @@ -20,29 +20,43 @@ package fsutil import ( + "crypto/rand" + "encoding/hex" "errors" "fmt" "io/fs" "os" "path/filepath" + "runtime" + "time" ) // rename is the final step of WriteFileAtomic; a variable only so a test can // inject a failure and prove the target is left untouched. var rename = os.Rename +// renameRetries bounds how often a Windows rename is retried while another +// process holds the target open (see renameWithRetry). +const renameRetries = 5 + // WriteFileAtomic writes data to path so that a reader (or a crash) observes // either the old content or the new content, never a truncated mix. It writes // a temp file in path's own directory (same filesystem, so the rename is -// atomic), syncs and closes it, then renames it over path. On any error the -// temp file is removed and path is left exactly as it was. +// atomic), syncs and closes it, renames it over path, then syncs the directory +// so the rename itself survives a crash. On any error the temp file is removed +// and path is left exactly as it was. // // It keeps os.WriteFile's observable semantics where they matter: -// - perm applies only when path does not exist; an existing file keeps its +// - perm applies only when path does not exist, and is filtered by the +// process umask exactly as os.WriteFile's is; an existing file keeps its // permission bits. // - a path that is a symlink is written through: the link's target is // replaced and the link itself survives. // +// One deliberate difference: a hard-linked path is replaced, not written +// through, so its other links keep the old content. Atomicity requires a new +// inode; a bundle file with several hard links is outside what okfctl manages. +// // The temp name is "..tmp-"—it never ends in ".md", so an // orphan left by a hard crash is never loaded as a bundle node. func WriteFileAtomic(path string, data []byte, perm os.FileMode) error { @@ -54,12 +68,15 @@ func WriteFileAtomic(path string, data []byte, perm os.FileMode) error { } target = resolved } - mode := perm + // An existing file keeps its mode; a new one takes perm at creation, + // through the umask. + var keepMode os.FileMode + exists := false if fi, err := os.Stat(target); err == nil { if !fi.Mode().IsRegular() { return fmt.Errorf("write %s: not a regular file", path) } - mode = fi.Mode().Perm() + keepMode, exists = fi.Mode().Perm(), true } else if !errors.Is(err, fs.ErrNotExist) { return fmt.Errorf("stat %s: %w", path, err) } @@ -68,11 +85,10 @@ func WriteFileAtomic(path string, data []byte, perm os.FileMode) error { if dir == "" { dir = "." } - tmp, err := os.CreateTemp(dir, "."+base+".tmp-*") + tmp, tmpName, err := createTemp(dir, base, perm) if err != nil { return fmt.Errorf("write %s: %w", path, err) } - tmpName := tmp.Name() committed := false defer func() { if !committed { @@ -91,12 +107,82 @@ func WriteFileAtomic(path string, data []byte, perm os.FileMode) error { if err := tmp.Close(); err != nil { return fmt.Errorf("close %s: %w", path, err) } - if err := os.Chmod(tmpName, mode); err != nil { - return fmt.Errorf("chmod %s: %w", path, err) + if exists { + if err := os.Chmod(tmpName, keepMode); err != nil { + return fmt.Errorf("chmod %s: %w", path, err) + } } - if err := rename(tmpName, target); err != nil { + if err := renameWithRetry(tmpName, target); err != nil { return fmt.Errorf("write %s: %w", path, err) } committed = true + syncDir(dir) return nil } + +// createTemp makes "..tmp-" in dir with perm, so a new file gets +// perm through the umask (os.CreateTemp would force 0600). +// +// On Windows, Go's O_EXCL create fails with "file exists" for any path under a +// directory junction—os.CreateTemp included—and ResolveInRoot accepts an +// in-bundle junction. There the name is checked free with Lstat and opened +// without O_EXCL; 64 random bits make a race with another creator moot. +func createTemp(dir, base string, perm os.FileMode) (*os.File, string, error) { + flags := os.O_RDWR | os.O_CREATE | os.O_EXCL + if runtime.GOOS == "windows" { + flags = os.O_RDWR | os.O_CREATE | os.O_TRUNC + } + var lastErr error + for range 10 { + var b [8]byte + if _, err := rand.Read(b[:]); err != nil { + return nil, "", err + } + name := filepath.Join(dir, "."+base+".tmp-"+hex.EncodeToString(b[:])) + if flags&os.O_EXCL == 0 { + if _, err := os.Lstat(name); err == nil { + lastErr = fs.ErrExist + continue + } + } + f, err := os.OpenFile(name, flags, perm) //nolint:gosec // G304: temp sibling of the caller's own target + if err == nil { + return f, name, nil + } + if !errors.Is(err, fs.ErrExist) { + return nil, "", err + } + lastErr = err + } + return nil, "", lastErr +} + +// renameWithRetry renames, retrying briefly on Windows: there a rename over a +// file another process holds open (a concurrent okfctl serve, an indexer, an +// antivirus scan) fails with a transient access-denied/sharing error that an +// in-place write would not have hit. +func renameWithRetry(from, to string) error { + err := rename(from, to) + if runtime.GOOS != "windows" { + return err + } + delay := 10 * time.Millisecond + for i := 0; err != nil && errors.Is(err, fs.ErrPermission) && i < renameRetries; i++ { + time.Sleep(delay) + delay *= 2 + err = rename(from, to) + } + return err +} + +// syncDir flushes dir's entries so a completed rename is durable. Best effort: +// Windows cannot open a directory for sync, and the data is already on disk. +func syncDir(dir string) { + if runtime.GOOS == "windows" { + return + } + if d, err := os.Open(dir); err == nil { //nolint:gosec // G304: the caller's own target directory + _ = d.Sync() + _ = d.Close() + } +} diff --git a/internal/fsutil/atomicwrite_review_test.go b/internal/fsutil/atomicwrite_review_test.go new file mode 100644 index 0000000..008c603 --- /dev/null +++ b/internal/fsutil/atomicwrite_review_test.go @@ -0,0 +1,88 @@ +// 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" + "io/fs" + "os" + "path/filepath" + "runtime" + "testing" +) + +// A transient access-denied on Windows (another process holds the target +// open) is retried; elsewhere, and for any other error, it is not. +func TestWriteFileAtomic_RenameRetry(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "a.md") + calls := 0 + rename = func(from, to string) error { + calls++ + if calls <= 2 { + return &os.LinkError{Op: "rename", Old: from, New: to, Err: fs.ErrPermission} + } + return os.Rename(from, to) + } + t.Cleanup(func() { rename = os.Rename }) + + err := WriteFileAtomic(p, []byte("x"), 0o644) + if runtime.GOOS == "windows" { + if err != nil || calls != 3 { + t.Fatalf("windows: err = %v after %d calls, want success on the 3rd", err, calls) + } + } else if err == nil || calls != 1 { + t.Fatalf("%s: err = %v after %d calls, want one failing call", runtime.GOOS, err, calls) + } + noTemps(t, dir) +} + +// Negative control: a non-permission failure is never retried. +func TestWriteFileAtomic_OtherRenameErrorNotRetried(t *testing.T) { + dir := t.TempDir() + calls := 0 + rename = func(string, string) error { calls++; return errors.New("disk on fire") } + t.Cleanup(func() { rename = os.Rename }) + if err := WriteFileAtomic(filepath.Join(dir, "a.md"), []byte("x"), 0o644); err == nil { + t.Fatal("expected the injected failure") + } + if calls != 1 { + t.Fatalf("rename called %d times, want 1", calls) + } + noTemps(t, dir) +} + +// ResolveInRoot accepts an in-bundle directory link, so the writer must work +// through one—a junction on unprivileged Windows, where an O_EXCL create under +// a junction fails. Both an existing and a new file are written. +func TestWriteFileAtomic_ThroughDirectoryLink(t *testing.T) { + real := t.TempDir() + if err := os.WriteFile(filepath.Join(real, "b.md"), []byte("old"), 0o644); err != nil { + t.Fatal(err) + } + link := filepath.Join(t.TempDir(), "sub") + if err := linkDir(real, link); err != nil { + t.Skipf("directory links unsupported: %v", err) + } + for _, name := range []string{"b.md", "c.md"} { + if err := WriteFileAtomic(filepath.Join(link, name), []byte("new"), 0o644); err != nil { + t.Fatalf("write %s through a directory link: %v", name, err) + } + if got, _ := os.ReadFile(filepath.Join(real, name)); string(got) != "new" { + t.Fatalf("%s = %q, want new", name, got) + } + } + noTemps(t, real) +} diff --git a/internal/fsutil/atomicwrite_umask_test.go b/internal/fsutil/atomicwrite_umask_test.go new file mode 100644 index 0000000..8cb257a --- /dev/null +++ b/internal/fsutil/atomicwrite_umask_test.go @@ -0,0 +1,51 @@ +// 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. + +//go:build unix + +package fsutil + +import ( + "os" + "path/filepath" + "syscall" + "testing" +) + +// A new file takes perm through the umask, as os.WriteFile's did. Not +// parallel: the umask is process-wide. +func TestWriteFileAtomic_NewFileHonoursUmask(t *testing.T) { + old := syscall.Umask(0o027) + t.Cleanup(func() { syscall.Umask(old) }) + + p := filepath.Join(t.TempDir(), "a.md") + if err := WriteFileAtomic(p, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + fi, _ := os.Stat(p) + if got := fi.Mode().Perm(); got != 0o640 { + t.Fatalf("mode = %v, want 0640 (0644 &^ umask 027)", got) + } + // Negative control: an existing file keeps its own mode, umask or not. + if err := os.Chmod(p, 0o604); err != nil { + t.Fatal(err) + } + if err := WriteFileAtomic(p, []byte("y"), 0o644); err != nil { + t.Fatal(err) + } + fi, _ = os.Stat(p) + if got := fi.Mode().Perm(); got != 0o604 { + t.Fatalf("existing mode = %v, want 0604 kept", got) + } +} diff --git a/internal/fsutil/b.md b/internal/fsutil/b.md new file mode 100644 index 0000000..c1b0730 --- /dev/null +++ b/internal/fsutil/b.md @@ -0,0 +1 @@ +x \ No newline at end of file From 5309c82dac9efb35727e3e920a7e63832bf3a2e1 Mon Sep 17 00:00:00 2001 From: LGuichet Date: Tue, 27 Oct 2026 10:45:46 +0100 Subject: [PATCH 21/28] =?UTF-8?q?=F0=9F=90=9B=20fix(okf):=20confine=20move?= =?UTF-8?q?=20rewrites=20and=20check=20the=20promote=20destination=20befor?= =?UTF-8?q?e=20any=20write?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - §3: ApplyMove now confines every node it rewrites, not only the two ends of the move, so a node reached through a directory link out of the bundle is never written through. - PromoteApply checks on disk that each destination is free before step 1 rewrites inbound links. The check used to run after the rewrites, so a refused promotion left links pointing at a concept that was never written. - §3.1: IsReservedPath cleans the path with the native separator first, so `node edit sub\index.md` on Windows is refused like sub/index.md. --- internal/okf/bundle.go | 6 +- internal/okf/mutate.go | 15 +- internal/okf/promote.go | 14 +- internal/okf/writesafety_review_test.go | 181 ++++++++++++++++++++++++ 4 files changed, 206 insertions(+), 10 deletions(-) create mode 100644 internal/okf/writesafety_review_test.go diff --git a/internal/okf/bundle.go b/internal/okf/bundle.go index b0354ae..3e8e720 100644 --- a/internal/okf/bundle.go +++ b/internal/okf/bundle.go @@ -33,9 +33,11 @@ import ( var ReservedFiles = map[string]bool{"index.md": true, "log.md": true} // IsReservedPath reports whether a bundle-relative slash path names a reserved -// file (index.md or log.md) at any depth. +// file (index.md or log.md) at any depth. The path is cleaned with the native +// separator first, the way a write resolves it, so a user-typed `sub\index.md` +// on Windows is recognized as the reserved file it lands on. func IsReservedPath(rel string) bool { - return ReservedFiles[path.Base(rel)] + return ReservedFiles[path.Base(filepath.ToSlash(filepath.Clean(rel)))] } // DefaultSkipDirs is the base-name skip list applied to the bundle walk. These diff --git a/internal/okf/mutate.go b/internal/okf/mutate.go index 74cf1aa..016f788 100644 --- a/internal/okf/mutate.go +++ b/internal/okf/mutate.go @@ -200,6 +200,16 @@ func ApplyMove(root string, b *Bundle, old, new string, rewrites []LinkRewrite) // the full file keeps offsets and content in the same coordinate space. // (A frontmatter block contains no node-resolving markdown link, so // scanning the whole file cannot introduce a spurious match.) + // §3: a rewritten node is written too, so confine it like the move ends—a + // node that is a symlink out of the bundle must not be written through. + absOf := map[string]string{} + for _, rw := range rewrites { + abs, err := fsutil.ResolveInRoot(root, rw.NodePath) + if err != nil { + return fmt.Errorf("move rewrite %s: %w", rw.NodePath, err) + } + absOf[rw.NodePath] = abs + } edited := map[string]string{} for _, rw := range rewrites { if b.Nodes[rw.NodePath] == nil { @@ -207,7 +217,7 @@ func ApplyMove(root string, b *Bundle, old, new string, rewrites []LinkRewrite) } content, ok := edited[rw.NodePath] if !ok { - raw, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(rw.NodePath))) //nolint:gosec // G304: reading a node from the user's own bundle + raw, err := os.ReadFile(absOf[rw.NodePath]) //nolint:gosec // G304: reading a node from the user's own bundle if err != nil { return fmt.Errorf("read %s: %w", rw.NodePath, err) } @@ -228,8 +238,7 @@ func ApplyMove(root string, b *Bundle, old, new string, rewrites []LinkRewrite) edited[rw.NodePath] = content } for path, content := range edited { - abs := filepath.Join(root, filepath.FromSlash(path)) - if err := fsutil.WriteFileAtomic(abs, []byte(content), 0o644); err != nil { //nolint:gosec // G306: a bundle node is a shareable knowledge document; 0o644 is intended + 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) } } diff --git a/internal/okf/promote.go b/internal/okf/promote.go index 71e15ab..d0de4ab 100644 --- a/internal/okf/promote.go +++ b/internal/okf/promote.go @@ -304,6 +304,15 @@ func PromoteApply(root string, b *Bundle, changes []PromoteChange) error { } absOf[p] = abs } + // PromotePlan only checks loaded nodes; the disk is the authority. A + // file already there (a non-node, or on a case-insensitive filesystem + // the index.md being promoted, --name Index) refuses the promotion here, + // before step 1 rewrites any inbound link. + if _, err := os.Lstat(absOf[ch.NewPath]); err == nil { + return fmt.Errorf("cannot promote %s: destination %s already exists", ch.OldPath, ch.NewPath) + } else if !os.IsNotExist(err) { + return fmt.Errorf("stat %s: %w", ch.NewPath, err) + } } // 1) Apply link rewrites to the FULL on-disk file content, so the YAML // frontmatter block is preserved by construction and the scanner's byte @@ -351,11 +360,6 @@ func PromoteApply(root string, b *Bundle, changes []PromoteChange) error { if err != nil { return fmt.Errorf("read %s: %w", ch.OldPath, err) } - if _, err := os.Stat(newAbs); err == nil { - return fmt.Errorf("destination already exists: %s", ch.NewPath) - } else if !os.IsNotExist(err) { - return fmt.Errorf("stat %s: %w", ch.NewPath, err) - } // The promoted file is byte-identical to the old index — same // frontmatter (created untouched) and the same verbatim body. Only its // PATH changes; that alone flips it from an illegal directory index to a diff --git a/internal/okf/writesafety_review_test.go b/internal/okf/writesafety_review_test.go new file mode 100644 index 0000000..21f39b3 --- /dev/null +++ b/internal/okf/writesafety_review_test.go @@ -0,0 +1,181 @@ +// 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 okf + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +// §3.1: a user-typed path is recognized as reserved once cleaned the way the +// write resolves it. +func TestWriteSafety_IsReservedPathCleansFirst(t *testing.T) { + for _, p := range []string{"index.md", "a/log.md", "a/./index.md", "a/b/../index.md"} { + if !IsReservedPath(p) { + t.Errorf("IsReservedPath(%q) = false, want true", p) + } + } + // Negative control: look-alikes stay ordinary nodes. + for _, p := range []string{"index.mdx", "a/index.md.bak", "indexes.md", "a/index/x.md"} { + if IsReservedPath(p) { + t.Errorf("IsReservedPath(%q) = true, want false", p) + } + } + // A backslash is a separator only on Windows; elsewhere it is an ordinary + // file-name byte, so `a\index.md` is a node named that way. + if got, want := IsReservedPath(`a\index.md`), runtime.GOOS == "windows"; got != want { + t.Errorf(`IsReservedPath("a\\index.md") = %v, want %v on %s`, got, want, runtime.GOOS) + } +} + +// caseInsensitiveFS reports whether dir's filesystem folds case. +func caseInsensitiveFS(t *testing.T, dir string) bool { + t.Helper() + p := filepath.Join(dir, "CaseProbe") + if err := os.WriteFile(p, nil, 0o644); err != nil { + t.Fatal(err) + } + defer func() { _ = os.Remove(p) }() + _, err := os.Stat(filepath.Join(dir, "caseprobe")) + return err == nil +} + +// --name Index on a case-insensitive filesystem names the very index.md being +// promoted; writing it and then removing the old index would lose the content. +func TestWriteSafety_PromoteRefusesCaseFoldedReservedName(t *testing.T) { + src := dirConceptIndex("Foo", "2026-01-01", "# Foo body\n") + root, b := mkPromoteBundle(t, map[string]string{"foo/index.md": src}) + if !caseInsensitiveFS(t, root) { + t.Skip("filesystem is case-sensitive: foo/Index.md is a distinct, legal node") + } + for _, name := range []string{"Index", "LOG"} { + if name == "LOG" { + writeTestFile(t, root, "foo/log.md", "# Log\n") + } + changes, err := PromotePlan(b, name) + if err != nil { + continue // refused at plan time is fine too + } + if err := PromoteApply(root, b, changes); err == nil { + t.Errorf("PromoteApply(--name %s) must be refused on a case-insensitive filesystem", name) + } + } + got, err := os.ReadFile(filepath.Join(root, "foo", "index.md")) + if err != nil || string(got) != src { + t.Fatalf("index.md lost or altered by a refused promotion: %q, %v", got, err) + } +} + +// PromotePlan only knows loaded nodes; a file that appeared on disk since (or +// was never loaded) refuses PromoteApply before any inbound link is rewritten. +func TestWriteSafety_PromoteRefusesExistingDiskFile(t *testing.T) { + inbound := nodeSrc("Ref") + "See [Foo](foo/index.md).\n" + root, b := mkPromoteBundle(t, map[string]string{ + "foo/index.md": dirConceptIndex("Foo", "2026-01-01", "# Foo\n"), + "ref.md": inbound, + }) + changes, err := PromotePlan(b, "") + if err != nil { + t.Fatal(err) + } + writeTestFile(t, root, "foo/foo.md", "authored meanwhile\n") + if err := PromoteApply(root, b, changes); err == nil { + t.Fatal("PromoteApply over an existing file must be refused") + } + if got, _ := os.ReadFile(filepath.Join(root, "foo", "foo.md")); string(got) != "authored meanwhile\n" { + t.Fatalf("existing file overwritten: %q", got) + } + if _, err := os.Stat(filepath.Join(root, "foo", "index.md")); err != nil { + t.Fatal("old index removed by a refused promotion") + } + if got, _ := os.ReadFile(filepath.Join(root, "ref.md")); string(got) != inbound { + t.Fatalf("inbound link rewritten by a refused promotion: %q", got) + } +} + +// Negative control: an ordinary promotion with a free destination still runs. +func TestWriteSafety_PromoteFreeDestinationStillWorks(t *testing.T) { + root, b := mkPromoteBundle(t, map[string]string{ + "foo/index.md": dirConceptIndex("Foo", "2026-01-01", "# Foo\n"), + }) + changes, err := PromotePlan(b, "overview") + if err != nil { + t.Fatal(err) + } + if err := PromoteApply(root, b, changes); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(root, "foo", "overview.md")); err != nil { + t.Fatal(err) + } +} + +// §3: a node rewritten by a move is written too, so a node that is a symlink +// out of the bundle must not be written through. +func TestWriteSafety_ApplyMoveRefusesRewriteThroughSymlink(t *testing.T) { + outsideDir := t.TempDir() + outside := filepath.Join(outsideDir, "b.md") + outsideSrc := nodeSrc("Outside") + "See [A](../a.md).\n" + if err := os.WriteFile(outside, []byte(outsideSrc), 0o644); err != nil { + t.Fatal(err) + } + root, b := mkMoveBundle(t, map[string]string{ + "a.md": nodeSrc("A"), + "sub/b.md": nodeSrc("B") + "See [A](../a.md).\n", + }) + rw, err := PlanMove(b, "a.md", "moved.md") + if err != nil { + t.Fatal(err) + } + // Swap sub/ for a directory link out of the bundle after planning (a + // junction on unprivileged Windows, which EvalSymlinks does not follow). + if err := os.RemoveAll(filepath.Join(root, "sub")); err != nil { + t.Fatal(err) + } + if err := linkDirForTest(outsideDir, filepath.Join(root, "sub")); err != nil { + t.Skipf("directory links unsupported: %v", err) + } + if err := ApplyMove(root, b, "a.md", "moved.md", rw); err == nil { + t.Fatal("ApplyMove must refuse to rewrite a node that links out of the bundle") + } + if got, _ := os.ReadFile(outside); string(got) != outsideSrc { + t.Fatalf("file outside the bundle rewritten: %q", got) + } + if _, err := os.Stat(filepath.Join(root, "a.md")); err != nil { + t.Fatal("source moved by a refused move") + } +} + +// Negative control: a rewritten node in a subdirectory is still confined in. +func TestWriteSafety_ApplyMoveNestedRewriteStillWorks(t *testing.T) { + root, b := mkMoveBundle(t, map[string]string{ + "a.md": nodeSrc("A"), + "real/b.md": nodeSrc("B") + "See [A](../a.md).\n", + }) + rw, err := PlanMove(b, "a.md", "moved.md") + if err != nil { + t.Fatal(err) + } + if err := ApplyMove(root, b, "a.md", "moved.md", rw); err != nil { + t.Fatal(err) + } + got, _ := os.ReadFile(filepath.Join(root, "real", "b.md")) + if !strings.Contains(string(got), "moved.md") { + t.Fatalf("inbound link not rewritten: %q", got) + } +} From 0538ad1f920512aacf717414afc591e458025286 Mon Sep 17 00:00:00 2001 From: LGuichet Date: Tue, 27 Oct 2026 11:33:21 +0100 Subject: [PATCH 22/28] =?UTF-8?q?=E2=9C=A8=20feat(fsutil):=20hash-checked,?= =?UTF-8?q?=20rollback-safe=20multi-file=20transaction?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fsutil.Tx stages writes and renames, checks every target against the SHA-256 the caller planned against before writing anything, applies the steps in order, and undoes the applied steps newest first when one fails. Each write stays atomic through WriteFileAtomic; directories a rename created are removed on rollback, pre-existing ones never are. The undo runs in-process from in-memory copies, so it covers a failed step, not a crash part-way through a commit. --- internal/fsutil/tx.go | 206 +++++++++++++++++++++++++++++++++++++ internal/fsutil/tx_test.go | 197 +++++++++++++++++++++++++++++++++++ 2 files changed, 403 insertions(+) create mode 100644 internal/fsutil/tx.go create mode 100644 internal/fsutil/tx_test.go 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") + } +} From 34042dfbc712fa42f0453cd589e77b1d55254c8b Mon Sep 17 00:00:00 2001 From: LGuichet Date: Tue, 27 Oct 2026 11:33:21 +0100 Subject: [PATCH 23/28] =?UTF-8?q?=F0=9F=90=9B=20fix(okf):=20refuse=20stale?= =?UTF-8?q?=20plans=20and=20roll=20back=20partial=20node=20mv=20and=20migr?= =?UTF-8?q?ate=20--apply?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit node mv rewrote inbound links one file at a time and then renamed the node: a failure on the directory step or the rename left every rewrite in place, pointing at a node that never moved, and a node edited after the load was overwritten without notice. migrate --apply wrote each node as it went, so a failure on a late node left the bundle half-migrated, and a plan was applied to files edited since phase 1. Load now records each node's SHA-256. ApplyMove checks every file it touches against it and commits the rewrites and the move as one fsutil.Tx. The migrate plan records a sha256 per node; --apply and its --dry-run refuse a node that no longer matches, and the apply renders every node and both version markers before committing them as one transaction. A plan without sha256 (written before this change) still applies, with a warning on stderr. --- cmd/migrate.go | 12 ++ cmd/migrate_hashcheck_test.go | 102 ++++++++++ internal/okf/bundle.go | 6 +- internal/okf/hashcheck_test.go | 296 ++++++++++++++++++++++++++++ internal/okf/migrate.go | 112 ++++++++--- internal/okf/mutate.go | 59 +++++- internal/okf/node.go | 4 + internal/okf/writepath_fuzz_test.go | 10 +- 8 files changed, 561 insertions(+), 40 deletions(-) create mode 100644 cmd/migrate_hashcheck_test.go create mode 100644 internal/okf/hashcheck_test.go 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/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 faa8ba5..f1f9420 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 { @@ -561,7 +616,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/writepath_fuzz_test.go b/internal/okf/writepath_fuzz_test.go index 803e1be..ac3efcf 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 @@ -184,8 +186,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 { From 2d52de94cda06df0cd3da8e047fb4f54ca128aac Mon Sep 17 00:00:00 2001 From: LGuichet Date: Tue, 27 Oct 2026 11:49:21 +0100 Subject: [PATCH 24/28] =?UTF-8?q?=F0=9F=9A=A8=20fix(lint):=20wrap=20the=20?= =?UTF-8?q?confinement=20cause=20with=20%w,=20dedupe=20the=20separator=20c?= =?UTF-8?q?utset,=20apply=20De=20Morgan=20in=20the=20tag=20fold?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit golangci-lint (errorlint, staticcheck SA1024 and QF1001) flagged four findings already on next and on #5, which failed the lint job here. The cutset is "/" on Unix and "/\\" on Windows, as before. --- internal/fsutil/confine.go | 11 ++++++++--- internal/okf/tagfold.go | 2 +- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/internal/fsutil/confine.go b/internal/fsutil/confine.go index 535e83f..6f20e31 100644 --- a/internal/fsutil/confine.go +++ b/internal/fsutil/confine.go @@ -69,7 +69,12 @@ func ResolveInRoot(root, rel string) (string, error) { if filepath.VolumeName(native) != "" { return "", fmt.Errorf("%w: %s", ErrEscapesRoot, rel) } - native = strings.TrimLeft(native, string(filepath.Separator)+"/") + // Trim leading separators: "/" everywhere, plus `\` on Windows. + cutset := "/" + if filepath.Separator != '/' { + cutset += string(filepath.Separator) + } + native = strings.TrimLeft(native, cutset) clean := filepath.Clean(native) if clean == "." || native == "" { return "", fmt.Errorf("%w: %q names the bundle root", ErrInvalidPath, rel) @@ -103,7 +108,7 @@ func ResolveInRoot(root, rel string) (string, error) { } realExisting, err := filepath.EvalSymlinks(existing) if err != nil { - return "", fmt.Errorf("%w: %s (%v)", ErrEscapesRoot, rel, err) + return "", fmt.Errorf("%w: %s (%w)", ErrEscapesRoot, rel, err) } if !within(realRoot, realExisting) { return "", fmt.Errorf("%w: %s resolves through a symlink to %s", ErrEscapesRoot, rel, realExisting) @@ -122,7 +127,7 @@ func ResolveInRoot(root, rel string) (string, error) { cur = filepath.Join(cur, part) fi, err := os.Lstat(cur) if err != nil { - return "", fmt.Errorf("%w: %s (%v)", ErrEscapesRoot, rel, err) + return "", fmt.Errorf("%w: %s (%w)", ErrEscapesRoot, rel, err) } if fi.Mode()&(os.ModeSymlink|os.ModeIrregular) == 0 { continue diff --git a/internal/okf/tagfold.go b/internal/okf/tagfold.go index 12aa59c..b88be48 100644 --- a/internal/okf/tagfold.go +++ b/internal/okf/tagfold.go @@ -79,7 +79,7 @@ func tagPluralCandidates(w string) []string { case strings.HasSuffix(w, "es"): j := n - 3 // the letter before "es" var out []string - if j > 0 && !(w[j] == 's' && w[j-1] == 's') { + if j > 0 && (w[j] != 's' || w[j-1] != 's') { out = append(out, w[:n-1]) } return append(out, w[:n-2]) From 1e2f6dd80f8748117e646204a078e6379bd0e544 Mon Sep 17 00:00:00 2001 From: LGuichet Date: Tue, 27 Oct 2026 11:56:50 +0100 Subject: [PATCH 25/28] =?UTF-8?q?=F0=9F=94=A7=20chore(deps):=20bump=20Go?= =?UTF-8?q?=20toolchain=201.26.9=20->=201.26.10=20for=20GO-2026-6809?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit govulncheck failed build-test on GO-2026-6809 (crypto/x509 distrusts compromised intermediate certificates), fixed in 1.26.10 and reported reachable from fsutil.createTemp's rand.Read. Bump the go.mod directive and every actions/setup-go pin, as #190 did. go mod tidy leaves go.sum unchanged; govulncheck on 1.26.10 reports no vulnerabilities. --- .github/workflows/ci.yml | 8 ++++---- .github/workflows/codeql.yml | 2 +- .github/workflows/govulncheck.yml | 2 +- .github/workflows/release.yml | 2 +- CHANGELOG.md | 3 +++ go.mod | 2 +- 6 files changed, 11 insertions(+), 8 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 067a660..f75e4c3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -45,7 +45,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: { go-version: '1.26.9' } + with: { go-version: '1.26.10' } - name: gofmt run: test -z "$(gofmt -l .)" || (gofmt -l . && exit 1) - name: vet @@ -65,7 +65,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: { go-version: '1.26.9' } + with: { go-version: '1.26.10' } - name: golangci-lint uses: golangci/golangci-lint-action@ba0d7d2ec06a0ea1cb5fa41b2e4a3ab91d21278a # v9.3.0 with: @@ -84,7 +84,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: { go-version: '1.26.9' } + with: { go-version: '1.26.10' } - name: fuzz untrusted-input parsers (negative control — normal input passes) run: | set -euo pipefail @@ -259,7 +259,7 @@ jobs: echo "negative control rejected as required — the schema gate catches malformed manifests" - name: set up Go uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: { go-version: '1.26.9' } + with: { go-version: '1.26.10' } - name: leak gate + offline validator on the packaged artifact # The Go suite validates the manifest offline AND runs the leak gate over # the packaged skill payload (declared skills resolve to shareable, no diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 2ec80b3..38807f6 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -22,7 +22,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: { go-version: '1.26.9' } + with: { go-version: '1.26.10' } - name: Initialize CodeQL uses: github/codeql-action/init@1c5b675653bb5c22dbe9b12b556ec555138e09fd # v4.38.1 with: diff --git a/.github/workflows/govulncheck.yml b/.github/workflows/govulncheck.yml index bc44303..5c47024 100644 --- a/.github/workflows/govulncheck.yml +++ b/.github/workflows/govulncheck.yml @@ -16,7 +16,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: { go-version: '1.26.9' } + with: { go-version: '1.26.10' } - name: govulncheck run: | go install golang.org/x/vuln/cmd/govulncheck@latest diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 07138dd..cd4c409 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -18,7 +18,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: { fetch-depth: 0 } - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: { go-version: '1.26.9' } + with: { go-version: '1.26.10' } # Refuse to publish a tag whose version has no real changelog entry. This # runs BEFORE goreleaser, so an empty release fails the build rather than # publishing and being reported after the fact. The gate asserts a dated, diff --git a/CHANGELOG.md b/CHANGELOG.md index ac28f83..e7f779f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,6 +51,9 @@ tagged release, goreleaser generates the release notes from the commit log - The Go toolchain was bumped from 1.26.6 to 1.26.9 to pick up patched standard-library fixes for seven disclosed vulnerabilities (GO-2026-6603, -6607, -6608, -6611, -6612, -6613, -6617), clearing `govulncheck` in CI. +- The Go toolchain was bumped from 1.26.9 to 1.26.10 for GO-2026-6809 + (`crypto/x509` distrusts compromised intermediate certificates), which + `govulncheck` reports as reachable from the atomic writer's `crypto/rand` use. ## [0.4.0] - 2026-08-19 diff --git a/go.mod b/go.mod index d52125b..2f38766 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/cwest/okfctl -go 1.26.9 +go 1.26.10 require ( github.com/spf13/cobra v1.10.2 From d2b12d213066c77bb224b37d13193dc2784bd0d0 Mon Sep 17 00:00:00 2001 From: LGuichet Date: Tue, 27 Oct 2026 12:01:59 +0100 Subject: [PATCH 26/28] =?UTF-8?q?=F0=9F=90=9B=20fix(okf):=20refuse=20to=20?= =?UTF-8?q?touch=20a=20frontmatter=20block=20the=20parser=20rejects?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit FuzzTouchModifiedRoundTrip found that TouchModifiedFile stamped 'modified' into a block with a duplicate key: decoding into a yaml.Node accepts it, so the file was rewritten and still did not parse. Check the block with ParseFrontmatter, the parser validate uses, and refuse it unchanged. The crasher is committed as a regression seed. --- internal/okf/frontmatter_edit.go | 6 ++++++ .../fuzz/FuzzTouchModifiedRoundTrip/duplicate-key-block | 2 ++ 2 files changed, 8 insertions(+) create mode 100644 internal/okf/testdata/fuzz/FuzzTouchModifiedRoundTrip/duplicate-key-block diff --git a/internal/okf/frontmatter_edit.go b/internal/okf/frontmatter_edit.go index 878e60f..74dc69f 100644 --- a/internal/okf/frontmatter_edit.go +++ b/internal/okf/frontmatter_edit.go @@ -60,6 +60,12 @@ func TouchModifiedFile(abs string, at time.Time) error { return fsutil.WriteFileAtomic(abs, out.Bytes(), 0o644) //nolint:gosec // G306: shareable bundle content file } + // Decoding into a yaml.Node accepts what the frontmatter parser rejects + // (a duplicate key), so check with the parser validate uses: a block it + // cannot read is refused, not re-encoded with a stamp added. + if _, _, err := ParseFrontmatter(raw); err != nil { + return fmt.Errorf("parse frontmatter of %s: %w", abs, err) + } var doc yaml.Node if err := yaml.Unmarshal(yamlBlock, &doc); err != nil { return fmt.Errorf("parse frontmatter of %s: %w", abs, err) 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") From a238165fdbf16e534046ceae4904945b5e9b0211 Mon Sep 17 00:00:00 2001 From: LGuichet Date: Wed, 4 Nov 2026 09:24:37 +0100 Subject: [PATCH 27/28] =?UTF-8?q?=F0=9F=90=9B=20fix(okf):=20double-quote?= =?UTF-8?q?=20a=20node=20new=20value=20that=20holds=20a=20control=20charac?= =?UTF-8?q?ter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit FuzzNewNodeFrontmatter found that a title of tab, newline, '0' was written as a yaml.v3 literal block whose first line starts with a tab, which does not parse back. Write any value containing a control character double-quoted, which escapes it and round-trips; every other value keeps the plain style. The crasher is committed as a regression seed. --- internal/okf/authoring.go | 14 ++++++++++---- .../FuzzNewNodeFrontmatter/tab-led-multiline-title | 3 +++ 2 files changed, 13 insertions(+), 4 deletions(-) create mode 100644 internal/okf/testdata/fuzz/FuzzNewNodeFrontmatter/tab-led-multiline-title 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/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") From f129a417506a6401501da0a700e9a7114adfaf4f Mon Sep 17 00:00:00 2001 From: LGuichet Date: Wed, 4 Nov 2026 09:31:32 +0100 Subject: [PATCH 28/28] =?UTF-8?q?=F0=9F=94=A5=20chore(okf):=20drop=20tagfo?= =?UTF-8?q?ld.go,=20which=20next=20removed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The merge with next kept internal/okf/tagfold.go alive because this branch carried a one-line lint edit to it, but next had moved its code elsewhere, so every symbol in it was unused and failed golangci-lint. --- internal/okf/tagfold.go | 158 ---------------------------------------- 1 file changed, 158 deletions(-) delete mode 100644 internal/okf/tagfold.go diff --git a/internal/okf/tagfold.go b/internal/okf/tagfold.go deleted file mode 100644 index b88be48..0000000 --- a/internal/okf/tagfold.go +++ /dev/null @@ -1,158 +0,0 @@ -// 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 okf - -import ( - "strings" - "unicode" -) - -// tagSurface is the context-free half of the tag fold: lower-cased, trimmed, -// and separator-insensitive. A hyphen, underscore, space, or slash is dropped -// wherever it appears (home-lab = homelab, ci/cd = cicd). A full stop is dropped -// only between two letters, where Unicode UAX #29 treats it as word-internal -// (node.js = nodejs); elsewhere it is kept, so `.net` stays apart from `net` and -// `v1.2` from `v12`. No suffix is touched here—plural folding needs the bundle's -// vocabulary (see tagKeys). -func tagSurface(s string) string { - r := []rune(strings.ToLower(strings.TrimSpace(s))) - var b strings.Builder - for i, c := range r { - switch c { - case '-', '_', ' ', '/': - continue - case '.': - if i > 0 && i < len(r)-1 && unicode.IsLetter(r[i-1]) && unicode.IsLetter(r[i+1]) { - continue - } - } - b.WriteRune(c) - } - return b.String() -} - -// tagInvariant is the Snowball English (Porter2) stemmer's list of invariant -// exceptional forms: words that look inflected but are left as-is. It is what -// keeps `news` from folding onto `new`. -var tagInvariant = map[string]bool{ - "sky": true, "news": true, "howe": true, "atlas": true, "cosmos": true, "bias": true, "andes": true, -} - -// tagPluralCandidates returns the singular forms KStem's plural() would try for -// a surface form, in KStem's order (Lucene KStemmer.java, derived from the UMass -// CIIR KStemmer). Its guards are what short tags need: -// -// - a word that is not letters-only is never stemmed (k8s, v1, oauth2); -// - a word of two letters or fewer is never stemmed (js); -// - `-ies` tries `-ie`, then `-y`; -// - `-es` tries dropping the `s` (unless a double `s` precedes it), then `es`; -// - a plain final `s` is dropped only when the word is longer than three -// letters and does not end in `ss` or `ous` (aws, ops, ios, dns stay whole). -// -// KStem chooses among candidates with a dictionary lookup; tagKeys uses the -// bundle's own tag vocabulary for that. -func tagPluralCandidates(w string) []string { - n := len(w) - if n <= 2 || tagInvariant[w] || !strings.HasSuffix(w, "s") { - return nil - } - for _, c := range w { - if !unicode.IsLetter(c) { - return nil - } - } - switch { - case strings.HasSuffix(w, "ies"): - return []string{w[:n-1], w[:n-3] + "y"} - case strings.HasSuffix(w, "es"): - j := n - 3 // the letter before "es" - var out []string - if j > 0 && (w[j] != 's' || w[j-1] != 's') { - out = append(out, w[:n-1]) - } - return append(out, w[:n-2]) - case n > 3 && w[n-2] != 's' && !strings.HasSuffix(w, "ous"): - return []string{w[:n-1]} - } - return nil -} - -// tagKeys maps every raw tag value in raws to its canonical key. Two values -// share a key when their surface forms are equal, or when one's surface form -// is a KStem plural candidate of the other's AND that candidate is itself a -// surface form in raws. Requiring the candidate to be attested in the bundle -// stands in for KStem's dictionary: a non-word stem (cach, nodej) can never -// become a key, and nothing is folded unless both spellings are present—which -// a near-duplicate finding needs anyway. -// -// Classes are connected components (lenses → lens → len joins all three when -// all three are tags), so the result depends only on the SET of values, never -// their order. The key is the component's shortest surface form, ties broken -// byte-wise; it is a grouping handle, not a display spelling. A value whose -// surface form is empty maps to "". -func tagKeys(raws []string) map[string]string { - parent := map[string]string{} - for _, r := range raws { - if s := tagSurface(r); s != "" { - parent[s] = s - } - } - find := func(x string) string { - for parent[x] != x { - x = parent[x] - } - return x - } - for s := range parent { - for _, c := range tagPluralCandidates(s) { - if _, ok := parent[c]; !ok { - continue - } - a, b := find(s), find(c) - if a != b { - if len(b) < len(a) || (len(b) == len(a) && b < a) { - a, b = b, a - } - parent[b] = a // the shorter, then byte-wise smaller, root wins - } - break - } - } - out := make(map[string]string, len(raws)) - for _, r := range raws { - if s := tagSurface(r); s != "" { - out[r] = find(s) - } else { - out[r] = "" - } - } - return out -} - -// bundleTagKeys is tagKeys over every tag value in the bundle (trimmed), the -// vocabulary both lint's tag-hygiene and analyze's clusters fold against. -func bundleTagKeys(b *Bundle) map[string]string { - seen := map[string]bool{} - var raws []string - for _, n := range b.Nodes { - for _, t := range nodeTags(n) { - if t = strings.TrimSpace(t); t != "" && !seen[t] { - seen[t] = true - raws = append(raws, t) - } - } - } - return tagKeys(raws) -}