466-c review: restore only what a version made by propose dropped; the answer counts the versions written

Builds: design 55 §1.1, §10; lead answers L-466-4, L-466-5 (issue 466 note 18), note 20 items (a), (b); 466/AC5, AC7
This commit is contained in:
2026-11-25 17:13:15 +01:00
parent ef7d3f69d2
commit 2799ba177c
4 changed files with 260 additions and 114 deletions
@@ -131,6 +131,10 @@ func TestItsProcessesAreThePreparationTheActAndTheJudge(t *testing.T) {
t.Fatalf("keep %v", keep)
}
h, _ := watch["health"].(map[string]any)
// 466/AC7: the manifest names knowledge_restore and ModuleTools holds it, in the manifest's order.
if !contains(ModuleTools, RestoreTool) || !contains(m.Tools, RestoreTool) {
t.Fatalf("knowledge_restore is not in the manifest and ModuleTools: %v %v", m.Tools, ModuleTools)
}
if watch == nil || watch["run"].([]any)[1] != "watch" || h["kind"] != "tool" || h["tool"] != HealthTool ||
!reflect.DeepEqual(m.Tools, ModuleTools) {
t.Fatalf("watch %v, tools %v", watch, m.Tools)
@@ -9,7 +9,6 @@ import (
"context"
"encoding/json"
"fmt"
"reflect"
"sort"
"strings"
)
@@ -27,10 +26,86 @@ type RestoredRecord struct {
func insightKey(in Insight) string { return in.Date + "\x00" + in.By + "\x00" + in.Before }
// restoredOf is the served record with what an earlier accepted version held and it lacks put back, and a line for
// each entry naming the version it came from; nil when nothing is missing.
func restoredOf(served *Record, versions []Version) (*Record, []string) {
// restoreField is one field of a record that propose does not take: how to tell it is held, and how to copy it.
type restoreField struct {
name string
has func(*Record) bool
copy func(dst, src *Record)
value func(*Record) any
clear func(*Record)
}
var restoreFields = []restoreField{
{"reconstructed", func(r *Record) bool { return r.Reconstructed != nil }, func(d, s *Record) { v := *s.Reconstructed; d.Reconstructed = &v }, func(r *Record) any { return r.Reconstructed }, func(r *Record) { r.Reconstructed = nil }},
{"amended", func(r *Record) bool { return len(r.Amended) > 0 }, func(d, s *Record) { d.Amended = append([]string(nil), s.Amended...) }, func(r *Record) any { return r.Amended }, func(r *Record) { r.Amended = nil }},
{"touches", func(r *Record) bool { return len(r.Touches) > 0 }, func(d, s *Record) { d.Touches = append([]string(nil), s.Touches...) }, func(r *Record) any { return r.Touches }, func(r *Record) { r.Touches = nil }},
{"the imported fields", func(r *Record) bool { return len(r.Extra) > 0 }, func(d, s *Record) {
d.Extra = map[string]string{}
for k, v := range s.Extra {
d.Extra[k] = v
}
}, func(r *Record) any { return r.Extra }, func(r *Record) { r.Extra = nil }},
{"source", func(r *Record) bool { return r.Source != "" }, func(d, s *Record) { d.Source = s.Source }, func(r *Record) any { return r.Source }, func(r *Record) { r.Source = "" }},
{"aliases", func(r *Record) bool { return len(r.Aliases) > 0 }, func(d, s *Record) {
d.Aliases = map[string]string{}
for k, v := range s.Aliases {
d.Aliases[k] = v
}
}, func(r *Record) any { return r.Aliases }, func(r *Record) { r.Aliases = nil }},
}
// restoreStep is a field put back and the index of the accepted version it comes from.
type restoreStep struct {
field restoreField
from int
}
// droppedByPropose reads the accepted versions in order and finds what a version made by propose dropped: an accepted
// version whose version just before it waited as a pending version (propose, then its reviews, then accept) and that
// lacks an insight, or a field, the accepted version before it held. A version a refresh, a form-only change or a
// recomputing of marks wrote is no such version, and what it removed is not taken back. Each entry comes from the
// accepted version just before the one that lacks it.
func droppedByPropose(versions []Version) (insights map[string]int, fields map[string]restoreStep) {
insights, fields = map[string]int{}, map[string]restoreStep{}
prev := -1
for i, v := range versions {
if v.Record == nil || v.Record.Pending != nil || !v.Record.Accepted() {
continue
}
if prev >= 0 && i > 0 && versions[i-1].Record != nil && versions[i-1].Record.Pending != nil {
before, now := versions[prev].Record, v.Record
have := map[string]bool{}
for _, in := range now.Insights {
have[insightKey(in)] = true
}
for _, in := range before.Insights {
if !have[insightKey(in)] {
insights[insightKey(in)] = prev
}
}
for _, f := range restoreFields {
if f.has(before) && !f.has(now) {
fields[f.name] = restoreStep{f, prev}
}
}
}
prev = i
}
return insights, fields
}
func versionNumber(versions []Version, i int) int {
if versions[i].N != 0 {
return versions[i].N
}
return i + 1
}
// restoredOf is the served record with what a version made by propose dropped put back, and a line for each entry
// naming the version it came from; nil when nothing is missing.
func restoredOf(served *Record, versions []Version) (*Record, []string, map[string]int) {
r := served.Clone()
dropped, fields := droppedByPropose(versions)
held := map[string]bool{}
for _, in := range served.Insights {
held[insightKey(in)] = true
@@ -41,80 +116,34 @@ func restoredOf(served *Record, versions []Version) (*Record, []string) {
if v.Record == nil || v.Record.Pending != nil || !v.Record.Accepted() {
continue
}
n := v.N
if n == 0 {
n = i + 1
}
for _, in := range v.Record.Insights {
if !held[insightKey(in)] {
if from, ok := dropped[insightKey(in)]; ok && from == i && !held[insightKey(in)] {
held[insightKey(in)] = true
added = append(added, in)
said = append(said, fmt.Sprintf("insight %s by %s (version %d)", in.Date, in.By, n))
said = append(said, fmt.Sprintf("insight %s by %s (version %d)", in.Date, in.By, versionNumber(versions, i)))
}
}
}
// A field is put back from the latest accepted version that held it.
for i := len(versions) - 1; i >= 0; i-- {
v := versions[i]
if v.Record == nil || v.Record.Pending != nil || !v.Record.Accepted() {
continue
}
n := v.N
if n == 0 {
n = i + 1
}
o := v.Record
if r.Reconstructed == nil && o.Reconstructed != nil {
b := *o.Reconstructed
r.Reconstructed = &b
said = append(said, fmt.Sprintf("reconstructed (version %d)", n))
}
if len(r.Amended) == 0 && len(o.Amended) > 0 {
r.Amended = append([]string(nil), o.Amended...)
said = append(said, fmt.Sprintf("amended (version %d)", n))
}
if len(r.Touches) == 0 && len(o.Touches) > 0 {
r.Touches = append([]string(nil), o.Touches...)
said = append(said, fmt.Sprintf("touches (version %d)", n))
}
if len(r.Extra) == 0 && len(o.Extra) > 0 {
r.Extra = map[string]string{}
for k, x := range o.Extra {
r.Extra[k] = x
}
said = append(said, fmt.Sprintf("the imported fields (version %d)", n))
}
if r.Source == "" && o.Source != "" {
r.Source = o.Source
said = append(said, fmt.Sprintf("source (version %d)", n))
}
if len(r.Aliases) == 0 && len(o.Aliases) > 0 {
r.Aliases = map[string]string{}
for k, x := range o.Aliases {
r.Aliases[k] = x
}
said = append(said, fmt.Sprintf("aliases (version %d)", n))
from := map[string]int{}
for _, f := range restoreFields {
if st, ok := fields[f.name]; ok && !f.has(served) {
f.copy(r, versions[st.from].Record)
from[f.name] = st.from
said = append(said, fmt.Sprintf("%s (version %d)", f.name, versionNumber(versions, st.from)))
}
}
if len(said) == 0 {
return nil, nil
return nil, nil, nil
}
r.Insights = append(append([]Insight(nil), served.Insights...), added...)
sort.SliceStable(r.Insights, func(i, j int) bool { return r.Insights[i].Date < r.Insights[j].Date })
return r, said
return r, said, from
}
// checkRestore is the restoring version's own check: every served insight is still there, each insight added was held
// by an earlier accepted version, and nothing but the insights and the fields restored differs from the served record.
func checkRestore(served, next *Record, versions []Version) error {
held := map[string]bool{}
for _, v := range versions {
if v.Record != nil && v.Record.Pending == nil && v.Record.Accepted() {
for _, in := range v.Record.Insights {
held[insightKey(in)] = true
}
}
}
// checkRestore is the restoring version's own check: every served insight is still there, each insight added is held
// by the accepted version it was taken from, each field put back is the value of that version and was empty in the
// served record, and no other field of the served record differs.
func checkRestore(served, next *Record, versions []Version, fields map[string]int) error {
have := map[string]bool{}
for _, in := range next.Insights {
have[insightKey(in)] = true
@@ -124,22 +153,48 @@ func checkRestore(served, next *Record, versions []Version) error {
return fmt.Errorf("the insight of %s is missing from the restored version", in.Date)
}
}
dropped, _ := droppedByPropose(versions)
serves := map[string]bool{}
for _, in := range served.Insights {
held[insightKey(in)] = true
serves[insightKey(in)] = true
}
for _, in := range next.Insights {
if !held[insightKey(in)] {
return fmt.Errorf("the insight of %s was held by no accepted version", in.Date)
from, ok := dropped[insightKey(in)]
if serves[insightKey(in)] {
continue
}
if !ok {
return fmt.Errorf("the insight of %s was dropped by no version made by propose", in.Date)
}
held := false
for _, x := range versions[from].Record.Insights {
held = held || insightKey(x) == insightKey(in)
}
if !held {
return fmt.Errorf("the insight of %s is not held by version %d", in.Date, versionNumber(versions, from))
}
}
a, b := served.Clone(), next.Clone()
for _, r := range []*Record{a, b} {
r.Insights, r.Reconstructed, r.Amended, r.Touches, r.Extra, r.Source, r.Aliases = nil, nil, nil, nil, nil, "", nil
a.Insights, b.Insights = nil, nil
for _, f := range restoreFields {
i, put := fields[f.name]
if !put {
continue
}
if f.has(served) || !f.has(next) {
return fmt.Errorf("%s was not empty in the served record, or was not put back", f.name)
}
got, _ := json.Marshal(f.value(next))
want, _ := json.Marshal(f.value(versions[i].Record))
if string(got) != string(want) {
return fmt.Errorf("%s is not the value version %d held", f.name, versionNumber(versions, i))
}
f.clear(b)
}
ja, _ := json.Marshal(a)
jb, _ := json.Marshal(b)
if !reflect.DeepEqual(ja, jb) {
return fmt.Errorf("something other than insights and fields differs")
if string(ja) != string(jb) {
return fmt.Errorf("a field of the served record other than the insights and the fields put back differs")
}
return nil
}
@@ -168,7 +223,7 @@ func (k *KB) Restore(only *Key, kind string, dry bool) ([]RestoredRecord, error)
if err != nil {
return nil, fmt.Errorf("%s: its versions cannot be read: %v", key, err)
}
next, said := restoredOf(e.Current, versions)
next, said, fromFields := restoredOf(e.Current, versions)
if next == nil {
continue
}
@@ -177,7 +232,7 @@ func (k *KB) Restore(only *Key, kind string, dry bool) ([]RestoredRecord, error)
case e.Pending != nil:
rr.Skipped = "a version waits for its review: it is restored once that is decided"
default:
if err := checkRestore(e.Current, next, versions); err != nil {
if err := checkRestore(e.Current, next, versions, fromFields); err != nil {
rr.Skipped = "the check refused it: " + err.Error()
} else if !dry {
why := "restored what a version dropped: " + strings.Join(said, "; ")
@@ -2,62 +2,143 @@ package main
import (
"context"
"fmt"
"strings"
"testing"
"time"
)
// 466/AC5: a record that lost an insight and a field an earlier accepted version held gets them back in one version by
// the knowledge base; a dry run writes nothing, and a second run writes nothing.
// 466/AC5: a record that lost an insight and a field an earlier accepted version held, in a version made by propose
// (a pending version, then an accepted one marked insight, as the old accept wrote it), gets them back in one version by
// the knowledge base; a dry run lists each entry and writes nothing; a second run writes nothing; what a refresh removed
// is not restored; a record with a version waiting for its review is skipped, saying so.
func TestRestoreGivesBackWhatAVersionDropped(t *testing.T) {
eachStore(t, func(t *testing.T, s Store) {
w := imported(t, s)
n := w.reserved(t, "author@g14")
p := valid(n)
w.accepted(t, "author@g14", p)
key := Key{KindDecision, n}
ctx := context.Background()
e := mustGet(t, s, key)
r := e.Current.Clone()
no := false
r.Reconstructed = &no
if err := s.Save(ctx, Version{By: "test", At: time.Now(), Why: "seed", Record: r}, true, false, e.Revision); err != nil {
t.Fatal(err)
}
p.Insight = "it said less"
p.Sections[2].Text = "Merges land sooner, by about a minute."
w.accepted(t, "author@g14", p)
// What an older propose did: a version that holds neither the insight nor the field.
e = mustGet(t, s, key)
lost := e.Current.Clone()
lost.Insights, lost.Reconstructed = nil, nil
if err := s.Save(ctx, Version{By: "author@g14", At: time.Now(), Why: "an insight that lost them", Record: lost}, true, false, e.Revision); err != nil {
t.Fatal(err)
}
before := mustGet(t, s, key).Versions
var tools []toolRun
for _, tool := range moduleTools(w.k, callerOf) {
tools = append(tools, toolRun{tool.Name, tool.Run})
}
out, err := callTool(t, tools, RestoreTool, map[string]any{"dry-run": true})
recs, _ := out["records"].([]any)
if err != nil || len(recs) != 1 || !strings.Contains(recs[0].(map[string]any)["record"].(string), itoa4(n)) || mustGet(t, s, key).Versions != before {
t.Fatalf("dry run: %v %v", err, out)
// accepted is a record accepted with reconstructed: false, then given one insight by the knowledge base as it
// is now; it answers its key and the number of the version that holds them.
accepted := func(t *testing.T) (Key, int) {
n := w.reserved(t, "author@g14")
p := valid(n)
w.accepted(t, "author@g14", p)
key := Key{KindDecision, n}
e := mustGet(t, s, key)
r := e.Current.Clone()
no := false
r.Reconstructed = &no
if err := s.Save(ctx, Version{By: "test", At: time.Now(), Why: "seed", Record: r}, true, false, e.Revision); err != nil {
t.Fatal(err)
}
p.Insight = "it said less"
p.Sections[2].Text = "Merges land sooner, by about a minute."
w.accepted(t, "author@g14", p)
return key, mustGet(t, s, key).Versions
}
if _, err := callTool(t, tools, RestoreTool, map[string]any{"number": float64(n), "kind": "decision"}); err != nil {
t.Fatal(err)
// lose is what an older propose and accept did with a second insight: a pending version, then the accepted one
// holding only the new insight and none of the fields.
lose := func(t *testing.T, key Key) {
e := mustGet(t, s, key)
in := Insight{Date: "2026-10-12", Before: "it said more", By: "corrector@ace"}
pend := e.Current.Clone()
pend.Status, pend.Insights, pend.Reconstructed = StatusProposed, nil, nil
pend.Pending = &PendingState{Insight: in}
if err := s.Save(ctx, Version{By: "corrector@ace", At: time.Now(), Why: "a progressive insight proposed", Record: pend, Insight: true}, false, false, e.Revision); err != nil {
t.Fatal(err)
}
e = mustGet(t, s, key)
lost := e.Current.Clone()
lost.Insights, lost.Reconstructed = []Insight{in}, nil
if err := s.Save(ctx, Version{By: "the knowledge base", At: time.Now(), Why: "accepted", Record: lost, Insight: true}, true, true, e.Revision); err != nil {
t.Fatal(err)
}
}
e = mustGet(t, s, key)
if e.Versions != before+1 || len(e.Current.Insights) != 1 || e.Current.Insights[0].Before != "it said less" ||
e.Current.Insights[0].By != "author@g14" || e.Current.Reconstructed == nil || *e.Current.Reconstructed {
t.Fatalf("not restored: %d versions (was %d), %+v", e.Versions, before, e.Current.Insights)
run := func(t *testing.T, key Key, args map[string]any) map[string]any {
args["kind"], args["number"] = key.Kind, float64(key.Number)
out, err := callTool(t, tools, RestoreTool, args)
if err != nil {
t.Fatal(err)
}
return out
}
if got := w.said.of(EventChanged); len(got) == 0 || got[len(got)-1]["by"] != "the knowledge base" {
t.Fatalf("no changed event by the knowledge base: %v", got)
}
out, err = callTool(t, tools, RestoreTool, map[string]any{})
if recs, _ := out["records"].([]any); err != nil || len(recs) != 0 || mustGet(t, s, key).Versions != before+1 {
t.Fatalf("a second run wrote: %v %v", err, out)
records := func(out map[string]any) []map[string]any {
var got []map[string]any
for _, r := range out["records"].([]any) {
got = append(got, r.(map[string]any))
}
return got
}
t.Run("a version made by propose dropped them", func(t *testing.T) {
key, held := accepted(t)
lose(t, key)
before := mustGet(t, s, key).Versions
want := []string{fmt.Sprintf("insight 2026-10-11 by author@g14 (version %d)", held), fmt.Sprintf("reconstructed (version %d)", held)}
dry := run(t, key, map[string]any{"dry-run": true})
recs := records(dry)
if len(recs) != 1 || fmt.Sprint(recs[0]["restored"]) != fmt.Sprint(toAny(want)) || recs[0]["skipped"] != nil ||
dry["written"] != false || mustGet(t, s, key).Versions != before {
t.Fatalf("dry run: %v", dry)
}
out := run(t, key, map[string]any{})
e := mustGet(t, s, key)
in := e.Current.Insights
if out["written"] != true || out["versions-written"] != float64(1) || e.Versions != before+1 || len(in) != 2 ||
in[0].Before != "it said less" || in[0].By != "author@g14" || in[1].Before != "it said more" || in[1].By != "corrector@ace" ||
e.Current.Reconstructed == nil || *e.Current.Reconstructed {
t.Fatalf("not restored: %v, %d versions (was %d), %+v", out, e.Versions, before, in)
}
if got := w.said.of(EventChanged); len(got) == 0 || got[len(got)-1]["by"] != "the knowledge base" {
t.Fatalf("no changed event by the knowledge base: %v", got)
}
again := run(t, key, map[string]any{})
if len(records(again)) != 0 || again["written"] != false || mustGet(t, s, key).Versions != before+1 {
t.Fatalf("a second run wrote: %v", again)
}
})
t.Run("what a refresh removed is not restored", func(t *testing.T) {
key, _ := accepted(t)
e := mustGet(t, s, key)
refreshed := e.Current.Clone()
refreshed.Reconstructed = nil
if err := s.Save(ctx, Version{By: "import@test", At: time.Now(), Why: "refreshed", Record: refreshed}, true, false, e.Revision); err != nil {
t.Fatal(err)
}
before := mustGet(t, s, key).Versions
out := run(t, key, map[string]any{})
if e := mustGet(t, s, key); len(records(out)) != 0 || e.Versions != before || e.Current.Reconstructed != nil {
t.Fatalf("a field a refresh removed was put back: %v", out)
}
})
t.Run("a record with a version waiting is skipped, and says so", func(t *testing.T) {
key, _ := accepted(t)
lose(t, key)
p := insightTo(t, w, key)
p.Insight = "it said nothing of the day"
if _, err := w.k.Propose("author@g14", p); err != nil {
t.Fatal(err)
}
before := mustGet(t, s, key).Versions
out := run(t, key, map[string]any{})
recs := records(out)
if len(recs) != 1 || !strings.Contains(fmt.Sprint(recs[0]["skipped"]), "waits for its review") ||
out["written"] != false || mustGet(t, s, key).Versions != before {
t.Fatalf("a record with a version waiting: %v", out)
}
})
})
}
func toAny(list []string) []any {
out := make([]any, len(list))
for i, s := range list {
out[i] = s
}
return out
}
@@ -472,7 +472,13 @@ func moduleTools(k *KB, caller func(map[string]any) string) []stdio.Tool {
if err != nil {
return nil, err
}
return map[string]any{"records": done, "written": !dry}, nil
wrote := 0
for _, d := range done {
if d.Version > 0 {
wrote++
}
}
return map[string]any{"records": done, "versions-written": wrote, "written": wrote > 0}, nil
}},
}
}