KeiSeiKit-1.0/_primitives/_rust/kei-graph-export/src/graph.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

69 lines
2.2 KiB
Rust

use crate::{edges, nodes};
use crate::types::{Edge, Node, Space, SpaceData};
use anyhow::Result;
use rusqlite::Connection;
use std::collections::HashMap;
use std::path::PathBuf;
pub struct GraphConfig {
pub registry_db: PathBuf,
pub ledger_db: PathBuf,
pub manifests_dir: PathBuf,
}
pub fn build_graph(cfg: &GraphConfig) -> Result<Space> {
let reg = Connection::open(&cfg.registry_db)?;
let led = Connection::open(&cfg.ledger_db)?;
let (mut nodes, block_lookup) = nodes::collect_blocks(&reg)?;
let agents = nodes::collect_agents(&led, &mut nodes)?;
let manifests = nodes::collect_manifests(&cfg.manifests_dir, &mut nodes)?;
nodes::collect_branches(&led, &mut nodes)?;
nodes::collect_skills(&led, &mut nodes)?;
let mut links = Vec::new();
edges::edges_manifest_block(&manifests, &block_lookup, &mut links);
edges::edges_manifest_path_ref(&manifests, &block_lookup, &mut links);
edges::edges_manifest_rule(&manifests, &block_lookup, &mut links);
edges::edges_branch_lineage(&led, &mut links)?;
edges::edges_agent_fork(&agents, &mut links);
edges::edges_skill_invocation(&led, &mut links)?;
edges::edges_agent_manifest(&agents, &manifests, &mut links);
compute_connections(&mut nodes, &links);
Ok(Space {
name: "Runtime",
icon: "activity",
description: "Live KeiSei agent + atom DNA graph",
colors: default_colors(),
data: SpaceData { nodes, links },
})
}
fn compute_connections(nodes: &mut Vec<Node>, links: &[Edge]) {
let mut degree: HashMap<String, usize> = HashMap::new();
for l in links {
*degree.entry(l.source.clone()).or_default() += 1;
*degree.entry(l.target.clone()).or_default() += 1;
}
for n in nodes.iter_mut() {
n.connections = *degree.get(&n.id).unwrap_or(&0);
}
}
fn default_colors() -> HashMap<String, String> {
[
("atom", "#6ee7b7"),
("hook", "#f59e0b"),
("primitive", "#60a5fa"),
("rule", "#c084fc"),
("skill", "#34d399"),
("agent", "#f87171"),
("branch", "#94a3b8"),
("manifest", "#fb923c"),
]
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect()
}