feat: rm guards (scope widening, merge targets), lint --clean and --suggest, v0.1.3
ci / release (push) Successful in 1m21s

This commit is contained in:
2026-11-22 19:29:33 +01:00
parent 7d1b6aed5f
commit dae7313e14
3 changed files with 244 additions and 7 deletions
+144 -6
View File
@@ -6,7 +6,7 @@ import std/[os, strutils, sequtils, algorithm, tables, times, osproc,
nativesockets, deques]
const
Version* = "0.1.2"
Version* = "0.1.3"
CycleVerbs* = ["part-of", "supersedes"]
DefaultVerb* = "relates-to"
@@ -425,6 +425,7 @@ Free markdown is allowed; only the `- type:` and `- verb:` lines are read.
- verb: part-of | inverse: contains | symmetric: no | from: any | to: any | Subject is a component of object
- verb: applies-to | inverse: scope-of | symmetric: no | from: preference | to: any | Preference applies to object (none = everywhere)
- verb: supersedes | inverse: superseded-by | symmetric: no | from: any | to: any | Subject replaces object
- verb: contradicts | inverse: contradicted-by | symmetric: no | from: any | to: any | Subject contradicts object; subject is the newer statement
- verb: depends-on | inverse: required-by | symmetric: no | from: any | to: any | Subject needs object
- verb: uses | inverse: used-by | symmetric: no | from: any | to: any | Subject uses object
- verb: owns | inverse: owned-by | symmetric: no | from: person | to: any | Subject owns object
@@ -511,8 +512,21 @@ proc cmdRm*(st: var Store, id: string, cascade: bool): string =
let e = st.entities[id]
let rels = st.rels.filterIt(it.s == id or it.o == id)
let relLines = rels.mapIt(" " & it.s & " " & it.v & " " & it.o & suffix(it.note))
let pointing = toSeq(st.entities.pairs).filterIt(it[1].redirect == id).mapIt(it[0])
if e.redirect == "" and pointing.len > 0:
fail("refusing to remove " & id & ": merge tombstones point to it:\n" &
pointing.mapIt(" " & it & " -> " & id).join("\n"))
# a preference whose only applies-to targets are id would silently become "everywhere"
var widened: seq[string]
for pid, pe in st.entities:
if pe.typ != "preference" or pid == id: continue
let tg = st.rels.filterIt(it.v == "applies-to" and it.s == pid).mapIt(it.o)
if tg.len > 0 and tg.allIt(it == id): widened.add pid
if widened.len > 0:
fail("refusing to remove " & id & ": it would widen the scope of preference(s) to everywhere " &
"(their only applies-to target); relink or remove them first:\n" &
widened.mapIt(" " & it).join("\n"))
if e.redirect != "":
let pointing = toSeq(st.entities.pairs).filterIt(it[1].redirect == id).mapIt(it[0])
if rels.len > 0 or pointing.len > 0:
var msg = "refusing to remove tombstone " & id & " (merged into " & e.redirect &
"); still referenced, resolve first:"
@@ -752,6 +766,117 @@ proc cmdLint*(st: Store, errorCount: var int): string =
lines.add $errs.len & " errors, " & $warns.len & " warnings"
lines.join("\n")
proc cmdLintClean*(st: var Store): string =
## Structural fixes only; prints every change. Atomic writes.
st.checkWritable
var lines: seq[string]
var rels = st.rels
# b. relates-to implied by any other verb on the same pair (either direction)
var keep: seq[Rel]
for r in rels:
if r.v == DefaultVerb and rels.anyIt(it.v != DefaultVerb and
((it.s == r.s and it.o == r.o) or (it.s == r.o and it.o == r.s))):
lines.add "removed relation " & r.s & " " & r.v & " " & r.o & suffix(r.note) &
" (pair already linked by a typed verb)"
else:
keep.add r
rels = keep
# c. transitively redundant part-of (sequential, so reachability is always preserved)
var i = 0
while i < rels.len:
let r = rels[i]
if r.v == "part-of":
var others = rels
others.delete(i)
if reaches(others.filterIt(it.v == "part-of"), "part-of", r.s, r.o):
lines.add "removed relation " & r.s & " " & r.v & " " & r.o & suffix(r.note) &
" (implied by a part-of chain)"
rels = others
continue
inc i
if rels.len != st.rels.len:
st.rels = rels
st.saveRels
# a. unreferenced redirect tombstones, repeated until stable
var again = true
while again:
again = false
for id, e in st.entities:
if e.redirect == "": continue
if st.rels.anyIt(it.s == id or it.o == id): continue
if toSeq(st.entities.values).anyIt(it.redirect == id): continue
let path = st.entityPath(id)
let fp = if fileExists(path): path else: st.dir / "entities" / (e.fileId & ".md")
removeFile(fp)
st.entities.del id
lines.add "removed tombstone entities/" & splitFile(fp).name & ".md (merged into " &
e.redirect & ", unreferenced)"
again = true
break
if lines.len == 0: "nothing to clean"
else: lines.join("\n")
proc supersededBy(rels: seq[Rel], id: string): seq[string] =
## Heads of the supersedes chains above id.
var seen = @[id]
var stack = @[id]
while stack.len > 0:
let cur = stack.pop
let ups = rels.filterIt(it.v == "supersedes" and it.o == cur).mapIt(it.s)
if ups.len == 0 and cur != id and cur notin result: result.add cur
for u in ups:
if u notin seen:
seen.add u
stack.add u
result.sort
proc normKey(s: string): string =
for c in s.toLowerAscii:
if c notin {' ', '-', '_', '.', '\t'}: result.add c
proc cmdLintSuggest*(st: Store): string =
## Read-only; numbered candidates for an LLM to discuss with the user.
var cands: seq[string]
let live = toSeq(st.entities.pairs).filterIt(it[1].redirect == "").mapIt(it[0])
for id in live:
let heads = supersededBy(st.rels, id)
if heads.len > 0:
cands.add "[superseded] " & id & " is superseded by " & heads.join(", ") & " -> rm " & id
var seenC: seq[string]
for r in st.rels:
if r.v == "contradicts" and r.o in live and r.s in live and r.o notin seenC:
seenC.add r.o
cands.add "[contradicted] " & r.s & " contradicts " & r.o & " (" & r.o &
" is the older statement) -> supersede or rm " & r.o
var keys = initOrderedTable[string, seq[string]]()
for id in live:
let e = st.entities[id]
for k in @[e.label] & e.aliases:
let nk = normKey(k)
if nk == "": continue
if nk notin keys: keys[nk] = @[]
if id notin keys[nk]: keys[nk].add id
var pairs: seq[(string, string)]
for nk, ids in keys:
for a in 0 ..< ids.len:
for b in a + 1 ..< ids.len:
var x = ids[b] # merged away: the less connected one, ties by id
var y = ids[a]
let nx = st.rels.countIt(it.s == x or it.o == x)
let ny = st.rels.countIt(it.s == y or it.o == y)
if nx > ny or (nx == ny and x < y): swap(x, y)
if (x, y) notin pairs:
pairs.add (x, y)
cands.add "[duplicate] " & x & " and " & y & " share label/alias '" & nk &
"' -> merge " & x & " into " & y
for id in live:
if st.entities[id].typ == "preference": continue
if not st.rels.anyIt(it.s == id or it.o == id):
cands.add "[orphan] " & id & " has no relations -> rm or link " & id
if cands.len == 0: return "no suggestions"
for i in 0 ..< cands.len: cands[i] = $(i + 1) & ". " & cands[i]
cands.join("\n")
# ---------------------------------------------------------------- dispatch
const Usage* = """sirmem - file-based knowledge-graph memory for LLM agents
@@ -773,11 +898,17 @@ commands:
find <text> search ids, labels, aliases, bodies, notes
path <a> <b> [maxdepth=4] shortest undirected path
rm <id> [--cascade] delete entity; refuses if it has relations
(--cascade removes them too); refuses tombstones
still referenced
(--cascade removes them too), if it is the only
applies-to target of a preference, if tombstones
point to it, or for tombstones still referenced
merge <from> <into> merge entity, leave redirect tombstone
prefs effective preferences for current context
lint check data; exit 1 on errors
lint [--clean] [--suggest] check data; exit 1 on errors
--clean: apply structural fixes (drop unreferenced
tombstones, relates-to duplicated by a typed verb,
transitively redundant part-of) and print each change
--suggest: read-only numbered candidates (superseded,
contradicted, duplicate, orphan) for review
--help, --version
"""
@@ -847,7 +978,14 @@ proc dispatch*(dir: string, args: seq[string], cwd: string,
result = cmdMerge(st, args[1], args[2])
of "prefs": result = cmdPrefs(st, cwd)
of "lint":
let flags = args[1 .. ^1]
for f in flags:
if f notin ["--clean", "--suggest"]: fail("usage: sirmem lint [--clean] [--suggest]")
var parts: seq[string]
if "--clean" in flags: parts.add cmdLintClean(st)
var n = 0
result = cmdLint(st, n)
parts.add cmdLint(st, n)
if "--suggest" in flags: parts.add "suggestions:\n" & cmdLintSuggest(st)
result = parts.join("\n")
if n > 0: exitCode = 1
else: fail("unknown command: " & cmd & " (try --help)")