feat: sirmem v0.1.0 knowledge-graph memory CLI
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
# Gitea Actions (GitHub-Actions-compatible). NOT YET RUN: untested on a real runner.
|
||||
# Assumptions:
|
||||
# - A runner labelled `ubuntu-latest` (adjust `runs-on`) with Docker/Node available for actions.
|
||||
# - Nim and zig are installed via devbox (jetify-com/devbox-install-action); the nix store is fetched from cache.nixos.org.
|
||||
# - Release upload goes through the Gitea REST API (curl) with the built-in token
|
||||
# `${{ github.token }}` (Gitea maps it to GITEA_TOKEN); the token must be allowed to write releases.
|
||||
# This avoids depending on third-party release actions that target GitHub only.
|
||||
name: ci
|
||||
on:
|
||||
push:
|
||||
branches: ["**"]
|
||||
tags: ["v*"]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: jetify-com/devbox-install-action@v0.13.0
|
||||
with:
|
||||
enable-cache: "false"
|
||||
- run: devbox run test
|
||||
|
||||
release:
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
needs: test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: jetify-com/devbox-install-action@v0.13.0
|
||||
with:
|
||||
enable-cache: "false"
|
||||
- name: Build all targets
|
||||
run: devbox run cross-all
|
||||
- name: Checksums
|
||||
run: cd dist && sha256sum sirmem-* > SHA256SUMS && cat SHA256SUMS
|
||||
- name: Create release and upload assets
|
||||
env:
|
||||
TOKEN: ${{ github.token }}
|
||||
SERVER: ${{ github.server_url }}
|
||||
REPO: ${{ github.repository }}
|
||||
TAG: ${{ github.ref_name }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
api="$SERVER/api/v1/repos/$REPO"
|
||||
id=$(curl -fsS -X POST "$api/releases" \
|
||||
-H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
|
||||
-d "{\"tag_name\":\"$TAG\",\"name\":\"$TAG\"}" | sed -n 's/.*"id":\([0-9]*\).*/\1/p' | head -1)
|
||||
for f in dist/*; do
|
||||
curl -fsS -X POST "$api/releases/$id/assets?name=$(basename "$f")" \
|
||||
-H "Authorization: token $TOKEN" -F "attachment=@$f"
|
||||
done
|
||||
@@ -0,0 +1,4 @@
|
||||
bin/
|
||||
dist/
|
||||
nimcache/
|
||||
*.tmp
|
||||
@@ -0,0 +1,30 @@
|
||||
# sirmem
|
||||
|
||||
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
|
||||
`devbox run <script>`. Fixing devbox.json / devbox.lock or running
|
||||
`devbox update` needs no permission.
|
||||
|
||||
## Layout
|
||||
- `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`.
|
||||
- `.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.
|
||||
|
||||
## Conventions
|
||||
- Errors: raise `SirmemError` (via `fail`); main prints `sirmem: error: ...`, exit 1. Warnings go to `Store.warnings` (stderr).
|
||||
- Relations are always rewritten through `saveRels` (sorted, unique, atomic).
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Davide Cappellini
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,24 @@
|
||||
# sirmem
|
||||
|
||||
Small CLI for a file-based knowledge-graph memory used by LLM agents. Plain
|
||||
text in, plain text out; the data is Markdown and TSV you can read and diff.
|
||||
|
||||
```
|
||||
sirmem init --dir ~/memory/data # default schema.md
|
||||
export SIRMEM_DIR=~/memory/data
|
||||
sirmem new sirlaptop machine
|
||||
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 prefs
|
||||
sirmem lint
|
||||
```
|
||||
|
||||
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.
|
||||
Extra over the spec: `init` command; env `SIRMEM_MACHINE` overrides the detected hostname.
|
||||
|
||||
MIT licensed.
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"$schema": "https://raw.githubusercontent.com/jetify-com/devbox/0.17.2/.schema/devbox.schema.json",
|
||||
"packages": [
|
||||
"nim@latest",
|
||||
"zig@latest",
|
||||
"git@latest"
|
||||
],
|
||||
"shell": {
|
||||
"scripts": {
|
||||
"build": [
|
||||
"mkdir -p bin && nim c -d:release --hints:off -o:bin/sirmem src/sirmem.nim"
|
||||
],
|
||||
"test": [
|
||||
"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"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
{
|
||||
"lockfile_version": "1",
|
||||
"packages": {
|
||||
"git@latest": {
|
||||
"last_modified": "2026-10-08T19:21:32Z",
|
||||
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#git",
|
||||
"source": "devbox-search",
|
||||
"version": "2.55.0",
|
||||
"systems": {
|
||||
"aarch64-darwin": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/gw7c7m0dwca5lg4152x9lpmxpj171bzw-git-2.55.0",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "doc",
|
||||
"path": "/nix/store/0f4p7kbl8hsdvynpk8n951bcbdx7qn3j-git-2.55.0-doc"
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/gw7c7m0dwca5lg4152x9lpmxpj171bzw-git-2.55.0"
|
||||
},
|
||||
"aarch64-linux": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/kj6aff4gmz3snpp35rl3gysbl9srd81a-git-2.55.0",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "debug",
|
||||
"path": "/nix/store/8l21kawpzlskyby6dhkjmdyamp34irpv-git-2.55.0-debug"
|
||||
},
|
||||
{
|
||||
"name": "doc",
|
||||
"path": "/nix/store/gzjmfgd110655anwlnj6qlj5ws8vacn2-git-2.55.0-doc"
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/kj6aff4gmz3snpp35rl3gysbl9srd81a-git-2.55.0"
|
||||
},
|
||||
"x86_64-linux": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/lg46w7hrjx7kylsh6645c9l975i8h43b-git-2.55.0",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "doc",
|
||||
"path": "/nix/store/5f39kd6g3irac28rgk89yqwaamaj01rx-git-2.55.0-doc"
|
||||
},
|
||||
{
|
||||
"name": "debug",
|
||||
"path": "/nix/store/jfnrrjgvhv0la9dpzb1yxg8bx2gf9aii-git-2.55.0-debug"
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/lg46w7hrjx7kylsh6645c9l975i8h43b-git-2.55.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"github:NixOS/nixpkgs/nixpkgs-unstable": {
|
||||
"last_modified": "2026-10-20T14:23:57Z",
|
||||
"resolved": "github:NixOS/nixpkgs/5adc50831c259f87faeb09ddf930d43597197473?lastModified=1792506237&narHash=sha256-Q%2F8KLB6jNfpaUN1HAedE%2Fu%2FEt9feE%2FzYSsutBLKrCFk%3D"
|
||||
},
|
||||
"nim@latest": {
|
||||
"last_modified": "2026-10-02T22:55:44Z",
|
||||
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#nim",
|
||||
"source": "devbox-search",
|
||||
"version": "2.2.12",
|
||||
"systems": {
|
||||
"aarch64-darwin": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/h055h3lxxsm8kql0mannw3706x740x7f-arm64-apple-darwin-nim-wrapper-2.2.12",
|
||||
"default": true
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/h055h3lxxsm8kql0mannw3706x740x7f-arm64-apple-darwin-nim-wrapper-2.2.12"
|
||||
},
|
||||
"aarch64-linux": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/2fh7rg634j8969c1r394llrsjmmhaip7-aarch64-unknown-linux-gnu-nim-wrapper-2.2.12",
|
||||
"default": true
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/2fh7rg634j8969c1r394llrsjmmhaip7-aarch64-unknown-linux-gnu-nim-wrapper-2.2.12"
|
||||
},
|
||||
"x86_64-linux": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/0cbdz34lsakfirycixckf6ypsd8hazhg-x86_64-unknown-linux-gnu-nim-wrapper-2.2.12",
|
||||
"default": true
|
||||
}
|
||||
],
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+24
@@ -0,0 +1,24 @@
|
||||
#!/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
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
os=$1 cpu=$2 target=$3 out=$4
|
||||
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
|
||||
Executable
+12
@@ -0,0 +1,12 @@
|
||||
#!/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[@]}"
|
||||
@@ -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)")
|
||||
@@ -0,0 +1,328 @@
|
||||
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 "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
|
||||
# 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 "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
|
||||
Reference in New Issue
Block a user