import std/[unittest, os, osproc, strutils, sequtils] import ../src/sirmem/core var counter = 0 var lastWarnings: seq[string] var lastCode = 0 proc freshDir(): string = inc counter result = getTempDir() / ("sirmem-test-" & $getCurrentProcessId() & "-" & $counter) / "data" removeDir(parentDir(result)) discard cmdInit(result) proc runIn(dir, cwd: string, args: varargs[string]): string = lastWarnings = @[] dispatch(dir, @args, cwd, lastCode, lastWarnings) proc run(dir: string, args: varargs[string]): string = runIn(dir, getCurrentDir(), args) proc fails(dir: string, args: varargs[string]): string = try: discard run(dir, args) except SirmemError as e: return e.msg checkpoint "expected failure: " & @args.join(" ") fail() proc relsText(dir: string): string = readFile(dir / "relations.tsv") putEnv("MEMORY_PERSON", "davide") putEnv("SIRMEM_MACHINE", "sirlaptop") proc seed(d: string) = for (id, t) in [("a", "concept"), ("b", "concept"), ("c", "concept"), ("d", "concept")]: discard run(d, "new", id, t) suite "entities": test "new/label/alias write front-matter": let d = freshDir() check run(d, "new", "my-proj", "project", "My Project").startsWith("created my-proj") discard run(d, "alias", "my-proj", "Owner/Repo") discard run(d, "alias", "my-proj", "owner/repo") # dedupe case-insens discard run(d, "label", "my-proj", "Renamed Project") let txt = readFile(d / "entities" / "my-proj.md") check txt.startsWith("---\nid: my-proj\ntype: project\nlabel: Renamed Project\naliases: Owner/Repo\ncreated: ") check fails(d, "new", "my-proj", "project").contains("already exists") check fails(d, "new", "x", "nonsense").contains("unknown type") check fails(d, "new", "Bad Id", "concept").contains("invalid id") test "new machine records system info": let d = freshDir() discard run(d, "new", "sirlaptop", "machine") let txt = readFile(d / "entities" / "sirlaptop.md") check "- os: " & hostOS in txt check "- arch: " in txt check "- hostname: sirlaptop" in txt suite "link / unlink / rel / who": test "canonicalization, inverse, default verb, note": let d = freshDir() seed(d) check run(d, "link", "a", "b") == "linked a relates-to b" check run(d, "link", "c", "relates-to", "a") == "linked a relates-to c" # symmetric sorted check run(d, "link", "b", "contains", "a", "first", "note") == "linked a part-of b" check relsText(d) == "a\tpart-of\tb\tfirst note\na\trelates-to\tb\na\trelates-to\tc\n" check run(d, "link", "a", "part-of", "b") == "linked a part-of b" # idempotent check relsText(d).count("part-of") == 1 check fails(d, "link", "a", "bogus", "b").contains("unknown verb") check fails(d, "link", "a", "part-of", "zzz").contains("entity not found") check fails(d, "link", "a", "part-of", "a").contains("itself") test "cycles rejected for part-of and supersedes": let d = freshDir() seed(d) discard run(d, "link", "a", "part-of", "b") discard run(d, "link", "b", "part-of", "c") check fails(d, "link", "c", "part-of", "a").contains("cycle") check fails(d, "link", "a", "contains", "c").contains("cycle") # inverse form discard run(d, "link", "a", "supersedes", "b") check fails(d, "link", "b", "supersedes", "a").contains("cycle") check fails(d, "link", "a", "superseded-by", "b").contains("cycle") discard run(d, "link", "c", "depends-on", "a") # other verbs may cycle discard run(d, "link", "a", "depends-on", "c") test "domain mismatch warns but writes": let d = freshDir() seed(d) discard run(d, "link", "a", "owns", "b") check lastWarnings.len == 1 and "domain/range" in lastWarnings[0] check "a\towns\tb" in relsText(d) test "rel shows both directions with inverse names and notes": let d = freshDir() seed(d) discard run(d, "link", "a", "part-of", "b", "why") discard run(d, "link", "c", "relates-to", "a") check run(d, "rel", "a") == "a part-of b # why\na relates-to c" check run(d, "rel", "b") == "b contains a # why" check run(d, "rel", "c") == "c relates-to a" check run(d, "rel", "d") == "no relations for d" test "who accepts verb and inverse": let d = freshDir() seed(d) discard run(d, "link", "a", "part-of", "c") discard run(d, "link", "b", "part-of", "c") check run(d, "who", "part-of", "c") == "a (a)\nb (b)" check run(d, "who", "contains", "a") == "c (c)" check run(d, "who", "part-of", "a") == "none" discard run(d, "link", "a", "d") check run(d, "who", "relates-to", "d") == "a (a)" check run(d, "who", "relates-to", "a") == "d (d)" test "unlink by verb and inverse": let d = freshDir() seed(d) discard run(d, "link", "a", "part-of", "b") discard run(d, "link", "a", "c") check run(d, "unlink", "b", "contains", "a") == "unlinked a part-of b" check run(d, "unlink", "c", "relates-to", "a") == "unlinked a relates-to c" check relsText(d) == "" check fails(d, "unlink", "a", "part-of", "b").contains("no such relation") test "writes are sorted, unique, atomic": let d = freshDir() seed(d) discard run(d, "link", "d", "uses", "a") discard run(d, "link", "c", "uses", "b") discard run(d, "link", "a", "uses", "b") discard run(d, "link", "a", "uses", "b", "n") check relsText(d) == "a\tuses\tb\tn\nc\tuses\tb\nd\tuses\ta\n" check not fileExists(d / "relations.tsv.tmp") check toSeq(walkFiles(d / "entities" / "*.tmp")).len == 0 # unsorted + duplicate hand-written file gets normalized on next write writeFile(d / "relations.tsv", "d\tuses\ta\na\tuses\tb\na\tuses\tb\n") discard run(d, "link", "b", "uses", "c") check relsText(d) == "a\tuses\tb\nb\tuses\tc\nd\tuses\ta\n" test "malformed relations file blocks writes": let d = freshDir() seed(d) writeFile(d / "relations.tsv", "garbage\n") check fails(d, "link", "a", "b").contains("malformed") suite "find / path": test "find reports where it matched": let d = freshDir() seed(d) discard run(d, "label", "a", "Alpha Thing") discard run(d, "alias", "b", "Bravo-Nick") writeFile(d / "entities" / "c.md", "---\nid: c\ntype: concept\nlabel: c\naliases: \ncreated: 2026-01-01\n---\nSome deep detail here\n") discard run(d, "link", "a", "uses", "b", "Carries DETAIL too") let o = run(d, "find", "detail") check "entity c" in o and "matched body: Some deep detail here" in o check "relation a uses b" in o and "matched note" in o check "matched label" in run(d, "find", "ALPHA") check "matched alias: Bravo-Nick" in run(d, "find", "nick") check "matched id" in run(d, "find", "d") check run(d, "find", "zzzzqq") == "no matches" test "path shortest, undirected, with directions": let d = freshDir() seed(d) discard run(d, "new", "e", "concept") discard run(d, "link", "a", "part-of", "b") discard run(d, "link", "c", "part-of", "b") discard run(d, "link", "c", "relates-to", "d") discard run(d, "link", "d", "uses", "e") check run(d, "path", "a", "c") == "a -part-of-> b\nb <-part-of- c\n(2 hops)" check run(d, "path", "a", "d") == "a -part-of-> b\nb <-part-of- c\nc -relates-to- d\n(3 hops)" check run(d, "path", "a", "e").contains("(4 hops)") check run(d, "path", "a", "e", "3").startsWith("no path") check run(d, "path", "a", "a").contains("same entity") check fails(d, "path", "a", "e", "x").contains("integer") suite "rm / unalias": test "unalias removes, errors when absent": let d = freshDir() seed(d) discard run(d, "alias", "a", "Foo") discard run(d, "alias", "a", "bar") check run(d, "unalias", "a", "foo") == "aliases of a: bar" check readFile(d / "entities" / "a.md").contains("aliases: bar\n") check fails(d, "unalias", "a", "foo").contains("alias not found") check fails(d, "unalias", "zzz", "x").contains("entity not found") test "rm without relations": let d = freshDir() seed(d) check run(d, "rm", "a") == "removed entities/a.md" check not fileExists(d / "entities" / "a.md") check fails(d, "rm", "a").contains("entity not found") check not fileExists(d / "entities" / "a.md.tmp") test "rm refuses and lists relations in both directions": let d = freshDir() seed(d) discard run(d, "link", "a", "part-of", "b", "why") discard run(d, "link", "c", "part-of", "a") let m = fails(d, "rm", "a") check m.contains("refusing to remove a") check m.contains(" a part-of b # why") check m.contains(" c part-of a") check fileExists(d / "entities" / "a.md") check relsText(d).count("\n") == 2 test "rm --cascade removes relations and file, prints them": let d = freshDir() seed(d) discard run(d, "link", "a", "part-of", "b", "why") discard run(d, "link", "c", "part-of", "a") discard run(d, "link", "c", "b") check run(d, "rm", "a", "--cascade") == "removed relation a part-of b # why\nremoved relation c part-of a\nremoved entities/a.md" check relsText(d) == "b\trelates-to\tc\n" check not fileExists(d / "entities" / "a.md") check run(d, "lint").contains("0 errors") test "tombstone: rm acts on the tombstone, protected while referenced": let d = freshDir() seed(d) discard run(d, "merge", "a", "b") # tombstone a is unreferenced: rm removes it, not b check run(d, "rm", "a") == "removed entities/a.md" check fileExists(d / "entities" / "b.md") # referenced by a relation let d2 = freshDir() seed(d2) discard run(d2, "merge", "a", "b") writeFile(d2 / "relations.tsv", "a\tpart-of\tc\n") var m = fails(d2, "rm", "a", "--cascade") check m.contains("tombstone a") and m.contains(" a part-of c") check fileExists(d2 / "entities" / "a.md") # referenced by another redirect let d3 = freshDir() seed(d3) discard run(d3, "merge", "a", "b") discard run(d3, "merge", "b", "c") m = fails(d3, "rm", "b") check m.contains("tombstone b") and m.contains("a -> b") check fileExists(d3 / "entities" / "b.md") suite "merge": test "rewrites relations, unions aliases, tombstones, resolves redirects": let d = freshDir() seed(d) discard run(d, "alias", "a", "aa") discard run(d, "alias", "b", "bb") discard run(d, "link", "a", "part-of", "c") discard run(d, "link", "b", "part-of", "c", "keep") discard run(d, "link", "a", "relates-to", "b") # becomes self -> dropped discard run(d, "link", "d", "uses", "a") check run(d, "merge", "a", "b") == "merged a into b" check relsText(d) == "b\tpart-of\tc\tkeep\nd\tuses\tb\n" let b = readFile(d / "entities" / "b.md") check "aliases: bb, aa" in b let a = readFile(d / "entities" / "a.md") check "redirect: b" in a check run(d, "rel", "a") == run(d, "rel", "b") # redirect resolved discard run(d, "link", "a", "uses", "c") # via tombstone check "b\tuses\tc" in relsText(d) check fails(d, "merge", "a", "c").contains("already merged") check fails(d, "merge", "c", "c").contains("itself") test "merge that would create a cycle is rejected and changes nothing": let d = freshDir() seed(d) discard run(d, "link", "a", "part-of", "b") discard run(d, "link", "b", "part-of", "c") let before = relsText(d) check fails(d, "merge", "a", "c").contains("cycle") check relsText(d) == before check "redirect" notin readFile(d / "entities" / "a.md") suite "context and prefs": test "person from env, then parent .env; machine; project from git remote": let d = freshDir() discard run(d, "new", "davide", "person") discard run(d, "new", "sirlaptop", "machine") discard run(d, "new", "proj", "project") discard run(d, "alias", "proj", "owner/repo") let work = parentDir(d) / "work" createDir(work) check execCmd("git init -q " & quoteShell(work)) == 0 check execCmd("git -C " & quoteShell(work) & " remote add origin git@host.example:Owner/Repo.git") == 0 let o = runIn(d, work, "context") check "person: davide (entity: yes, davide)" in o check "machine: sirlaptop (entity: yes, sirlaptop)" in o check "project: owner/repo (entity: yes, proj)" in o # not a git dir -> not detected check "project: (not detected)" in runIn(d, parentDir(d), "context") # .env fallback putEnv("MEMORY_PERSON", "") writeFile(parentDir(d) / ".env", "OTHER=1\nexport MEMORY_PERSON=\"someone\"\n") check "person: someone (entity: no)" in runIn(d, work, "context") putEnv("MEMORY_PERSON", "davide") test "prefs precedence grouping, unscoped, supersedes": let d = freshDir() discard run(d, "new", "davide", "person") discard run(d, "new", "sirlaptop", "machine") discard run(d, "new", "othermachine", "machine") discard run(d, "new", "proj", "project") discard run(d, "alias", "proj", "owner/repo") let work = parentDir(d) / "work" createDir(work) discard execCmd("git init -q " & quoteShell(work)) discard execCmd("git -C " & quoteShell(work) & " remote add origin https://host.example/owner/repo") for (id, label) in [("p-all", "All"), ("p-mach", "Mach"), ("p-pers", "Pers"), ("p-proj", "Proj"), ("p-other", "Other"), ("p-old", "Old"), ("p-multi", "Multi"), ("p-dead", "Dead")]: discard run(d, "new", id, "preference", label) writeFile(d / "entities" / "p-all.md", "---\nid: p-all\ntype: preference\nlabel: All\naliases: \ncreated: 2026-01-01\n---\nBody of all\n") discard run(d, "link", "p-mach", "applies-to", "sirlaptop") discard run(d, "link", "p-pers", "applies-to", "davide") discard run(d, "link", "p-proj", "applies-to", "proj") discard run(d, "link", "p-other", "applies-to", "othermachine") discard run(d, "link", "p-multi", "applies-to", "othermachine") discard run(d, "link", "p-multi", "applies-to", "proj") # any match -> project level discard run(d, "link", "p-old", "applies-to", "davide") discard run(d, "link", "p-pers", "supersedes", "p-old") # superseder not applicable (other machine) must not hide p-dead discard run(d, "link", "p-other", "supersedes", "p-dead") let o = runIn(d, work, "prefs") check o.splitLines[0].contains("later groups win") let order = ["## everywhere", "### All (p-all)", "Body of all", "## machine", "### Mach", "## person", "### Pers", "## project"] var last = -1 for m in order: let i = o.find(m) check i > last last = i check "p-proj" in o and "p-multi" in o and "p-dead" in o check "p-old" notin o check "p-other" notin o check o.find("p-proj") < o.find("p-multi") or o.find("p-multi") < o.find("p-proj") check o.find("## project") < o.find("p-multi") suite "lint": test "errors vs warnings and exit semantic": let d = freshDir() seed(d) discard run(d, "link", "a", "owns", "b") # warning domain discard run(d, "link", "a", "uses", "b") var n = 0 var out1 = cmdLint(loadStore(d), n) check n == 0 check "warning: domain/range" in out1 check "warning: orphan entity: d" in out1 check run(d, "lint") == out1 and lastCode == 0 discard run(d, "new", "pref9", "preference") check "orphan entity: pref9" notin run(d, "lint") # break things by hand writeFile(d / "relations.tsv", "a\tbogus\tb\n" & "a\tuses\tghost\n" & "c\trelates-to\ta\n" & # non-canonical symmetric "a\tuses\tb\n" & "a\tuses\tb\n" & # duplicate "a\tpart-of\tb\n" & "b\tpart-of\ta\n" & # cycle "malformed line\n" & "a\tcontains\tb\n") # inverse name stored out1 = run(d, "lint") check lastCode == 1 for m in ["error: unknown verb: a bogus b", "error: dangling id ghost", "non-canonical symmetric", "error: duplicate relation", "error: part-of cycle", "error: relations.tsv: malformed line 8", "inverse verb name"]: check m in out1 check not out1.contains("warning: entity id") test "filename mismatch and bad schema/entity files": let d = freshDir() seed(d) writeFile(d / "entities" / "wrong.md", "---\nid: other\ntype: concept\nlabel: x\naliases: \ncreated: 2026-01-01\n---\n") writeFile(d / "entities" / "broken.md", "no front matter") writeFile(d / "schema.md", readFile(d / "schema.md") & "- verb: bad | inverse: x\n") discard run(d, "link", "a", "b") let o = run(d, "lint") check "warning: entity id other differs from filename wrong.md" in o check "error: entities/broken.md: missing front-matter" in o check "error: schema.md:" in o check lastCode == 1 suite "rm guards": test "rm refuses to widen a preference scope (with and without cascade)": let d = freshDir() seed(d) discard run(d, "new", "p1", "preference") discard run(d, "new", "p2", "preference") discard run(d, "link", "p1", "applies-to", "a") discard run(d, "link", "p2", "applies-to", "a") discard run(d, "link", "p2", "applies-to", "b") for args in [@["rm", "a"], @["rm", "a", "--cascade"]]: let m = fails(d, args) check m.contains("widen") and m.contains(" p1") and not m.contains(" p2") check fileExists(d / "entities" / "a.md") # p2 still has b: removing b is fine; a preference removed itself is fine check run(d, "rm", "b", "--cascade").contains("removed entities/b.md") check run(d, "rm", "p1", "--cascade").contains("removed entities/p1.md") test "rm refuses an entity that tombstones point to": let d = freshDir() seed(d) discard run(d, "merge", "a", "b") let m = fails(d, "rm", "b") check m.contains("tombstones point to it") and m.contains(" a -> b") check fileExists(d / "entities" / "b.md") suite "lint --clean / --suggest": test "clean appends removed relates-to note to the first typed relation": let d = freshDir() seed(d) discard run(d, "link", "a", "uses", "b", "first") discard run(d, "link", "b", "part-of", "a", "second") discard run(d, "link", "a", "relates-to", "b", "extra") let o = run(d, "lint", "--clean") check "note appended to a uses b" in o check "a\tuses\tb\tfirst | extra" in relsText(d) check "relates-to" notin relsText(d) discard run(d, "link", "c", "uses", "d") discard run(d, "link", "c", "relates-to", "d", "n2") discard run(d, "lint", "--clean") check "c\tuses\td\tn2" in relsText(d) test "clean removes tombstones, redundant relates-to and part-of; prints changes": let d = freshDir() seed(d) discard run(d, "new", "t1", "concept") discard run(d, "new", "t2", "concept") discard run(d, "merge", "t1", "t2") # t1 -> t2 -> (t2 is live) discard run(d, "merge", "t2", "d") # t2 -> d, t1 -> t2 discard run(d, "link", "a", "uses", "b") discard run(d, "link", "b", "relates-to", "a", "n") discard run(d, "new", "e", "concept") discard run(d, "link", "e", "relates-to", "d") # keep discard run(d, "link", "a", "part-of", "b") discard run(d, "link", "b", "part-of", "c") discard run(d, "link", "a", "part-of", "c") # redundant discard run(d, "link", "a", "part-of", "d") # redundant (a>b>c>d below) discard run(d, "link", "c", "part-of", "d") let o = run(d, "lint", "--clean") check "removed relation a relates-to b # n (pair already linked by a typed verb)" in o check "removed relation a part-of c (implied by a part-of chain)" in o check "removed relation a part-of d (implied by a part-of chain)" in o check "removed tombstone entities/t1.md" in o check "removed tombstone entities/t2.md" in o check not fileExists(d / "entities" / "t1.md") and not fileExists(d / "entities" / "t2.md") check "d\trelates-to\te" in relsText(d) # kept check relsText(d).count("part-of") == 3 check "0 errors" in o and lastCode == 0 check run(d, "lint", "--clean").startsWith("nothing to clean") test "clean keeps referenced tombstones": let d = freshDir() seed(d) discard run(d, "merge", "a", "b") writeFile(d / "relations.tsv", "a\tuses\tc\n") check run(d, "lint", "--clean").startsWith("nothing to clean") check fileExists(d / "entities" / "a.md") test "suggest lists candidates read-only; clean + suggest combine": let d = freshDir() seed(d) discard run(d, "new", "old", "concept") discard run(d, "new", "mid", "concept") discard run(d, "new", "new1", "concept") discard run(d, "link", "new1", "supersedes", "mid") discard run(d, "link", "mid", "supersedes", "old") discard run(d, "link", "a", "contradicts", "b") discard run(d, "new", "foo-bar", "concept", "Foo Bar") discard run(d, "new", "fb", "concept", "fb") discard run(d, "alias", "fb", "foo_bar") discard run(d, "new", "pref", "preference") # everywhere: not an orphan let before = relsText(d) let o = run(d, "lint", "--suggest") check "[superseded] mid is superseded by new1 -> rm mid" in o check "[superseded] old is superseded by new1 -> rm old" in o check "[contradicted] a contradicts b (b is the older statement) -> supersede or rm b" in o check "[duplicate]" in o and "merge " in o and "'foobar'" in o check "[orphan] c has no relations -> rm or link c" in o check "orphan] pref" notin o check "1. " in o and "2. " in o check relsText(d) == before let o2 = run(d, "lint", "--clean", "--suggest") check o2.startsWith("nothing to clean") and "suggestions:" in o2 let d2 = freshDir() check run(d2, "lint", "--suggest").endsWith("no suggestions") check fails(d2, "lint", "--bogus").contains("usage") suite "cli": test "help, version, missing dir, unknown command (binary)": let exe = getCurrentDir() / "bin" / "sirmem" require fileExists(exe) let (v, c0) = execCmdEx(quoteShell(exe) & " --version") check c0 == 0 and v.startsWith("sirmem " & Version) check execCmdEx(quoteShell(exe) & " --help")[0].contains("usage:") let (o1, c1) = execCmdEx("env -u SIRMEM_DIR " & quoteShell(exe) & " lint 2>&1") check c1 == 1 and "no data dir" in o1 let d = freshDir() let (o2, c2) = execCmdEx("SIRMEM_DIR=" & quoteShell(d) & " " & quoteShell(exe) & " bogus 2>&1") check c2 == 1 and "unknown command" in o2 let (o3, c3) = execCmdEx(quoteShell(exe) & " lint --dir " & quoteShell(d)) check c3 == 0 and "0 errors" in o3