5 Commits
Author SHA1 Message Date
SirStone e98107dcd7 fix: lint --clean keeps relates-to note on the typed relation; no orphan warning for preferences; v0.1.4
ci / release (push) Successful in 1m23s
2026-11-22 19:42:41 +01:00
SirStone dae7313e14 feat: rm guards (scope widening, merge targets), lint --clean and --suggest, v0.1.3
ci / release (push) Successful in 1m21s
2026-11-22 19:29:33 +01:00
SirStone 7d1b6aed5f feat: rm (with --cascade) and unalias commands, v0.1.2
ci / release (push) Successful in 1m13s
2026-11-22 19:05:52 +01:00
SirStone 7c44fedcab build: aarch64 uses cached glibc cross gcc (static) instead of uncached musl
ci / release (push) Successful in 1m53s
2026-11-22 18:21:36 +01:00
SirStone 32ec81ff6c build: cross-compile with Nix gcc toolchains instead of zig; drop macOS; v0.1.1
ci / release (push) Canceled after 47m21s
2026-11-22 17:56:42 +01:00
9 changed files with 521 additions and 115 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
# Gitea Actions, triggered only by pushed v* tags (the runner is slow): tests, then release.
# Runs on the NixOS host runner (label `nixos`, host mode) with plain shell steps only.
# Tooling comes from the host's devbox, which honours devbox.lock like local runs.
# Tooling comes from the host's devbox (honours devbox.lock); cross gcc comes from nix shell.
# Release upload goes through the Gitea REST API with the built-in job token.
name: ci
on:
+12 -8
View File
@@ -3,7 +3,7 @@
Nim CLI (stdlib only, no nimble deps) for a file-based knowledge-graph memory.
## Tooling: devbox
All tooling comes from devbox (nim, zig, git). Use `devbox shell` or
All tooling comes from devbox (nim, git, file). Cross toolchains come from Nix (below). Use `devbox shell` or
`devbox run <script>`. Fixing devbox.json / devbox.lock or running
`devbox update` needs no permission.
@@ -11,19 +11,23 @@ All tooling comes from devbox (nim, zig, git). Use `devbox shell` or
- `src/sirmem/core.nim`: all logic; every command is a `cmdXxx` proc returning its output, `dispatch` routes args.
- `src/sirmem.nim`: thin main (`--dir`/`SIRMEM_DIR`, exit codes, stderr).
- `tests/test_all.nim`: std/unittest; the CLI suite runs `bin/sirmem`, so build first.
- `scripts/build.sh`, `scripts/zigcc`: cross-compile with `zig cc`.
- `scripts/build.sh`: cross-compile with Nix-provided gcc toolchains.
- `.gitea/workflows/release.yml`: CI (test on push, release on `v*` tag).
## Build / test
- `devbox run build` -> `bin/sirmem`
- `devbox run test` (builds the binary, then runs the tests)
## Cross-compile (zig cc)
`scripts/build.sh <nim-os> <nim-cpu> <zig-target> <out>`, or `devbox run cross-all` -> `dist/`.
Targets: linux amd64 `x86_64-linux-musl`, linux arm64 `aarch64-linux-musl`,
macosx arm64 `aarch64-macos`, windows amd64 `x86_64-windows-gnu`.
Known zig 0.16 quirks (documented in build.sh): do not use `--opt:size`; linux-musl needs
`-d:useMalloc`; linux arm64 needs `--tlsEmulation:on` and links flakily, so the script retries.
## Cross-compile (Nix cross gcc)
`scripts/build.sh <linux-x86_64|linux-aarch64|windows-x86_64> [out]`, or `devbox run cross-all` -> `dist/`.
Follows https://nim-lang.org/docs/nimc.html#crossminuscompilation: the script runs `nix shell nixpkgs#<pkg>.stdenv.cc`
and sets `--os/--cpu` plus `--<cpu>.<os>.gcc.exe/.linkerexe/.path` (and plain `--gcc.*`, since the
per-platform ones are ignored when target == host).
- linux-x86_64: `pkgsCross.musl64`, static. linux-aarch64: `pkgsCross.aarch64-multiplatform` (glibc, static via `glibc.static`; the musl gcc is not in cache.nixos.org so CI would compile gcc).
- windows-x86_64: `pkgsCross.mingwW64`, `-d:mingw`, static; needs `windows.mcfgthreads` on `-L` (gcc 15 threading lib).
Supported targets: linux x86_64, linux aarch64, windows x86_64. **No macOS build** (dropped; no darwin toolchain).
Quirk: nim.cfg pins the mingw `gcc.path` to /usr/bin, so the script overrides `.gcc.path`.
The Nim version must be the devbox one (>= 2.2.12); older system nims fail to compile.
## Conventions
- Errors: raise `SirmemError` (via `fail`); main prints `sirmem: error: ...`, exit 1. Warnings go to `Store.warnings` (stderr).
+18
View File
@@ -11,6 +11,8 @@ sirmem new my-proj project "My Project"
sirmem alias my-proj owner/repo
sirmem link my-proj uses sirlaptop "dev box"
sirmem rel my-proj
sirmem unalias my-proj owner/repo # remove an alias
sirmem rm sirlaptop --cascade # delete an entity (and its relations)
sirmem prefs
sirmem lint
```
@@ -19,6 +21,22 @@ Data dir: `schema.md` (types and verbs), `relations.tsv` (sorted, one direction)
`entities/<id>.md` (front-matter + body). Run `sirmem --help` for all commands.
Build: `devbox run build`, test: `devbox run test`. See AGENTS.md.
`rm <id>` refuses while the entity has relations (listed); `--cascade` removes them too and prints each one.
A merge tombstone is never removed while relations or other redirects still point to it, and `rm` refuses to
delete an entity that tombstones point to, or one that is the only `applies-to` target of a preference (it would
silently become "everywhere"); the offending preferences/tombstones are listed.
`sirmem lint --clean` applies structural fixes only and prints each change: removes unreferenced redirect
tombstones, `relates-to` lines whose pair is also linked by a typed verb (a non-empty note is appended to the first typed
relation's note, separated by ` | `), and `part-of` lines implied by a
longer `part-of` chain. `sirmem lint --suggest` is read-only and prints numbered candidates (superseded,
contradicted, duplicate by normalised label/alias, orphan) with a suggested action for an LLM to review with the
user. Both flags can be combined (clean first, then lint, then suggest).
Extra over the spec: `init` command; env `SIRMEM_MACHINE` overrides the detected hostname.
MIT licensed.
## Releases
Prebuilt, statically linked binaries for linux x86_64, linux aarch64 and windows x86_64 are attached to each
release (`sirmem-linux-x86_64`, `sirmem-linux-aarch64`, `sirmem-windows-x86_64.exe`, plus `SHA256SUMS`).
There is no macOS build for now. They are cross-built with Nix-provided gcc toolchains (`devbox run cross-all`).
+5 -6
View File
@@ -2,8 +2,8 @@
"$schema": "https://raw.githubusercontent.com/jetify-com/devbox/0.17.2/.schema/devbox.schema.json",
"packages": [
"nim@latest",
"zig@latest",
"git@latest"
"git@latest",
"file@latest"
],
"shell": {
"scripts": {
@@ -14,10 +14,9 @@
"mkdir -p bin && nim c -d:release --hints:off -o:bin/sirmem src/sirmem.nim && nim c -r --hints:off -o:bin/test_all tests/test_all.nim"
],
"cross-all": [
"scripts/build.sh linux amd64 x86_64-linux-musl dist/sirmem-linux-x86_64",
"scripts/build.sh linux arm64 aarch64-linux-musl dist/sirmem-linux-aarch64",
"scripts/build.sh macosx arm64 aarch64-macos dist/sirmem-macos-aarch64",
"scripts/build.sh windows amd64 x86_64-windows-gnu dist/sirmem-windows-x86_64.exe"
"scripts/build.sh linux-x86_64",
"scripts/build.sh linux-aarch64",
"scripts/build.sh windows-x86_64"
]
}
}
+65 -64
View File
@@ -1,6 +1,71 @@
{
"lockfile_version": "1",
"packages": {
"file@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#file",
"source": "devbox-search",
"version": "5.48",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/y44vpziwbzfm8020dzlqqbybyyy7lb6g-file-5.48",
"default": true
},
{
"name": "man",
"path": "/nix/store/7yg6zjnp45r9wmqcl25j53la8kq4vgqx-file-5.48-man",
"default": true
},
{
"name": "dev",
"path": "/nix/store/dwcwy285s7cxb2j17czakarhdhhy7ckm-file-5.48-dev"
}
],
"store_path": "/nix/store/y44vpziwbzfm8020dzlqqbybyyy7lb6g-file-5.48"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/66sd1x1hls0yijibn00iz08jh4fnas9z-file-5.48",
"default": true
},
{
"name": "man",
"path": "/nix/store/zxp92l25sfj2hlk18khjhzq1gq4s6596-file-5.48-man",
"default": true
},
{
"name": "dev",
"path": "/nix/store/0164l0qhhgf7q5lbpyqi0iplk3l9p0q9-file-5.48-dev"
}
],
"store_path": "/nix/store/66sd1x1hls0yijibn00iz08jh4fnas9z-file-5.48"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/g0fbnccaan8q0rxlw43xnbyb90i94vlc-file-5.48",
"default": true
},
{
"name": "man",
"path": "/nix/store/8za7zyz740a9zhdzpfxsm4bw3g9pw6g0-file-5.48-man",
"default": true
},
{
"name": "dev",
"path": "/nix/store/gqv62wzqrdmdspyrzwx4b028rvf1yshv-file-5.48-dev"
}
],
"store_path": "/nix/store/g0fbnccaan8q0rxlw43xnbyb90i94vlc-file-5.48"
}
}
},
"git@latest": {
"last_modified": "2026-10-08T19:21:32Z",
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#git",
@@ -100,70 +165,6 @@
"store_path": "/nix/store/0cbdz34lsakfirycixckf6ypsd8hazhg-x86_64-unknown-linux-gnu-nim-wrapper-2.2.12"
}
}
},
"zig@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#zig",
"source": "devbox-search",
"version": "0.16.0",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/1yqcgzbny4k5p4b9irn5vw4vy8b5d5dh-zig-0.16.0",
"default": true
},
{
"name": "doc",
"path": "/nix/store/5d4ycm0d1mc7j7a58b7bj1b22mw4cprr-zig-0.16.0-doc"
}
],
"store_path": "/nix/store/1yqcgzbny4k5p4b9irn5vw4vy8b5d5dh-zig-0.16.0"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/amh3bnymjncd56jwmd2hqdkciz9d7pys-zig-0.16.0",
"default": true
},
{
"name": "doc",
"path": "/nix/store/nggishdy0y2cqx3p1js220m1jl76gkmh-zig-0.16.0-doc"
}
],
"store_path": "/nix/store/amh3bnymjncd56jwmd2hqdkciz9d7pys-zig-0.16.0"
},
"x86_64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/7wsm80i713618s84j1hw2nk2v58zf081-zig-0.16.0",
"default": true
},
{
"name": "doc",
"path": "/nix/store/6h4nc1xc8kr3wfn7f4f6ma4my48mn9qk-zig-0.16.0-doc"
}
],
"store_path": "/nix/store/7wsm80i713618s84j1hw2nk2v58zf081-zig-0.16.0"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/qsk2cha4nk70bpz53qix9mypj4mjcbsr-zig-0.16.0",
"default": true
},
{
"name": "doc",
"path": "/nix/store/7g6azggrab0gzrcw2vrbzl0i33pb762d-zig-0.16.0-doc"
}
],
"store_path": "/nix/store/qsk2cha4nk70bpz53qix9mypj4mjcbsr-zig-0.16.0"
}
}
}
}
}
+31 -20
View File
@@ -1,24 +1,35 @@
#!/usr/bin/env bash
# usage: scripts/build.sh <nim-os> <nim-cpu> <zig-target> <output>
# e.g. scripts/build.sh windows amd64 x86_64-windows-gnu dist/sirmem-windows-x86_64.exe
# usage: scripts/build.sh <linux-x86_64|linux-aarch64|windows-x86_64> [output]
# Cross-compiles following https://nim-lang.org/docs/nimc.html#crossminuscompilation
# with the cross gcc from nixpkgs, fetched on demand through `nix shell`.
set -euo pipefail
cd "$(dirname "$0")/.."
os=$1 cpu=$2 target=$3 out=$4
target=${1:?target: linux-x86_64 | linux-aarch64 | windows-x86_64}
case $target in
linux-x86_64)
out=${2:-dist/sirmem-linux-x86_64}; pkg=pkgsCross.musl64; triple=x86_64-unknown-linux-musl
nimcpu=amd64 nimos=linux; flags=(--passL:-static) ;;
linux-aarch64)
out=${2:-dist/sirmem-linux-aarch64}; pkg=pkgsCross.aarch64-multiplatform; triple=aarch64-unknown-linux-gnu
# musl variant is not in cache.nixos.org (CI would compile gcc), so static glibc instead
st=$(nix build --no-link --print-out-paths "nixpkgs#$pkg.glibc.static" | head -1)
nimcpu=arm64 nimos=linux; flags=(--passL:-static "--passL:-L$st/lib") ;;
windows-x86_64)
out=${2:-dist/sirmem-windows-x86_64.exe}; pkg=pkgsCross.mingwW64; triple=x86_64-w64-mingw32
nimcpu=amd64 nimos=windows
# gcc 15 mingw threads via mcfgthread: its import lib is not on gcc's default search path
mcf=$(nix build --no-link --print-out-paths "nixpkgs#$pkg.windows.mcfgthreads")
flags=(-d:mingw --passL:-static "--passL:-L$mcf/lib") ;;
*) echo "unknown target $target" >&2; exit 2 ;;
esac
mkdir -p "$(dirname "$out")"
export ZIG_TARGET=$target
# Notes from trial and error with zig 0.16: --opt:size breaks linking (empty undefined
# symbols); -d:useMalloc is needed on linux-musl; aarch64-linux needs --tlsEmulation:on
# (TLS relocs fail to link otherwise) but x86_64-linux fails *with* it.
extra=()
if [ "$os" = linux ] && [ "$cpu" = arm64 ]; then extra+=(--tlsEmulation:on); fi
# zig cc 0.16 sporadically fails to link aarch64-linux ("undefined symbol:" with an empty
# name, also seen as CacheCheckFailed); a retry succeeds, so retry up to 5 times.
for attempt in 1 2 3 4 5; do
rm -rf "nimcache/$target"
if nim c -d:release -d:strip -d:useMalloc --parallelBuild:1 --hints:off \
"${extra[@]}" --os:"$os" --cpu:"$cpu" \
--cc:clang --clang.exe:"$PWD/scripts/zigcc" --clang.linkerexe:"$PWD/scripts/zigcc" \
--nimcache:"nimcache/$target" -o:"$out" src/sirmem.nim ; then exit 0; fi
echo "build attempt $attempt failed, retrying" >&2
done
exit 1
# `nix shell` puts <triple>-gcc on PATH. Nim's <cpu>.<os>.gcc.* settings (as in the Nim
# cross-compilation docs) are what a cross build needs; they are ignored when target == host,
# so plain gcc.* is set too. nim.cfg pins the mingw gcc.path to /usr/bin, so path is set too.
export NIMCPU=$nimcpu NIMOS=$nimos TRIPLE=$triple OUT=$out TARGET=$target
exec nix shell "nixpkgs#$pkg.stdenv.cc" --command bash -c '
gcc=$TRIPLE-gcc; dir=$(dirname "$(command -v "$gcc")")
exec nim c -d:release -d:strip --hints:off --os:$NIMOS --cpu:$NIMCPU "$@" \
--gcc.exe:"$gcc" --gcc.linkerexe:"$gcc" \
--$NIMCPU.$NIMOS.gcc.path:"$dir" --$NIMCPU.$NIMOS.gcc.exe:"$gcc" --$NIMCPU.$NIMOS.gcc.linkerexe:"$gcc" \
--nimcache:"nimcache/$TARGET" -o:"$OUT" src/sirmem.nim' _ "${flags[@]}"
-12
View File
@@ -1,12 +0,0 @@
#!/usr/bin/env bash
# C compiler/linker wrapper so Nim can use `zig cc` for cross-compiling.
# Needs ZIG_TARGET (e.g. aarch64-linux-musl). Filters flags zig cc rejects.
args=()
for a in "$@"; do
case "$a" in
-Wl,--no-gc-sections|-Wl,-rpath*|-fpie|-pie) ;;
-ldl) case "$ZIG_TARGET" in *windows*) ;; *) args+=("$a") ;; esac ;;
*) args+=("$a") ;;
esac
done
exec zig cc -target "${ZIG_TARGET:?ZIG_TARGET not set}" "${args[@]}"
+214 -4
View File
@@ -6,7 +6,7 @@ import std/[os, strutils, sequtils, algorithm, tables, times, osproc,
nativesockets, deques]
const
Version* = "0.1.0"
Version* = "0.1.4"
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
@@ -493,6 +494,62 @@ proc cmdUnlink*(st: var Store, s0, verb, o0: string): string =
proc suffix(note: string): string =
if note != "": " # " & note else: ""
proc cmdUnalias*(st: var Store, id0, alias: string): string =
## Acts on the entity named, tombstones included (no redirect resolving).
if id0 notin st.entities: fail("entity not found: " & id0)
let a = alias.strip.replace(",", " ").oneLine
var e = st.entities[id0]
let idx = e.aliases.findIt(it.toLowerAscii == a.toLowerAscii)
if a == "" or idx < 0: fail("alias not found on " & id0 & ": " & alias.strip)
e.aliases.delete(idx)
st.saveEntity(e)
"aliases of " & id0 & ": " & e.aliases.join(", ")
proc cmdRm*(st: var Store, id: string, cascade: bool): string =
## Deletes entities/<id>.md. Acts on the named id (a tombstone is not resolved).
st.checkWritable
if id notin st.entities: fail("entity not found: " & id)
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 != "":
if rels.len > 0 or pointing.len > 0:
var msg = "refusing to remove tombstone " & id & " (merged into " & e.redirect &
"); still referenced, resolve first:"
if rels.len > 0: msg.add "\nrelations:\n" & relLines.join("\n")
if pointing.len > 0: msg.add "\nredirects:\n" & pointing.mapIt(" " & it & " -> " & id).join("\n")
fail(msg)
elif rels.len > 0 and not cascade:
fail("refusing to remove " & id & ": it has " & $rels.len &
" relation(s) (use --cascade to remove them too):\n" & relLines.join("\n"))
var lines: seq[string]
if rels.len > 0:
st.rels = st.rels.filterIt(not (it.s == id or it.o == id))
st.saveRels
for l in relLines: lines.add "removed relation" & l[1 .. ^1]
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 entities/" & splitFile(fp).name & ".md"
for t, te in st.entities:
if te.redirect == id: st.warnings.add "tombstone " & t & " now redirects to removed " & id
lines.join("\n")
proc cmdRel*(st: Store, id0: string): string =
let id = st.resolve(id0)
var lines: seq[string]
@@ -698,7 +755,7 @@ proc cmdLint*(st: Store, errorCount: var int): string =
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.redirect == "" and e.typ != "preference" 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
@@ -709,6 +766,132 @@ 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[bool]
for r in rels:
keep.add not (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))))
for idx in 0 ..< rels.len:
if keep[idx]: continue
let r = rels[idx]
var target = -1
for j in 0 ..< rels.len:
let t = rels[j]
if t.v != DefaultVerb and ((t.s == r.s and t.o == r.o) or (t.s == r.o and t.o == r.s)):
if target < 0 or (t.s, t.v, t.o) < (rels[target].s, rels[target].v, rels[target].o):
target = j
var msg = "removed relation " & r.s & " " & r.v & " " & r.o & suffix(r.note) &
" (pair already linked by a typed verb)"
if r.note != "" and target >= 0:
let t = rels[target]
rels[target].note = if t.note == "": r.note else: t.note & " | " & r.note
msg.add "; note appended to " & t.s & " " & t.v & " " & t.o
lines.add msg
var kept: seq[Rel]
for idx in 0 ..< rels.len:
if keep[idx]: kept.add rels[idx]
rels = kept
# 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 != st.rels:
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
@@ -722,15 +905,25 @@ commands:
new <id> <type> [label] create entity
label <id> <new label> change label
alias <id> <alias> add alias
unalias <id> <alias> remove 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
rm <id> [--cascade] delete entity; refuses if it has relations
(--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
"""
@@ -766,6 +959,16 @@ proc dispatch*(dir: string, args: seq[string], cwd: string,
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 "unalias":
need(args, 2, "unalias <id> <alias>")
result = cmdUnalias(st, args[1], args[2 .. ^1].join(" "))
of "rm":
need(args, 1, "rm <id> [--cascade]")
let rest = args[1 .. ^1]
let casc = "--cascade" in rest
let ids = rest.filterIt(it != "--cascade")
if ids.len != 1: fail("usage: sirmem rm <id> [--cascade]")
result = cmdRm(st, ids[0], casc)
of "unlink":
need(args, 3, "unlink <s> <verb> <o>")
result = cmdUnlink(st, args[1], args[2], args[3])
@@ -790,7 +993,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)")
+175
View File
@@ -174,6 +174,73 @@ suite "find / 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()
@@ -282,6 +349,8 @@ suite "lint":
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" &
@@ -312,6 +381,112 @@ suite "lint":
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"