manus-tracker

tracker for scientific manuscripts
git clone git://src.adamsgaard.dk/manus-tracker # fast
git clone https://src.adamsgaard.dk/manus-tracker.git # slow
Log | Files | Refs | README Back to index

commit ad17f5441ed6be33b0458e8c91dab5c2d041c7f4
Author: Anders Damsgaard <anders@adamsgaard.dk>
Date:   Thu, 26 Nov 2026 06:44:07 +0300

feat(store): add recutils store for manuscripts, tasks, comments and relations

Diffstat:
A.gitignore | 1+
Ago.mod | 3+++
Astore/model.go | 246+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Astore/rec.go | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Astore/store.go | 387+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Astore/store_test.go | 153+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 906 insertions(+), 0 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1 @@ +/manus diff --git a/go.mod b/go.mod @@ -0,0 +1,3 @@ +module manus + +go 1.27 diff --git a/store/model.go b/store/model.go @@ -0,0 +1,246 @@ +package store + +import ( + "fmt" + "slices" + "strconv" + "strings" +) + +var ( + Stages = []string{"idea", "draft", "internal", "submitted", "review", "revision", "accepted", "published", "dropped"} + Statuses = []string{"todo", "doing", "blocked", "done"} + Kinds = []string{"latex", "docx", "odt"} + Roles = []string{"lead", "coauthor"} + RelKinds = []string{"blocks", "relates", "duplicates", "parent"} +) + +// ManuscriptKeys lists the editable manuscript fields in file order. +var ManuscriptKeys = []string{ + "title", "dir", "src", "repo", "main", "kind", "stage", "role", "lead", + "coauthors", "ball", "journal", "deadline", "doi", "parent", "revision", "tag", +} + +type Manuscript struct { + ID string + Fields map[string]string + Extra []Field + Tasks []*Task +} + +func (m *Manuscript) Get(k string) string { return m.Fields[k] } + +func (m *Manuscript) Revision() int { + n, _ := strconv.Atoi(m.Fields["revision"]) + return n +} + +// Set validates and assigns a manuscript field. +func (m *Manuscript) Set(k, v string) error { + if !slices.Contains(ManuscriptKeys, k) { + return fmt.Errorf("unknown field %q (have: %s)", k, strings.Join(ManuscriptKeys, ", ")) + } + v = strings.TrimSpace(v) + allowed := map[string][]string{"stage": Stages, "kind": Kinds, "role": Roles}[k] + if v != "" && allowed != nil && !slices.Contains(allowed, v) { + return fmt.Errorf("invalid %s %q (have: %s)", k, v, strings.Join(allowed, ", ")) + } + if v != "" && k == "revision" { + if _, err := strconv.Atoi(v); err != nil { + return fmt.Errorf("revision must be an integer") + } + } + if m.Fields == nil { + m.Fields = map[string]string{} + } + m.Fields[k] = v + return nil +} + +type Task struct { + ID int + Title string + Status string + Created string + Closed string + Due string + Source string + Rels []Rel + Comments []Comment + Extra []Field +} + +type Comment struct { + At, Text string +} + +type Rel struct { + Kind string + To Ref +} + +// Ref addresses a task globally as "manuscript#n". +type Ref struct { + MS string + N int +} + +func (r Ref) String() string { return fmt.Sprintf("%s#%d", r.MS, r.N) } + +// ParseRef accepts "ms#n", "#n" or "n"; the short forms use def as manuscript. +func ParseRef(s, def string) (Ref, error) { + ms, num, ok := strings.Cut(s, "#") + if !ok { + ms, num = "", s + } + if ms == "" { + ms = def + } + n, err := strconv.Atoi(num) + if err != nil || n < 1 { + return Ref{}, fmt.Errorf("bad task reference %q (want manuscript#n)", s) + } + if ms == "" { + return Ref{}, fmt.Errorf("task reference %q needs a manuscript (not inside one)", s) + } + return Ref{ms, n}, nil +} + +func NormRelKind(k string) (string, error) { + if k == "dup" { + k = "duplicates" + } + if !slices.Contains(RelKinds, k) { + return "", fmt.Errorf("unknown relation %q (have: %s)", k, strings.Join(RelKinds, ", ")) + } + return k, nil +} + +func ValidStatus(s string) error { + if !slices.Contains(Statuses, s) { + return fmt.Errorf("invalid status %q (have: %s)", s, strings.Join(Statuses, ", ")) + } + return nil +} + +func (m *Manuscript) Task(n int) *Task { + for _, t := range m.Tasks { + if t.ID == n { + return t + } + } + return nil +} + +func (m *Manuscript) NextTaskID() int { + n := 0 + for _, t := range m.Tasks { + n = max(n, t.ID) + } + return n + 1 +} + +func (m *Manuscript) records() []Record { + mr := Record{Type: "manuscript", Fields: []Field{{"id", m.ID}}} + for _, k := range ManuscriptKeys { + if v := m.Fields[k]; v != "" { + mr.Fields = append(mr.Fields, Field{k, v}) + } + } + mr.Fields = append(mr.Fields, m.Extra...) + recs := []Record{mr} + for _, t := range m.Tasks { + tr := Record{Type: "task", Fields: []Field{{"id", strconv.Itoa(t.ID)}, {"title", t.Title}, {"status", t.Status}}} + opt := func(k, v string) { + if v != "" { + tr.Fields = append(tr.Fields, Field{k, v}) + } + } + opt("created", t.Created) + opt("closed", t.Closed) + opt("due", t.Due) + opt("source", t.Source) + for _, r := range t.Rels { + tr.Fields = append(tr.Fields, Field{"rel", r.Kind + " " + r.To.String()}) + } + tr.Fields = append(tr.Fields, t.Extra...) + recs = append(recs, tr) + } + for _, t := range m.Tasks { + for _, c := range t.Comments { + recs = append(recs, Record{Type: "comment", Fields: []Field{ + {"task", strconv.Itoa(t.ID)}, {"at", c.At}, {"text", c.Text}, + }}) + } + } + return recs +} + +func fromRecords(recs []Record) (*Manuscript, error) { + m := &Manuscript{Fields: map[string]string{}} + for _, r := range recs { + switch r.Type { + case "manuscript": + for _, f := range r.Fields { + switch { + case f.Key == "id": + m.ID = f.Val + case slices.Contains(ManuscriptKeys, f.Key): + m.Fields[f.Key] = f.Val + default: + m.Extra = append(m.Extra, f) + } + } + case "task": + t := &Task{} + for _, f := range r.Fields { + switch f.Key { + case "id": + n, err := strconv.Atoi(f.Val) + if err != nil { + return nil, fmt.Errorf("task id %q: %v", f.Val, err) + } + t.ID = n + case "title": + t.Title = f.Val + case "status": + t.Status = f.Val + case "created": + t.Created = f.Val + case "closed": + t.Closed = f.Val + case "due": + t.Due = f.Val + case "source": + t.Source = f.Val + case "rel": + kind, to, _ := strings.Cut(f.Val, " ") + ref, err := ParseRef(strings.TrimSpace(to), m.ID) + if err != nil { + return nil, err + } + t.Rels = append(t.Rels, Rel{kind, ref}) + default: + t.Extra = append(t.Extra, f) + } + } + if t.Status == "" { + t.Status = "todo" + } + m.Tasks = append(m.Tasks, t) + case "comment": + n, _ := strconv.Atoi(r.Get("task")) + t := m.Task(n) + if t == nil { + return nil, fmt.Errorf("comment for unknown task %d", n) + } + t.Comments = append(t.Comments, Comment{r.Get("at"), r.Get("text")}) + default: + return nil, fmt.Errorf("unknown record type %q", r.Type) + } + } + if m.ID == "" { + return nil, fmt.Errorf("missing manuscript record") + } + return m, nil +} diff --git a/store/rec.go b/store/rec.go @@ -0,0 +1,116 @@ +package store + +import ( + "bufio" + "fmt" + "io" + "strings" +) + +// Field is one key/value pair of a record; keys may repeat. +type Field struct { + Key, Val string +} + +// Record is a recutils record with the type set by the preceding %rec line. +type Record struct { + Type string + Fields []Field +} + +func (r Record) Get(key string) string { + for _, f := range r.Fields { + if f.Key == key { + return f.Val + } + } + return "" +} + +func (r Record) All(key string) []string { + var v []string + for _, f := range r.Fields { + if f.Key == key { + v = append(v, f.Val) + } + } + return v +} + +// ParseRec reads records in GNU recutils format: "key: value" lines, +// "+ " continuation lines, blank-line separators, "%rec: type" headers. +func ParseRec(r io.Reader) ([]Record, error) { + var ( + recs []Record + cur *Record + typ string + n int + ) + flush := func() { + if cur != nil && len(cur.Fields) > 0 { + recs = append(recs, *cur) + } + cur = nil + } + sc := bufio.NewScanner(r) + sc.Buffer(make([]byte, 0, 64*1024), 4*1024*1024) + for sc.Scan() { + n++ + line := sc.Text() + switch { + case strings.TrimSpace(line) == "": + flush() + case strings.HasPrefix(line, "#"): + case strings.HasPrefix(line, "%"): + flush() + k, v, _ := strings.Cut(line[1:], ":") + if k == "rec" { + typ = strings.TrimSpace(v) + } + case strings.HasPrefix(line, "+"): + if cur == nil || len(cur.Fields) == 0 { + return nil, fmt.Errorf("line %d: continuation without field", n) + } + f := &cur.Fields[len(cur.Fields)-1] + f.Val += "\n" + strings.TrimPrefix(line[1:], " ") + default: + k, v, ok := strings.Cut(line, ":") + if !ok || strings.ContainsAny(k, " \t") || k == "" { + return nil, fmt.Errorf("line %d: expected 'key: value'", n) + } + if cur == nil { + cur = &Record{Type: typ} + } + cur.Fields = append(cur.Fields, Field{k, strings.TrimPrefix(v, " ")}) + } + } + flush() + return recs, sc.Err() +} + +// WriteRec writes records, emitting a %rec header whenever the type changes. +func WriteRec(w io.Writer, recs []Record) error { + bw := bufio.NewWriter(w) + typ := "" + for i, r := range recs { + if i > 0 { + bw.WriteString("\n") + } + if r.Type != typ { + fmt.Fprintf(bw, "%%rec: %s\n\n", r.Type) + typ = r.Type + } + for _, f := range r.Fields { + lines := strings.Split(f.Val, "\n") + fmt.Fprintf(bw, "%s: %s\n", f.Key, lines[0]) + for _, l := range lines[1:] { + if l == "" { + bw.WriteString("+\n") + } else { + fmt.Fprintf(bw, "+ %s\n", l) + } + } + } + } + return bw.Flush() +} diff --git a/store/store.go b/store/store.go @@ -0,0 +1,387 @@ +package store + +import ( + "bytes" + "fmt" + "os" + "os/exec" + "path/filepath" + "slices" + "sort" + "strings" + "syscall" + "time" +) + +const DataDir = ".tracker" + +type Store struct { + Root string + MS map[string]*Manuscript + dirty map[string]bool + files []string +} + +// Now is replaceable in tests. +var Now = time.Now + +func Today() string { return Now().Format("2006-01-02") } + +// Load reads all manuscripts under root/.tracker without locking; writes +// are atomic renames, so a concurrent reader sees whole files. +func Load(root string) (*Store, error) { + s := &Store{Root: root, MS: map[string]*Manuscript{}, dirty: map[string]bool{}} + paths, err := filepath.Glob(filepath.Join(root, DataDir, "*.rec")) + if err != nil { + return nil, err + } + for _, p := range paths { + f, err := os.Open(p) + if err != nil { + return nil, err + } + recs, err := ParseRec(f) + f.Close() + if err != nil { + return nil, fmt.Errorf("%s: %v", p, err) + } + m, err := fromRecords(recs) + if err != nil { + return nil, fmt.Errorf("%s: %v", p, err) + } + s.MS[m.ID] = m + } + return s, nil +} + +// Edit locks the tracker, loads it, runs fn, saves touched manuscripts and, +// if root is a git repository, commits the touched files with msg. +func Edit(root string, fn func(s *Store) (msg string, err error)) error { + if err := os.MkdirAll(filepath.Join(root, DataDir), 0o755); err != nil { + return err + } + lf, err := os.OpenFile(filepath.Join(root, DataDir, ".lock"), os.O_CREATE|os.O_RDWR, 0o644) + if err != nil { + return err + } + defer lf.Close() + if err := syscall.Flock(int(lf.Fd()), syscall.LOCK_EX); err != nil { + return err + } + defer syscall.Flock(int(lf.Fd()), syscall.LOCK_UN) + + s, err := Load(root) + if err != nil { + return err + } + msg, err := fn(s) + if err != nil { + return err + } + for id := range s.dirty { + if err := s.save(s.MS[id]); err != nil { + return err + } + s.files = append(s.files, filepath.Join(DataDir, id+".rec")) + } + if msg == "" || len(s.files) == 0 { + return nil + } + return commit(root, msg, s.files) +} + +// Touch marks a manuscript for saving. +func (s *Store) Touch(m *Manuscript) { s.dirty[m.ID] = true } + +// TouchFile adds another file (relative to root) to the commit. +func (s *Store) TouchFile(rel string) { s.files = append(s.files, rel) } + +func (s *Store) save(m *Manuscript) error { + p := filepath.Join(s.Root, DataDir, m.ID+".rec") + var buf bytes.Buffer + if err := WriteRec(&buf, m.records()); err != nil { + return err + } + tmp := p + ".tmp" + if err := os.WriteFile(tmp, buf.Bytes(), 0o644); err != nil { + return err + } + return os.Rename(tmp, p) +} + +func commit(root, msg string, files []string) error { + if os.Getenv("MANUS_NOGIT") != "" { + return nil + } + if _, err := os.Stat(filepath.Join(root, ".git")); err != nil { + return nil + } + slices.Sort(files) + files = slices.Compact(files) + git := func(args ...string) error { + out, err := exec.Command("git", append([]string{"-C", root}, args...)...).CombinedOutput() + if err != nil { + return fmt.Errorf("git %s: %v: %s", args[0], err, bytes.TrimSpace(out)) + } + return nil + } + if err := git(append([]string{"add", "--"}, files...)...); err != nil { + return err + } + if exec.Command("git", append([]string{"-C", root, "diff", "--cached", "--quiet", "--"}, files...)...).Run() == nil { + return nil + } + return git(append([]string{"commit", "-q", "-m", "chore(tracker): " + msg, "--"}, files...)...) +} + +func (s *Store) Get(id string) (*Manuscript, error) { + m, ok := s.MS[id] + if !ok { + return nil, fmt.Errorf("no manuscript %q", id) + } + return m, nil +} + +func (s *Store) Task(r Ref) (*Manuscript, *Task, error) { + m, err := s.Get(r.MS) + if err != nil { + return nil, nil, err + } + t := m.Task(r.N) + if t == nil { + return nil, nil, fmt.Errorf("no task %s", r) + } + return m, t, nil +} + +// IDs returns manuscript ids sorted by stage order, then id. +func (s *Store) IDs() []string { + ids := make([]string, 0, len(s.MS)) + for id := range s.MS { + ids = append(ids, id) + } + sort.Slice(ids, func(i, j int) bool { + a, b := slices.Index(Stages, s.MS[ids[i]].Get("stage")), slices.Index(Stages, s.MS[ids[j]].Get("stage")) + if a != b { + return a < b + } + return ids[i] < ids[j] + }) + return ids +} + +// Path returns the absolute manuscript directory. +func (s *Store) Path(m *Manuscript) string { + d := m.Get("dir") + if d == "" { + d = m.ID + } + if filepath.IsAbs(d) { + return d + } + return filepath.Join(s.Root, d) +} + +// SrcPath returns the absolute source directory. +func (s *Store) SrcPath(m *Manuscript) string { + return filepath.Join(s.Path(m), m.Get("src")) +} + +// RepoPath returns the absolute git repository directory, or "". +func (s *Store) RepoPath(m *Manuscript) string { + if r := m.Get("repo"); r != "" { + return filepath.Join(s.Path(m), r) + } + return "" +} + +// At returns the manuscript whose directory most specifically contains dir. +func (s *Store) At(dir string) *Manuscript { + var best *Manuscript + bestLen := -1 + for _, m := range s.MS { + p := s.Path(m) + if (dir == p || strings.HasPrefix(dir, p+string(filepath.Separator))) && len(p) > bestLen { + best, bestLen = m, len(p) + } + } + return best +} + +// Children returns revisions whose parent is id. +func (s *Store) Children(id string) []*Manuscript { + var c []*Manuscript + for _, cid := range s.IDs() { + if s.MS[cid].Get("parent") == id { + c = append(c, s.MS[cid]) + } + } + return c +} + +// Lineage returns the revision chain ending at m, oldest first. +func (s *Store) Lineage(m *Manuscript) []*Manuscript { + chain := []*Manuscript{m} + seen := map[string]bool{m.ID: true} + for p := m.Get("parent"); p != "" && !seen[p]; { + pm, ok := s.MS[p] + if !ok { + break + } + seen[p] = true + chain = append([]*Manuscript{pm}, chain...) + p = pm.Get("parent") + } + return chain +} + +// Inverse lists relations pointing at r, named from r's point of view. +func (s *Store) Inverse(r Ref) []Rel { + inv := map[string]string{"blocks": "blocked-by", "parent": "child", "relates": "relates", "duplicates": "duplicated-by"} + var out []Rel + for _, id := range s.IDs() { + for _, t := range s.MS[id].Tasks { + for _, rel := range t.Rels { + if rel.To == r { + out = append(out, Rel{inv[rel.Kind], Ref{id, t.ID}}) + } + } + } + } + return out +} + +// Blockers returns unfinished tasks that block r. +func (s *Store) Blockers(r Ref) []Ref { + var out []Ref + for _, rel := range s.Inverse(r) { + if rel.Kind != "blocked-by" { + continue + } + if _, t, err := s.Task(rel.To); err == nil && t.Status != "done" { + out = append(out, rel.To) + } + } + return out +} + +// EffectiveStatus is "blocked" when an unfinished task blocks an open one. +func (s *Store) EffectiveStatus(r Ref, t *Task) string { + if t.Status != "done" && len(s.Blockers(r)) > 0 { + return "blocked" + } + return t.Status +} + +// SetStatus changes a task status and keeps the closed date consistent. +func SetStatus(t *Task, status string) error { + if err := ValidStatus(status); err != nil { + return err + } + t.Status = status + t.Closed = "" + if status == "done" { + t.Closed = Today() + } + return nil +} + +// AddTask appends a new task to m and returns it. +func (s *Store) AddTask(m *Manuscript, title string) (*Task, error) { + title = strings.TrimSpace(title) + if title == "" || strings.Contains(title, "\n") { + return nil, fmt.Errorf("task title must be a single non-empty line") + } + t := &Task{ID: m.NextTaskID(), Title: title, Status: "todo", Created: Today()} + m.Tasks = append(m.Tasks, t) + s.Touch(m) + return t, nil +} + +func (s *Store) Comment(m *Manuscript, t *Task, text string) error { + text = strings.TrimSpace(text) + if text == "" { + return fmt.Errorf("empty comment") + } + t.Comments = append(t.Comments, Comment{Now().Format("2006-01-02T15:04"), text}) + s.Touch(m) + return nil +} + +// Relate adds (or with del removes) a relation from a to b. +func (s *Store) Relate(a Ref, kind string, b Ref, del bool) error { + kind, err := NormRelKind(kind) + if err != nil { + return err + } + ma, ta, err := s.Task(a) + if err != nil { + return err + } + if _, _, err := s.Task(b); err != nil { + return err + } + if a == b { + return fmt.Errorf("a task cannot relate to itself") + } + rel := Rel{kind, b} + i := slices.Index(ta.Rels, rel) + switch { + case del && i < 0: + return fmt.Errorf("%s has no relation %s %s", a, kind, b) + case del: + ta.Rels = slices.Delete(ta.Rels, i, i+1) + case i >= 0: + return nil + default: + if kind == "blocks" && s.reaches(b, a) { + return fmt.Errorf("%s blocks %s would create a cycle", a, b) + } + ta.Rels = append(ta.Rels, rel) + } + s.Touch(ma) + return nil +} + +func (s *Store) reaches(from, to Ref) bool { + seen := map[Ref]bool{} + stack := []Ref{from} + for len(stack) > 0 { + r := stack[len(stack)-1] + stack = stack[:len(stack)-1] + if r == to { + return true + } + if seen[r] { + continue + } + seen[r] = true + if _, t, err := s.Task(r); err == nil { + for _, rel := range t.Rels { + if rel.Kind == "blocks" { + stack = append(stack, rel.To) + } + } + } + } + return false +} + +// Create registers a new manuscript. +func (s *Store) Create(id string, fields map[string]string) (*Manuscript, error) { + if id == "" || strings.ContainsAny(id, "/# \t\n") || strings.HasPrefix(id, ".") { + return nil, fmt.Errorf("invalid manuscript id %q", id) + } + if _, ok := s.MS[id]; ok { + return nil, fmt.Errorf("manuscript %q already exists", id) + } + m := &Manuscript{ID: id, Fields: map[string]string{}} + for k, v := range fields { + if err := m.Set(k, v); err != nil { + return nil, err + } + } + s.MS[id] = m + s.Touch(m) + return m, nil +} diff --git a/store/store_test.go b/store/store_test.go @@ -0,0 +1,153 @@ +package store + +import ( + "bytes" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +func init() { + Now = func() time.Time { return time.Date(2026, 11, 26, 10, 0, 0, 0, time.UTC) } +} + +func TestRecRoundTrip(t *testing.T) { + in := "%rec: manuscript\n\nid: a\ntitle: T\n\n%rec: comment\n\ntask: 1\ntext: line one\n+\n+ line three\n" + recs, err := ParseRec(strings.NewReader(in)) + if err != nil { + t.Fatal(err) + } + if len(recs) != 2 || recs[1].Get("text") != "line one\n\nline three" { + t.Fatalf("unexpected parse: %+v", recs) + } + var buf bytes.Buffer + if err := WriteRec(&buf, recs); err != nil { + t.Fatal(err) + } + if buf.String() != in { + t.Fatalf("round trip differs:\n%q\n%q", buf.String(), in) + } +} + +func TestRecErrors(t *testing.T) { + for _, in := range []string{"+ orphan\n", "no colon here\n"} { + if _, err := ParseRec(strings.NewReader(in)); err == nil { + t.Errorf("expected error for %q", in) + } + } +} + +func TestParseRef(t *testing.T) { + r, err := ParseRef("#3", "ms") + if err != nil || r != (Ref{"ms", 3}) { + t.Fatalf("got %v %v", r, err) + } + if _, err := ParseRef("3", ""); err == nil { + t.Fatal("expected error without default manuscript") + } + if _, err := ParseRef("a#x", ""); err == nil { + t.Fatal("expected error for non-numeric") + } +} + +func TestEditPersistsAndRelates(t *testing.T) { + root := t.TempDir() + err := Edit(root, func(s *Store) (string, error) { + a, err := s.Create("a", map[string]string{"stage": "draft"}) + if err != nil { + return "", err + } + b, _ := s.Create("b", nil) + t1, _ := s.AddTask(a, "first") + t2, _ := s.AddTask(b, "second") + if err := s.Relate(Ref{"a", t1.ID}, "blocks", Ref{"b", t2.ID}, false); err != nil { + return "", err + } + if err := s.Relate(Ref{"b", t2.ID}, "blocks", Ref{"a", t1.ID}, false); err == nil { + return "", os.ErrInvalid + } + return "", s.Comment(a, t1, "multi\nline") + }) + if err != nil { + t.Fatal(err) + } + s, err := Load(root) + if err != nil { + t.Fatal(err) + } + _, t2, err := s.Task(Ref{"b", 1}) + if err != nil { + t.Fatal(err) + } + if got := s.EffectiveStatus(Ref{"b", 1}, t2); got != "blocked" { + t.Fatalf("effective status = %s", got) + } + if inv := s.Inverse(Ref{"b", 1}); len(inv) != 1 || inv[0].Kind != "blocked-by" { + t.Fatalf("inverse = %v", inv) + } + _, t1, _ := s.Task(Ref{"a", 1}) + if t1.Comments[0].Text != "multi\nline" { + t.Fatalf("comment = %q", t1.Comments[0].Text) + } + SetStatus(t1, "done") + if s.EffectiveStatus(Ref{"b", 1}, t2) != "todo" || t1.Closed != "2026-11-26" { + t.Fatal("blocker done should unblock") + } +} + +func TestSetValidation(t *testing.T) { + m := &Manuscript{} + if err := m.Set("stage", "nope"); err == nil { + t.Fatal("expected stage error") + } + if err := m.Set("color", "x"); err == nil { + t.Fatal("expected unknown key error") + } + if err := m.Set("stage", "submitted"); err != nil { + t.Fatal(err) + } +} + +func TestAtAndLineage(t *testing.T) { + s := &Store{Root: "/r", MS: map[string]*Manuscript{ + "a": {ID: "a", Fields: map[string]string{"dir": "a"}}, + "a-r1": {ID: "a-r1", Fields: map[string]string{"dir": "a/sub", "parent": "a"}}, + }} + if m := s.At("/r/a/sub/figs"); m == nil || m.ID != "a-r1" { + t.Fatalf("At = %v", m) + } + if m := s.At("/r/ab"); m != nil { + t.Fatalf("At matched prefix without separator: %v", m.ID) + } + if l := s.Lineage(s.MS["a-r1"]); len(l) != 2 || l[0].ID != "a" { + t.Fatalf("lineage = %v", l) + } +} + +func TestEditCommits(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git not available") + } + root := t.TempDir() + for _, args := range [][]string{{"init", "-q"}, {"config", "user.email", "t@example.org"}, {"config", "user.name", "t"}} { + if out, err := exec.Command("git", append([]string{"-C", root}, args...)...).CombinedOutput(); err != nil { + t.Fatalf("%v: %s", err, out) + } + } + os.WriteFile(filepath.Join(root, "other.txt"), []byte("x"), 0o644) + exec.Command("git", "-C", root, "add", "other.txt").Run() + err := Edit(root, func(s *Store) (string, error) { + _, err := s.Create("a", nil) + return "add a", err + }) + if err != nil { + t.Fatal(err) + } + out, _ := exec.Command("git", "-C", root, "log", "--format=%s", "--name-only").Output() + if !strings.Contains(string(out), "chore(tracker): add a") || strings.Contains(string(out), "other.txt") { + t.Fatalf("log = %s", out) + } +}