KeiSeiKit-1.0/_primitives/_rust/kei-graph-export/src/main.rs
Parfii-bot a31a056f61 feat(graph): live runtime DNA viewer — kei-graph-export + lbm-graph-viz adapter
User pushback: "можно нашего Кейси подключить к обсидиан? будет в
онлайне строить граф из всех наших агентов?"

Closer-to-question architecture: don't build new Obsidian plugin —
re-use the legacy `~/Projects/lbm-graph-viz/` D3 viewer (lineage:
keicode → living-graph → lbm → lbm-graph-viz → keisei-graph). Strip
its Hebbian/co-change edges, replace with DNA-derived edges from the
kei-registry + kei-ledger. Open in any browser, file://...index.html.

NEW Rust crate `_primitives/_rust/kei-graph-export/` (~440 LOC, 5 files)

Reads:
  ~/.claude/registry.sqlite       (730 active blocks)
  ~/.claude/agents/ledger.sqlite  (6 agents post-cleanup)
  _manifests/*.toml               (38 agent manifests)

Emits 581-node, 291-edge graph. Edge types:
  block_dep        171  manifest → atom (blocks=[])
  path_ref          99  manifest → atom (path:NAME refs)
  branch_lineage    11  parent_branch → branch
  agent_uses_manifest 10  agent → manifest (slug from branch name)

Output formats:
  --format spaces-fragment  →  `window.RUNTIME_SPACE = {...}` JS file
  --format json             →  raw {nodes, links} for downstream tools

Block-name lookup is multi-resolution: each block is registered under
display name + lowercased + file-stem slug (from path basename) so
manifest references like `blocks = ["baseline"]` resolve to a registry
row whose `name` column holds "BASELINE — inherit from Main Claude".
Without this fix the graph had 0 block_dep edges; with it, 171.

NEW background updater `hooks/graph-export-watcher.sh` + launchd plist
template `_primitives/templates/io.keisei.graph-export.plist`

5-second loop:
  while true; do
      kei-graph-export --format spaces-fragment --output <viz>/data-runtime.js.tmp
      mv <viz>/data-runtime.js.tmp <viz>/data-runtime.js  # atomic
      sleep 5
  done

launchd plist substitutes `HOME_DIR` and `HOOKS_DIR` placeholders at
install time. RunAtLoad=true, KeepAlive=true. Logs to
~/.claude/memory/graph-export.log. Bypass: GRAPH_EXPORT_BYPASS=1.

Loaded into user-side launchd (PID 16474 confirmed running). File
mtime advances every 5s — live updates verified.

PATCH `~/Projects/lbm-graph-viz/index.html` (outside kit, surgical)

Three changes:
  1. Add `<script src="data-runtime.js">` BEFORE `spaces.js` (window
     global available when SPACES is defined).
  2. After spaces.js: `if (window.RUNTIME_SPACE) SPACES.runtime = window.RUNTIME_SPACE;`
  3. Auto-refresh setInterval(5s): fetch data-runtime.js, eval (re-
     assigns window.RUNTIME_SPACE), hash-compare, re-render via
     `rebuildGraph()` if currently viewing the runtime space.

window.RUNTIME_SPACE (not const RUNTIME_SPACE) avoids the
"const cannot be re-declared" error on subsequent eval() calls.

Effect: open file://~/Projects/lbm-graph-viz/index.html in any
browser, switch to "Runtime" space — full DNA graph of every agent /
atom / skill / branch / manifest / hook / primitive / rule, force-
laid-out by D3. Updates every 5 seconds without page reload.

What this does NOT do (deferred):
  - Obsidian mirror — separate work, would emit .md per node into
    ~/Projects/KeiSeiVault/. Useful for backlinks navigation but
    file-watcher latency similar to current 5s polling.
  - Skill-invocation edges — table is empty until next Skill tool
    use; will populate naturally.
  - Scoped queries (orphan finder, hot-path PageRank). Out of scope
    for v1; the JSON --format export feeds any downstream tool.
  - `agent_uses_manifest` heuristic warns on unknown subagent slugs
    (e.g. `physics-deriver` with no manifest yet). Non-fatal.

=== STATUS-TRUTH MARKER ===
shipped: functional
stubs: 0
cargo-check: PASS
behaviour-verified: yes
follow-up-required:
  - Obsidian vault mirror (Phase C, separate work)
  - Skill-edges populate from real Skill use (not blockered)
  - Hot-path PageRank highlighting in viewer (cosmetic)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 13:07:21 +08:00

66 lines
1.9 KiB
Rust

mod types;
mod nodes;
mod edges;
mod graph;
use anyhow::Result;
use clap::Parser;
use std::path::PathBuf;
#[derive(Parser)]
#[command(name = "kei-graph-export", about = "Export KeiSei graph as D3 space fragment")]
struct Cli {
#[arg(long)]
registry_db: Option<PathBuf>,
#[arg(long)]
ledger_db: Option<PathBuf>,
#[arg(long)]
manifests_dir: Option<PathBuf>,
#[arg(long, default_value = "spaces-fragment")]
format: String,
#[arg(long, short = 'o')]
output: Option<PathBuf>,
}
fn home_path(suffix: &str) -> PathBuf {
let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
PathBuf::from(home).join(suffix)
}
fn main() -> Result<()> {
let cli = Cli::parse();
let registry_db = cli.registry_db
.or_else(|| std::env::var("KEI_REGISTRY_DB").ok().map(PathBuf::from))
.unwrap_or_else(|| home_path(".claude/registry.sqlite"));
let ledger_db = cli.ledger_db
.or_else(|| std::env::var("KEI_LEDGER_DB").ok().map(PathBuf::from))
.unwrap_or_else(|| home_path(".claude/agents/ledger.sqlite"));
let manifests_dir = cli.manifests_dir
.unwrap_or_else(|| home_path("Projects/KeiSeiKit-public/_manifests"));
let cfg = graph::GraphConfig { registry_db, ledger_db, manifests_dir };
let space = graph::build_graph(&cfg)?;
let content = match cli.format.as_str() {
"json" => serde_json::to_string_pretty(&space.data)?,
// window.RUNTIME_SPACE = ... — assigning to global avoids the
// `const RUNTIME_SPACE` re-declaration error when the auto-refresh
// script re-evaluates this file every 5s in the browser.
_ => format!(
"// Auto-generated by kei-graph-export — do not edit.\n\
window.RUNTIME_SPACE = {};\n",
serde_json::to_string(&space)?
),
};
match cli.output {
Some(path) => std::fs::write(path, content)?,
None => print!("{}", content),
}
Ok(())
}