feat: sirmem v0.1.0 knowledge-graph memory CLI
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
import std/[os, strutils]
|
||||
import sirmem/core
|
||||
|
||||
proc main() =
|
||||
var dir = getEnv("SIRMEM_DIR")
|
||||
var args: seq[string]
|
||||
var raw = commandLineParams()
|
||||
var i = 0
|
||||
while i < raw.len:
|
||||
let a = raw[i]
|
||||
if a == "--dir":
|
||||
if i + 1 >= raw.len:
|
||||
stderr.writeLine "sirmem: error: --dir needs a path"
|
||||
quit 1
|
||||
dir = raw[i + 1]
|
||||
i += 2
|
||||
continue
|
||||
elif a.startsWith("--dir="):
|
||||
dir = a["--dir=".len .. ^1]
|
||||
else:
|
||||
args.add a
|
||||
inc i
|
||||
var code = 0
|
||||
var warnings: seq[string]
|
||||
try:
|
||||
let outp = dispatch(dir, args, getCurrentDir(), code, warnings)
|
||||
for w in warnings: stderr.writeLine "warning: " & w
|
||||
echo outp
|
||||
quit code
|
||||
except SirmemError as e:
|
||||
for w in warnings: stderr.writeLine "warning: " & w
|
||||
stderr.writeLine "sirmem: error: " & e.msg
|
||||
quit 1
|
||||
except CatchableError as e:
|
||||
stderr.writeLine "sirmem: error: " & e.msg
|
||||
quit 1
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,796 @@
|
||||
## sirmem core: file-based knowledge-graph memory for LLM agents.
|
||||
## Stdlib only. All commands return their plain-text output and raise
|
||||
## SirmemError on user-facing errors; warnings are collected in Store.warnings.
|
||||
|
||||
import std/[os, strutils, sequtils, algorithm, tables, times, osproc,
|
||||
nativesockets, deques]
|
||||
|
||||
const
|
||||
Version* = "0.1.0"
|
||||
CycleVerbs* = ["part-of", "supersedes"]
|
||||
DefaultVerb* = "relates-to"
|
||||
|
||||
type
|
||||
SirmemError* = object of CatchableError
|
||||
|
||||
Verb* = object
|
||||
name*, inverse*, fromT*, toT*, def*: string
|
||||
symmetric*: bool
|
||||
|
||||
Schema* = object
|
||||
types*: seq[(string, string)]
|
||||
verbs*: seq[Verb]
|
||||
errors*: seq[string]
|
||||
|
||||
Entity* = object
|
||||
id*, typ*, label*, created*, redirect*, body*, fileId*: string
|
||||
aliases*: seq[string]
|
||||
|
||||
Rel* = object
|
||||
s*, v*, o*, note*: string
|
||||
|
||||
Store* = object
|
||||
dir*: string
|
||||
schema*: Schema
|
||||
entities*: OrderedTable[string, Entity]
|
||||
rels*: seq[Rel]
|
||||
badRelLines*: seq[string] ## "line N: text"
|
||||
loadErrors*: seq[string] ## malformed entity files
|
||||
warnings*: seq[string]
|
||||
|
||||
Ctx* = object
|
||||
person*, machine*, projectUrl*, projectRef*: string
|
||||
personId*, machineId*, projectId*: string ## entity ids ("" = none)
|
||||
|
||||
proc fail*(msg: string) {.noreturn.} =
|
||||
raise newException(SirmemError, msg)
|
||||
|
||||
# ---------------------------------------------------------------- basics
|
||||
|
||||
proc isSlug*(s: string): bool =
|
||||
if s.len == 0 or s[0] == '-' or s[^1] == '-' or "--" in s: return false
|
||||
for c in s:
|
||||
if c notin {'a'..'z', '0'..'9', '-'}: return false
|
||||
true
|
||||
|
||||
proc slugify*(s: string): string =
|
||||
var lastDash = true
|
||||
for c in s.toLowerAscii:
|
||||
if c in {'a'..'z', '0'..'9'}:
|
||||
result.add c
|
||||
lastDash = false
|
||||
elif not lastDash:
|
||||
result.add '-'
|
||||
lastDash = true
|
||||
result.removeSuffix('-')
|
||||
|
||||
proc oneLine(s: string): string =
|
||||
s.multiReplace(("\t", " "), ("\r", " "), ("\n", " ")).strip
|
||||
|
||||
proc atomicWrite*(path, content: string) =
|
||||
createDir(parentDir(path))
|
||||
let tmp = path & ".tmp"
|
||||
writeFile(tmp, content)
|
||||
moveFile(tmp, path)
|
||||
|
||||
# ---------------------------------------------------------------- schema
|
||||
|
||||
proc kvField(p, key: string, val: var string): bool =
|
||||
if p.startsWith(key & ":"):
|
||||
val = p[key.len + 1 .. ^1].strip
|
||||
true
|
||||
else:
|
||||
false
|
||||
|
||||
proc parseSchema*(text: string): Schema =
|
||||
var n = 0
|
||||
for raw in text.splitLines:
|
||||
inc n
|
||||
let line = raw.strip
|
||||
if line.startsWith("- type:"):
|
||||
let parts = line["- type:".len .. ^1].split('|').mapIt(it.strip)
|
||||
if not isSlug(parts[0]):
|
||||
result.errors.add "schema.md:" & $n & ": malformed type line: " & line
|
||||
else:
|
||||
result.types.add (parts[0], parts[1 .. ^1].join(" | "))
|
||||
elif line.startsWith("- verb:"):
|
||||
let parts = line["- verb:".len .. ^1].split('|').mapIt(it.strip)
|
||||
var v: Verb
|
||||
var ok = parts.len >= 5 and isSlug(parts[0])
|
||||
if ok:
|
||||
v.name = parts[0]
|
||||
var sym: string
|
||||
ok = kvField(parts[1], "inverse", v.inverse) and
|
||||
kvField(parts[2], "symmetric", sym) and
|
||||
kvField(parts[3], "from", v.fromT) and
|
||||
kvField(parts[4], "to", v.toT) and sym in ["yes", "no"] and
|
||||
(v.inverse == "-" or isSlug(v.inverse))
|
||||
v.symmetric = sym == "yes"
|
||||
v.def = parts[5 .. ^1].join(" | ")
|
||||
if v.inverse == "-" or v.symmetric: v.inverse = ""
|
||||
if ok:
|
||||
result.verbs.add v
|
||||
else:
|
||||
result.errors.add "schema.md:" & $n & ": malformed verb line: " & line
|
||||
var seen: seq[string]
|
||||
for v in result.verbs:
|
||||
for nm in [v.name, v.inverse]:
|
||||
if nm == "": continue
|
||||
if nm in seen:
|
||||
result.errors.add "schema.md: verb name used twice: " & nm
|
||||
seen.add nm
|
||||
|
||||
proc resolveVerb*(sc: Schema, name: string): tuple[verb: Verb, inverted: bool] =
|
||||
for v in sc.verbs:
|
||||
if v.name == name: return (v, false)
|
||||
for v in sc.verbs:
|
||||
if v.inverse != "" and v.inverse == name: return (v, true)
|
||||
fail("unknown verb: " & name)
|
||||
|
||||
proc hasType*(sc: Schema, t: string): bool =
|
||||
sc.types.anyIt(it[0] == t)
|
||||
|
||||
proc canonical*(sc: Schema, s, verb, o: string): Rel =
|
||||
## Canonical stored direction: inverse names swap, symmetric sorts.
|
||||
let (v, inv) = resolveVerb(sc, verb)
|
||||
result = Rel(s: s, v: v.name, o: o)
|
||||
if inv: swap(result.s, result.o)
|
||||
if v.symmetric and result.s > result.o: swap(result.s, result.o)
|
||||
|
||||
# ---------------------------------------------------------------- entities
|
||||
|
||||
proc parseEntity*(text, fileStem: string): Entity =
|
||||
let lines = text.replace("\r\n", "\n").split('\n')
|
||||
if lines.len == 0 or lines[0].strip != "---":
|
||||
fail("missing front-matter")
|
||||
var close = -1
|
||||
for i in 1 ..< lines.len:
|
||||
if lines[i].strip == "---":
|
||||
close = i
|
||||
break
|
||||
if close < 0: fail("unterminated front-matter")
|
||||
for i in 1 ..< close:
|
||||
let l = lines[i]
|
||||
let c = l.find(':')
|
||||
if c < 0:
|
||||
if l.strip != "": fail("bad front-matter line: " & l)
|
||||
continue
|
||||
let k = l[0 ..< c].strip.toLowerAscii
|
||||
let val = l[c + 1 .. ^1].strip
|
||||
case k
|
||||
of "id": result.id = val
|
||||
of "type": result.typ = val
|
||||
of "label": result.label = val
|
||||
of "aliases": result.aliases = val.split(',').mapIt(it.strip).filterIt(it != "")
|
||||
of "created": result.created = val
|
||||
of "redirect": result.redirect = val
|
||||
else: discard
|
||||
if result.id == "": fail("front-matter has no id")
|
||||
if result.typ == "": fail("front-matter has no type")
|
||||
if result.label == "": result.label = result.id
|
||||
result.body = lines[close + 1 .. ^1].join("\n").strip(chars = {'\n', '\r'})
|
||||
result.fileId = fileStem
|
||||
|
||||
proc renderEntity*(e: Entity): string =
|
||||
result = "---\nid: " & e.id & "\ntype: " & e.typ & "\nlabel: " & e.label &
|
||||
"\naliases: " & e.aliases.join(", ") & "\ncreated: " & e.created & "\n"
|
||||
if e.redirect != "": result.add "redirect: " & e.redirect & "\n"
|
||||
result.add "---\n"
|
||||
if e.body != "": result.add e.body & "\n"
|
||||
|
||||
proc entityPath*(st: Store, id: string): string =
|
||||
st.dir / "entities" / (id & ".md")
|
||||
|
||||
proc saveEntity*(st: var Store, e: Entity) =
|
||||
st.entities[e.id] = e
|
||||
atomicWrite(st.entityPath(e.id), renderEntity(e))
|
||||
|
||||
# ---------------------------------------------------------------- relations
|
||||
|
||||
proc parseRels*(text: string): tuple[rels: seq[Rel], bad: seq[string]] =
|
||||
var n = 0
|
||||
for raw in text.splitLines:
|
||||
inc n
|
||||
if raw.strip == "": continue
|
||||
let p = raw.split('\t')
|
||||
if p.len < 3 or p[0].strip == "" or p[1].strip == "" or p[2].strip == "":
|
||||
result.bad.add "line " & $n & ": " & raw
|
||||
else:
|
||||
result.rels.add Rel(s: p[0], v: p[1], o: p[2],
|
||||
note: (if p.len > 3: p[3 .. ^1].join(" ").strip else: ""))
|
||||
|
||||
proc cmpRel(a, b: Rel): int =
|
||||
result = cmp(a.s, b.s)
|
||||
if result == 0: result = cmp(a.v, b.v)
|
||||
if result == 0: result = cmp(a.o, b.o)
|
||||
|
||||
proc normalizeRels*(rels: seq[Rel]): seq[Rel] =
|
||||
## Sorted by (s,v,o), unique; on duplicates prefer one with a note.
|
||||
let sorted = rels.sorted(cmpRel)
|
||||
for r in sorted:
|
||||
if result.len > 0 and cmpRel(result[^1], r) == 0:
|
||||
if result[^1].note == "": result[^1].note = r.note
|
||||
else:
|
||||
result.add r
|
||||
|
||||
proc renderRels*(rels: seq[Rel]): string =
|
||||
for r in rels:
|
||||
result.add r.s & "\t" & r.v & "\t" & r.o
|
||||
if r.note != "": result.add "\t" & r.note
|
||||
result.add "\n"
|
||||
|
||||
proc saveRels*(st: var Store) =
|
||||
st.rels = normalizeRels(st.rels)
|
||||
atomicWrite(st.dir / "relations.tsv", renderRels(st.rels))
|
||||
|
||||
# ---------------------------------------------------------------- store
|
||||
|
||||
proc loadStore*(dir: string): Store =
|
||||
if not dirExists(dir): fail("data dir not found: " & dir)
|
||||
result.dir = dir
|
||||
let sp = dir / "schema.md"
|
||||
if not fileExists(sp): fail("schema.md not found in " & dir & " (try: sirmem init)")
|
||||
result.schema = parseSchema(readFile(sp))
|
||||
let ed = dir / "entities"
|
||||
if dirExists(ed):
|
||||
var files: seq[string]
|
||||
for f in walkFiles(ed / "*.md"): files.add f
|
||||
files.sort
|
||||
for f in files:
|
||||
let stem = splitFile(f).name
|
||||
try:
|
||||
let e = parseEntity(readFile(f), stem)
|
||||
if e.id in result.entities:
|
||||
result.loadErrors.add "entities/" & stem & ".md: duplicate id " & e.id
|
||||
else:
|
||||
result.entities[e.id] = e
|
||||
except SirmemError as ex:
|
||||
result.loadErrors.add "entities/" & stem & ".md: " & ex.msg
|
||||
let rp = dir / "relations.tsv"
|
||||
if fileExists(rp):
|
||||
let (r, b) = parseRels(readFile(rp))
|
||||
result.rels = r
|
||||
result.badRelLines = b
|
||||
|
||||
proc checkWritable(st: Store) =
|
||||
if st.badRelLines.len > 0:
|
||||
fail("relations.tsv has malformed lines (run lint): " & st.badRelLines[0])
|
||||
|
||||
proc resolve*(st: Store, id: string): string =
|
||||
var cur = id
|
||||
for _ in 0 .. 10:
|
||||
if cur notin st.entities: fail("entity not found: " & cur)
|
||||
let e = st.entities[cur]
|
||||
if e.redirect == "": return cur
|
||||
cur = e.redirect
|
||||
fail("redirect loop starting at " & id)
|
||||
|
||||
proc label(st: Store, id: string): string =
|
||||
if id in st.entities: st.entities[id].label else: id
|
||||
|
||||
# ---------------------------------------------------------------- graph
|
||||
|
||||
proc reaches(rels: seq[Rel], verb, a, b: string): bool =
|
||||
var seen: seq[string] = @[a]
|
||||
var stack = @[a]
|
||||
while stack.len > 0:
|
||||
let cur = stack.pop
|
||||
if cur == b: return true
|
||||
for r in rels:
|
||||
if r.v == verb and r.s == cur and r.o notin seen:
|
||||
seen.add r.o
|
||||
stack.add r.o
|
||||
|
||||
proc wouldCycle(rels: seq[Rel], verb, s, o: string): bool =
|
||||
s == o or reaches(rels, verb, o, s)
|
||||
|
||||
proc findCycles(rels: seq[Rel]): seq[string] =
|
||||
for cv in CycleVerbs:
|
||||
let es = rels.filterIt(it.v == cv)
|
||||
for r in es:
|
||||
if r.s == r.o or reaches(es, cv, r.o, r.s):
|
||||
result.add cv & " cycle through: " & r.s & " " & cv & " " & r.o
|
||||
|
||||
proc matchesType(pattern, typ: string): bool =
|
||||
pattern == "any" or pattern == typ
|
||||
|
||||
proc domainWarning(st: Store, r: Rel): string =
|
||||
if r.s notin st.entities or r.o notin st.entities: return ""
|
||||
var v: Verb
|
||||
try: v = resolveVerb(st.schema, r.v).verb
|
||||
except SirmemError: return ""
|
||||
let st1 = st.entities[r.s].typ
|
||||
let ot = st.entities[r.o].typ
|
||||
let ok = (matchesType(v.fromT, st1) and matchesType(v.toT, ot)) or
|
||||
(v.symmetric and matchesType(v.fromT, ot) and matchesType(v.toT, st1))
|
||||
if ok: "" else:
|
||||
"domain/range mismatch: " & r.s & " (" & st1 & ") " & r.v & " " & r.o &
|
||||
" (" & ot & "); verb expects " & v.fromT & " -> " & v.toT
|
||||
|
||||
# ---------------------------------------------------------------- context
|
||||
|
||||
proc readDotEnvVar(path, key: string): string =
|
||||
if not fileExists(path): return ""
|
||||
for raw in readFile(path).splitLines:
|
||||
var l = raw.strip
|
||||
if l.startsWith("export "): l = l[7 .. ^1].strip
|
||||
if l.startsWith(key & "="):
|
||||
result = l[key.len + 1 .. ^1].strip
|
||||
if result.len >= 2 and result[0] in {'"', '\''} and result[^1] == result[0]:
|
||||
result = result[1 .. ^2]
|
||||
return
|
||||
|
||||
proc detectPerson*(dir: string): string =
|
||||
let e = getEnv("MEMORY_PERSON")
|
||||
if e != "": return e
|
||||
let parent = parentDir(normalizedPath(absolutePath(dir)))
|
||||
readDotEnvVar(parent / ".env", "MEMORY_PERSON")
|
||||
|
||||
proc detectMachine*(): string =
|
||||
let o = getEnv("SIRMEM_MACHINE") # override, mainly for tests
|
||||
if o != "": return slugify(o)
|
||||
var h = ""
|
||||
try: h = getHostname()
|
||||
except CatchableError: discard
|
||||
slugify(h.split('.')[0])
|
||||
|
||||
proc detectProjectUrl*(cwd: string): string =
|
||||
try:
|
||||
let (o, code) = execCmdEx("git remote get-url origin", workingDir = cwd)
|
||||
if code == 0: return o.strip
|
||||
except CatchableError: discard
|
||||
|
||||
proc normUrl(u: string): string =
|
||||
result = u.strip.toLowerAscii.strip(chars = {'/'})
|
||||
result.removeSuffix(".git")
|
||||
|
||||
proc ownerRepo*(url: string): string =
|
||||
let parts = normUrl(url).split({'/', ':'}).filterIt(it != "")
|
||||
if parts.len >= 2: parts[^2] & "/" & parts[^1] else: ""
|
||||
|
||||
proc aliasMatches(e: Entity, name: string): bool =
|
||||
e.aliases.anyIt(it.toLowerAscii == name.toLowerAscii)
|
||||
|
||||
proc detectContext*(st: Store, cwd: string): Ctx =
|
||||
result.person = detectPerson(st.dir)
|
||||
result.machine = detectMachine()
|
||||
result.projectUrl = detectProjectUrl(cwd)
|
||||
result.projectRef = ownerRepo(result.projectUrl)
|
||||
proc find(st: Store, typ, name: string): string =
|
||||
if name == "": return ""
|
||||
let slug = slugify(name)
|
||||
if slug in st.entities and st.entities[slug].typ == typ and
|
||||
st.entities[slug].redirect == "": return slug
|
||||
for id, e in st.entities:
|
||||
if e.typ == typ and e.redirect == "" and aliasMatches(e, name): return id
|
||||
result.personId = find(st, "person", result.person)
|
||||
result.machineId = find(st, "machine", result.machine)
|
||||
if result.projectUrl != "":
|
||||
for id, e in st.entities:
|
||||
if e.typ != "project" or e.redirect != "": continue
|
||||
if e.aliases.anyIt(normUrl(it) == normUrl(result.projectUrl) or
|
||||
(result.projectRef != "" and normUrl(it) == result.projectRef)):
|
||||
result.projectId = id
|
||||
break
|
||||
|
||||
proc cmdContext*(st: Store, cwd: string): string =
|
||||
let c = detectContext(st, cwd)
|
||||
proc line(k, v, id: string): string =
|
||||
if v == "": k & ": (not detected)\n"
|
||||
else: k & ": " & v & " (entity: " & (if id != "": "yes, " & id else: "no") & ")\n"
|
||||
result = line("person", c.person, c.personId) &
|
||||
line("machine", c.machine, c.machineId) &
|
||||
line("project", (if c.projectRef != "": c.projectRef else: c.projectUrl),
|
||||
c.projectId)
|
||||
|
||||
# ---------------------------------------------------------------- commands
|
||||
|
||||
proc machineBody*(): string =
|
||||
var lines = @["- os: " & hostOS]
|
||||
when defined(linux):
|
||||
var distro = ""
|
||||
if fileExists("/etc/os-release"):
|
||||
for l in readFile("/etc/os-release").splitLines:
|
||||
if l.startsWith("PRETTY_NAME="): distro = l[12 .. ^1].strip(chars = {'"', '\''})
|
||||
if distro != "": lines.add "- distro: " & distro
|
||||
if fileExists("/proc/sys/kernel/osrelease"):
|
||||
lines.add "- kernel: " & readFile("/proc/sys/kernel/osrelease").strip
|
||||
elif defined(macosx):
|
||||
try:
|
||||
let (o, c) = execCmdEx("sw_vers -productVersion")
|
||||
if c == 0: lines.add "- distro: macOS " & o.strip
|
||||
except CatchableError: discard
|
||||
lines.add "- arch: " & hostCPU
|
||||
lines.add "- hostname: " & detectMachine()
|
||||
lines.join("\n")
|
||||
|
||||
proc cmdInit*(dir: string): string =
|
||||
createDir(dir)
|
||||
createDir(dir / "entities")
|
||||
let sp = dir / "schema.md"
|
||||
if fileExists(sp): fail("schema.md already exists in " & dir)
|
||||
writeFile(sp, """# Schema
|
||||
|
||||
Free markdown is allowed; only the `- type:` and `- verb:` lines are read.
|
||||
|
||||
## Types
|
||||
- type: person | A human
|
||||
- type: machine | A computer
|
||||
- type: project | A code repository or project; aliases hold its git URLs
|
||||
- type: preference | A rule or habit; scope given by applies-to
|
||||
- type: concept | Anything else worth remembering
|
||||
|
||||
## Verbs
|
||||
- verb: relates-to | inverse: - | symmetric: yes | from: any | to: any | Generic association
|
||||
- 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: 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
|
||||
""")
|
||||
atomicWrite(dir / "relations.tsv", "")
|
||||
"initialized " & dir
|
||||
|
||||
proc cmdNew*(st: var Store, id, typ, label: string): string =
|
||||
if not isSlug(id): fail("invalid id (need kebab-case slug): " & id)
|
||||
if not st.schema.hasType(typ):
|
||||
fail("unknown type: " & typ & " (known: " & st.schema.types.mapIt(it[0]).join(", ") & ")")
|
||||
if id in st.entities or fileExists(st.entityPath(id)): fail("entity already exists: " & id)
|
||||
var e = Entity(id: id, typ: typ, label: (if label.strip != "": label.strip else: id),
|
||||
created: now().format("yyyy-MM-dd"), fileId: id)
|
||||
if typ == "machine": e.body = machineBody()
|
||||
st.saveEntity(e)
|
||||
"created " & id & " (" & typ & ")"
|
||||
|
||||
proc cmdLabel*(st: var Store, id0, label: string): string =
|
||||
let id = st.resolve(id0)
|
||||
if label.strip == "": fail("empty label")
|
||||
var e = st.entities[id]
|
||||
e.label = label.strip.oneLine
|
||||
st.saveEntity(e)
|
||||
"label of " & id & ": " & e.label
|
||||
|
||||
proc cmdAlias*(st: var Store, id0, alias: string): string =
|
||||
let id = st.resolve(id0)
|
||||
let a = alias.strip.replace(",", " ").oneLine
|
||||
if a == "": fail("empty alias")
|
||||
var e = st.entities[id]
|
||||
if not e.aliases.anyIt(it.toLowerAscii == a.toLowerAscii):
|
||||
e.aliases.add a
|
||||
st.saveEntity(e)
|
||||
"aliases of " & id & ": " & e.aliases.join(", ")
|
||||
|
||||
proc cmdLink*(st: var Store, s0, verb, o0, note: string): string =
|
||||
st.checkWritable
|
||||
let s = st.resolve(s0)
|
||||
let o = st.resolve(o0)
|
||||
let r0 = canonical(st.schema, s, verb, o)
|
||||
var r = r0
|
||||
r.note = oneLine(note)
|
||||
if r.s == r.o: fail("cannot link an entity to itself: " & s)
|
||||
if r.v in CycleVerbs and wouldCycle(st.rels, r.v, r.s, r.o):
|
||||
fail("would create a cycle in " & r.v & ": " & r.s & " " & r.v & " " & r.o)
|
||||
let w = domainWarning(st, r)
|
||||
if w != "": st.warnings.add w
|
||||
let idx = st.rels.findIt(it.s == r.s and it.v == r.v and it.o == r.o)
|
||||
if idx >= 0:
|
||||
if r.note != "": st.rels[idx].note = r.note
|
||||
else:
|
||||
st.rels.add r
|
||||
st.saveRels
|
||||
"linked " & r.s & " " & r.v & " " & r.o
|
||||
|
||||
proc cmdUnlink*(st: var Store, s0, verb, o0: string): string =
|
||||
st.checkWritable
|
||||
let r = canonical(st.schema, st.resolve(s0), verb, st.resolve(o0))
|
||||
let idx = st.rels.findIt(it.s == r.s and it.v == r.v and it.o == r.o)
|
||||
if idx < 0: fail("no such relation: " & r.s & " " & r.v & " " & r.o)
|
||||
st.rels.delete(idx)
|
||||
st.saveRels
|
||||
"unlinked " & r.s & " " & r.v & " " & r.o
|
||||
|
||||
proc suffix(note: string): string =
|
||||
if note != "": " # " & note else: ""
|
||||
|
||||
proc cmdRel*(st: Store, id0: string): string =
|
||||
let id = st.resolve(id0)
|
||||
var lines: seq[string]
|
||||
for r in st.rels:
|
||||
let v = resolveVerb(st.schema, r.v).verb
|
||||
if r.s == id:
|
||||
lines.add id & " " & r.v & " " & r.o & suffix(r.note)
|
||||
elif r.o == id:
|
||||
if v.symmetric: lines.add id & " " & r.v & " " & r.s & suffix(r.note)
|
||||
elif v.inverse != "": lines.add id & " " & v.inverse & " " & r.s & suffix(r.note)
|
||||
else: lines.add r.s & " " & r.v & " " & id & suffix(r.note)
|
||||
if lines.len == 0: return "no relations for " & id
|
||||
lines.sort
|
||||
lines.join("\n")
|
||||
|
||||
proc cmdWho*(st: Store, verb, id0: string): string =
|
||||
let id = st.resolve(id0)
|
||||
let (v, inv) = resolveVerb(st.schema, verb)
|
||||
var found: seq[string]
|
||||
for r in st.rels:
|
||||
if r.v != v.name: continue
|
||||
if v.symmetric:
|
||||
if r.o == id: found.add r.s
|
||||
elif r.s == id: found.add r.o
|
||||
elif not inv and r.o == id: found.add r.s
|
||||
elif inv and r.s == id: found.add r.o
|
||||
found.sort
|
||||
if found.len == 0: return "none"
|
||||
found.mapIt(it & " (" & st.label(it) & ")").join("\n")
|
||||
|
||||
proc cmdFind*(st: Store, text: string): string =
|
||||
let q = text.strip.toLowerAscii
|
||||
if q == "": fail("empty search text")
|
||||
var blocks: seq[string]
|
||||
for id, e in st.entities:
|
||||
var hits: seq[string]
|
||||
if q in id.toLowerAscii: hits.add " matched id"
|
||||
if q in e.label.toLowerAscii: hits.add " matched label"
|
||||
for a in e.aliases:
|
||||
if q in a.toLowerAscii: hits.add " matched alias: " & a
|
||||
for l in e.body.splitLines:
|
||||
if q in l.toLowerAscii:
|
||||
hits.add " matched body: " & l.strip
|
||||
break
|
||||
if hits.len > 0:
|
||||
blocks.add "entity " & id & " [" & e.typ & "] " & e.label & "\n" & hits.join("\n")
|
||||
for r in st.rels:
|
||||
if r.note != "" and q in r.note.toLowerAscii:
|
||||
blocks.add "relation " & r.s & " " & r.v & " " & r.o & "\n matched note: " & r.note
|
||||
if blocks.len == 0: "no matches" else: blocks.join("\n")
|
||||
|
||||
proc cmdPath*(st: Store, a0, b0: string, maxDepth: int): string =
|
||||
let a = st.resolve(a0)
|
||||
let b = st.resolve(b0)
|
||||
if a == b: return a & " (same entity)"
|
||||
type Step = object
|
||||
prev: string
|
||||
rel: Rel
|
||||
fwd: bool
|
||||
var visited = initTable[string, Step]()
|
||||
visited[a] = Step()
|
||||
var q = initDeque[(string, int)]()
|
||||
q.addLast((a, 0))
|
||||
var done = false
|
||||
while q.len > 0 and not done:
|
||||
let (cur, d) = q.popFirst
|
||||
if d >= maxDepth: continue
|
||||
for r in st.rels:
|
||||
var nxt = ""
|
||||
var fwd = true
|
||||
if r.s == cur: nxt = r.o
|
||||
elif r.o == cur:
|
||||
nxt = r.s
|
||||
fwd = false
|
||||
if nxt == "" or nxt in visited: continue
|
||||
visited[nxt] = Step(prev: cur, rel: r, fwd: fwd)
|
||||
if nxt == b:
|
||||
done = true
|
||||
break
|
||||
q.addLast((nxt, d + 1))
|
||||
if b notin visited: return "no path between " & a & " and " & b & " within " & $maxDepth & " hops"
|
||||
var hops: seq[string]
|
||||
var cur = b
|
||||
while cur != a:
|
||||
let s = visited[cur]
|
||||
let sym = resolveVerb(st.schema, s.rel.v).verb.symmetric
|
||||
hops.add (if sym: s.prev & " -" & s.rel.v & "- " & cur
|
||||
elif s.fwd: s.prev & " -" & s.rel.v & "-> " & cur
|
||||
else: s.prev & " <-" & s.rel.v & "- " & cur)
|
||||
cur = s.prev
|
||||
hops.reverse
|
||||
hops.join("\n") & "\n(" & $hops.len & " hops)"
|
||||
|
||||
proc cmdMerge*(st: var Store, from0, into0: string): string =
|
||||
st.checkWritable
|
||||
if from0 notin st.entities: fail("entity not found: " & from0)
|
||||
if st.entities[from0].redirect != "":
|
||||
fail(from0 & " is already merged into " & st.entities[from0].redirect)
|
||||
let f = from0
|
||||
let t = st.resolve(into0)
|
||||
if f == t: fail("cannot merge an entity into itself")
|
||||
var newRels: seq[Rel]
|
||||
for r in st.rels:
|
||||
var x = r
|
||||
if x.s == f: x.s = t
|
||||
if x.o == f: x.o = t
|
||||
if x.s == x.o: continue
|
||||
try:
|
||||
if resolveVerb(st.schema, x.v).verb.symmetric and x.s > x.o: swap(x.s, x.o)
|
||||
except SirmemError: discard
|
||||
newRels.add x
|
||||
newRels = normalizeRels(newRels)
|
||||
let cyc = findCycles(newRels)
|
||||
if cyc.len > 0: fail("merge would create a cycle: " & cyc[0])
|
||||
var fe = st.entities[f]
|
||||
var te = st.entities[t]
|
||||
if fe.typ != te.typ:
|
||||
st.warnings.add "merging different types: " & f & " (" & fe.typ & ") into " & t & " (" & te.typ & ")"
|
||||
for a in fe.aliases:
|
||||
if not te.aliases.anyIt(it.toLowerAscii == a.toLowerAscii): te.aliases.add a
|
||||
fe.redirect = t
|
||||
fe.aliases = @[]
|
||||
fe.body = "Merged into " & t & "."
|
||||
st.saveEntity(te)
|
||||
st.saveEntity(fe)
|
||||
st.rels = newRels
|
||||
st.saveRels
|
||||
"merged " & f & " into " & t
|
||||
|
||||
proc cmdPrefs*(st: Store, cwd: string): string =
|
||||
let c = detectContext(st, cwd)
|
||||
type Lvl = enum lEverywhere, lMachine, lPerson, lProject
|
||||
let names = ["everywhere", "machine", "person", "project"]
|
||||
var applicable: seq[(string, Lvl)]
|
||||
for id, e in st.entities:
|
||||
if e.typ != "preference" or e.redirect != "": continue
|
||||
let targets = st.rels.filterIt(it.v == "applies-to" and it.s == id).mapIt(it.o)
|
||||
if targets.len == 0:
|
||||
applicable.add (id, lEverywhere)
|
||||
continue
|
||||
var best = -1
|
||||
for t in targets:
|
||||
if c.machineId != "" and t == c.machineId: best = max(best, ord(lMachine))
|
||||
if c.personId != "" and t == c.personId: best = max(best, ord(lPerson))
|
||||
if c.projectId != "" and t == c.projectId: best = max(best, ord(lProject))
|
||||
if best >= 0: applicable.add (id, Lvl(best))
|
||||
let ids = applicable.mapIt(it[0])
|
||||
var superseded: seq[string]
|
||||
for r in st.rels:
|
||||
if r.v == "supersedes" and r.s in ids: superseded.add r.o
|
||||
result = "Preferences for person=" & (if c.personId != "": c.personId else: "-") &
|
||||
" machine=" & (if c.machineId != "": c.machineId else: "-") &
|
||||
" project=" & (if c.projectId != "": c.projectId else: "-") &
|
||||
". Groups are in precedence order everywhere < machine < person < project; later groups win on conflict.\n"
|
||||
var any = false
|
||||
for lvl in Lvl:
|
||||
var items = applicable.filterIt(it[1] == lvl and it[0] notin superseded).mapIt(it[0])
|
||||
if items.len == 0: continue
|
||||
items.sort
|
||||
any = true
|
||||
result.add "\n## " & names[ord(lvl)] & "\n"
|
||||
for id in items:
|
||||
let e = st.entities[id]
|
||||
result.add "\n### " & e.label & " (" & id & ")\n"
|
||||
if e.body != "": result.add e.body & "\n"
|
||||
if not any: result.add "\n(no applicable preferences)\n"
|
||||
result.removeSuffix('\n')
|
||||
|
||||
proc cmdLint*(st: Store, errorCount: var int): string =
|
||||
var errs, warns: seq[string]
|
||||
for e in st.schema.errors: errs.add e
|
||||
for e in st.loadErrors: errs.add e
|
||||
for b in st.badRelLines: errs.add "relations.tsv: malformed " & b
|
||||
var seen: seq[(string, string, string)]
|
||||
for r in st.rels:
|
||||
let tag = r.s & " " & r.v & " " & r.o
|
||||
var verb: Verb
|
||||
var known = true
|
||||
try:
|
||||
let (v, inv) = resolveVerb(st.schema, r.v)
|
||||
verb = v
|
||||
if inv:
|
||||
errs.add "relation uses inverse verb name (store canonical '" & v.name & "'): " & tag
|
||||
except SirmemError:
|
||||
known = false
|
||||
errs.add "unknown verb: " & tag
|
||||
for id in [r.s, r.o]:
|
||||
if id notin st.entities: errs.add "dangling id " & id & " in: " & tag
|
||||
elif st.entities[id].redirect != "":
|
||||
warns.add "relation references merged tombstone " & id & ": " & tag
|
||||
if r.s == r.o: errs.add "self relation: " & tag
|
||||
let key = (r.s, r.v, r.o)
|
||||
if key in seen: errs.add "duplicate relation: " & tag
|
||||
seen.add key
|
||||
if known and verb.symmetric and r.s > r.o:
|
||||
errs.add "non-canonical symmetric relation (subject must sort first): " & tag
|
||||
if known:
|
||||
let w = domainWarning(st, r)
|
||||
if w != "": warns.add w
|
||||
for c in findCycles(st.rels): errs.add c
|
||||
var used: seq[string]
|
||||
for r in st.rels:
|
||||
used.add r.s
|
||||
used.add r.o
|
||||
for id, e in st.entities:
|
||||
if e.redirect == "" and id notin used: warns.add "orphan entity: " & id
|
||||
if e.fileId != id: warns.add "entity id " & id & " differs from filename " & e.fileId & ".md"
|
||||
if not st.schema.hasType(e.typ) and e.redirect == "":
|
||||
warns.add "entity " & id & " has type not in schema: " & e.typ
|
||||
errorCount = errs.len
|
||||
var lines: seq[string]
|
||||
for e in errs: lines.add "error: " & e
|
||||
for w in warns: lines.add "warning: " & w
|
||||
lines.add $errs.len & " errors, " & $warns.len & " warnings"
|
||||
lines.join("\n")
|
||||
|
||||
# ---------------------------------------------------------------- dispatch
|
||||
|
||||
const Usage* = """sirmem - file-based knowledge-graph memory for LLM agents
|
||||
|
||||
usage: sirmem [--dir <path>] <command> [args]
|
||||
data dir: --dir <path> or env SIRMEM_DIR (required)
|
||||
|
||||
commands:
|
||||
init create schema.md (default), entities/, relations.tsv
|
||||
context detected person, machine, project
|
||||
new <id> <type> [label] create entity
|
||||
label <id> <new label> change label
|
||||
alias <id> <alias> add alias
|
||||
link <s> [verb] <o> [note] add relation (default verb: relates-to)
|
||||
unlink <s> <verb> <o> remove relation
|
||||
rel <id> all relations of an entity
|
||||
who <verb> <id> subjects having <verb> relation to id
|
||||
find <text> search ids, labels, aliases, bodies, notes
|
||||
path <a> <b> [maxdepth=4] shortest undirected path
|
||||
merge <from> <into> merge entity, leave redirect tombstone
|
||||
prefs effective preferences for current context
|
||||
lint check data; exit 1 on errors
|
||||
--help, --version
|
||||
"""
|
||||
|
||||
proc need(args: seq[string], n: int, usage: string) =
|
||||
if args.len < n + 1: fail("usage: sirmem " & usage)
|
||||
|
||||
proc dispatch*(dir: string, args: seq[string], cwd: string,
|
||||
exitCode: var int, warnings: var seq[string]): string =
|
||||
## args[0] is the command. dir may be "" only for help/version.
|
||||
exitCode = 0
|
||||
if args.len == 0: return Usage
|
||||
let cmd = args[0]
|
||||
case cmd
|
||||
of "--help", "-h", "help": return Usage
|
||||
of "--version", "-V", "version": return "sirmem " & Version
|
||||
else: discard
|
||||
if dir == "": fail("no data dir: pass --dir <path> or set SIRMEM_DIR")
|
||||
if cmd == "init": return cmdInit(dir)
|
||||
var st = loadStore(dir)
|
||||
defer: warnings.add st.warnings
|
||||
case cmd
|
||||
of "context": result = cmdContext(st, cwd)
|
||||
of "new":
|
||||
need(args, 2, "new <id> <type> [label]")
|
||||
result = cmdNew(st, args[1], args[2], args[3 .. ^1].join(" "))
|
||||
of "label":
|
||||
need(args, 2, "label <id> <new label>")
|
||||
result = cmdLabel(st, args[1], args[2 .. ^1].join(" "))
|
||||
of "alias":
|
||||
need(args, 2, "alias <id> <alias>")
|
||||
result = cmdAlias(st, args[1], args[2 .. ^1].join(" "))
|
||||
of "link":
|
||||
need(args, 2, "link <s> [verb] <o> [note]")
|
||||
if args.len == 3: result = cmdLink(st, args[1], DefaultVerb, args[2], "")
|
||||
else: result = cmdLink(st, args[1], args[2], args[3], args[4 .. ^1].join(" "))
|
||||
of "unlink":
|
||||
need(args, 3, "unlink <s> <verb> <o>")
|
||||
result = cmdUnlink(st, args[1], args[2], args[3])
|
||||
of "rel":
|
||||
need(args, 1, "rel <id>")
|
||||
result = cmdRel(st, args[1])
|
||||
of "who":
|
||||
need(args, 2, "who <verb> <id>")
|
||||
result = cmdWho(st, args[1], args[2])
|
||||
of "find":
|
||||
need(args, 1, "find <text>")
|
||||
result = cmdFind(st, args[1 .. ^1].join(" "))
|
||||
of "path":
|
||||
need(args, 2, "path <a> <b> [maxdepth=4]")
|
||||
var d = 4
|
||||
if args.len > 3:
|
||||
try: d = parseInt(args[3])
|
||||
except ValueError: fail("maxdepth must be an integer: " & args[3])
|
||||
result = cmdPath(st, args[1], args[2], d)
|
||||
of "merge":
|
||||
need(args, 2, "merge <from> <into>")
|
||||
result = cmdMerge(st, args[1], args[2])
|
||||
of "prefs": result = cmdPrefs(st, cwd)
|
||||
of "lint":
|
||||
var n = 0
|
||||
result = cmdLint(st, n)
|
||||
if n > 0: exitCode = 1
|
||||
else: fail("unknown command: " & cmd & " (try --help)")
|
||||
Reference in New Issue
Block a user