an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions
HTML agent-harnessagent-orchestrationagentsai-agentsautonomous-agentsclaude-codecodexcoding-agentsdesktop-appdeveloper-toolselectrongemini-cliharnessharness-engineeringlocal-firstmemorymulti-agentopencodeorchestrationtypescript
feat(knowledge-graph): v1 vertical slice — ingest, store, agent CLI (flag OFF)
Chaitanya Giri33748d0a766e
diff --git a/electron-builder.yml b/electron-builder.ymlindex 93b1e493..31ae0462 100644--- a/electron-builder.yml+++ b/electron-builder.yml@@ -24,6 +24,13 @@ files:extraResources:- from: resources/md-slack-reply.cjsto: md-slack-reply.cjs+ # Knowledge Graph agent CLI + its pure-JS core. Agents invoke `node+ # <resources>/kg.cjs` out-of-process; kg-core.cjs ships beside it so the CLI's+ # `require('./kg-core.cjs')` resolves outside the asar.+ - from: resources/kg.cjs+ to: kg.cjs+ - from: src/main/kg-core.cjs+ to: kg-core.cjsasarUnpack:- "**/node_modules/node-pty/**"diff --git a/electron.vite.config.ts b/electron.vite.config.tsindex e9459913..e40f9734 100644--- a/electron.vite.config.ts+++ b/electron.vite.config.ts@@ -15,7 +15,11 @@ const define = { __APP_VERSION__: JSON.stringify(pkg.version) };// build, so the sidecar is emitted from a single place for every path.function copyMainSidecars() {const ASSETS: Array<[string, string]> = [- ['src/main/slack-trigger.cjs', 'out/main/slack-trigger.cjs']+ ['src/main/slack-trigger.cjs', 'out/main/slack-trigger.cjs'],+ // Knowledge Graph core: required by knowledge.ts at runtime (pure-JS, no+ // native deps), so it must be emitted next to the main bundle like the+ // Slack sidecar above.+ ['src/main/kg-core.cjs', 'out/main/kg-core.cjs']];return {name: 'copy-main-cjs-sidecars',diff --git a/resources/kg.cjs b/resources/kg.cjsnew file mode 100644index 00000000..30e71d23--- /dev/null+++ b/resources/kg.cjs@@ -0,0 +1,126 @@+#!/usr/bin/env node+'use strict';+/**+ * kg.cjs — the agent-facing Knowledge Graph CLI.+ *+ * A spawned agent queries the enterprise knowledge store by running this via its+ * shell, exactly the way the hive surfaces MemPalace (`mempalace search …`):+ *+ * node "$KG_CLI" search "<query>" [--limit N] [--json]+ * node "$KG_CLI" list [--json]+ * node "$KG_CLI" get <docId>+ *+ * Pure Node (node:fs only via kg-core) — no native modules, so it runs cleanly+ * under a plain `node` outside the Electron app/asar. The main process injects:+ * KG_ROOT — the store directory (required)+ * KG_CORE — absolute path to kg-core.cjs (preferred resolution)+ * See docs/design/knowledge-graph.md and src/main/kg-core.cjs.+ */++const path = require('node:path');++function loadCore() {+ const candidates = [+ process.env.KG_CORE,+ path.join(__dirname, 'kg-core.cjs'), // packaged: beside this file in resources+ path.join(__dirname, '..', 'src', 'main', 'kg-core.cjs'), // dev repo: resources/ → src/main/+ path.join(__dirname, '..', 'main', 'kg-core.cjs'), // built: out/main next to a copied cli+ path.join(__dirname, 'main', 'kg-core.cjs')+ ].filter(Boolean);+ for (const c of candidates) {+ try { return require(c); } catch { /* try next */ }+ }+ fail('knowledge core module (kg-core.cjs) not found');+}++function fail(msg, code = 1) {+ process.stderr.write(`kg: ${msg}\n`);+ process.exit(code);+}++/** Minimal `--flag value` / `--flag=value` / bare-positional argv parser. */+function parseArgs(argv) {+ const positionals = [];+ const flags = {};+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ if (a.startsWith('--')) {+ const eq = a.indexOf('=');+ if (eq !== -1) { flags[a.slice(2, eq)] = a.slice(eq + 1); }+ else if (i + 1 < argv.length && !argv[i + 1].startsWith('--')) { flags[a.slice(2)] = argv[++i]; }+ else { flags[a.slice(2)] = true; }+ } else {+ positionals.push(a);+ }+ }+ return { positionals, flags };+}++function main() {+ const [cmd, ...rest] = process.argv.slice(2);+ const { positionals, flags } = parseArgs(rest);++ const kgRoot = process.env.KG_ROOT;+ if (!kgRoot) fail('Knowledge Graph is not configured (KG_ROOT unset). It is off or unavailable.', 0);++ const core = loadCore();+ const json = flags.json === true || flags.json === 'true';++ switch (cmd) {+ case 'search': {+ const query = positionals.join(' ').trim();+ if (!query) fail('usage: kg search "<query>" [--limit N] [--json]');+ const limit = Number(flags.limit) || 8;+ const results = core.search(kgRoot, query, { limit });+ if (json) { process.stdout.write(JSON.stringify(results, null, 2) + '\n'); return; }+ if (!results.length) { process.stdout.write(`No knowledge matched "${query}".\n`); return; }+ let out = `Knowledge results for "${query}" (${results.length}):\n\n`;+ results.forEach((r, i) => {+ out += `${i + 1}. ${r.title} [${r.modality}] (id: ${r.docId})\n`;+ out += ` source: ${r.source}\n`;+ out += ` ${r.snippet}\n\n`;+ });+ out += 'Use `kg get <id>` for the full document.\n';+ process.stdout.write(out);+ return;+ }+ case 'list': {+ const docs = core.list(kgRoot);+ if (json) { process.stdout.write(JSON.stringify(docs, null, 2) + '\n'); return; }+ if (!docs.length) { process.stdout.write('The knowledge base is empty.\n'); return; }+ let out = `Knowledge base — ${docs.length} document(s):\n\n`;+ for (const d of docs) {+ const tags = (d.tags && d.tags.length) ? ` #${d.tags.join(' #')}` : '';+ out += `• ${d.title} [${d.modality}] (id: ${d.id})${tags}\n`;+ }+ process.stdout.write(out);+ return;+ }+ case 'get': {+ const docId = positionals[0];+ if (!docId) fail('usage: kg get <docId>');+ const doc = core.getDoc(kgRoot, docId);+ if (!doc) fail(`no document with id "${docId}"`, 0);+ if (json) { process.stdout.write(JSON.stringify(doc, null, 2) + '\n'); return; }+ process.stdout.write(`# ${doc.meta.title} [${doc.meta.modality}]\nsource: ${doc.meta.source}\n\n${doc.text}\n`);+ return;+ }+ case 'stats': {+ const s = core.stats(kgRoot);+ process.stdout.write(json ? JSON.stringify(s, null, 2) + '\n'+ : `Knowledge base: ${s.docCount} document(s), ${s.chunkCount} chunk(s).\n`);+ return;+ }+ default:+ process.stdout.write(+ 'Knowledge Graph CLI\n\n'+ + ' kg search "<query>" [--limit N] [--json] ranked passages from the enterprise knowledge base\n'+ + ' kg list [--json] all documents (title, modality, id)\n'+ + ' kg get <docId> [--json] full extracted text of one document\n'+ + ' kg stats [--json] corpus counts\n'+ );+ process.exit(cmd ? 1 : 0);+ }+}++main();diff --git a/src/main/config.ts b/src/main/config.tsindex 8b11c83e..a660830e 100644--- a/src/main/config.ts+++ b/src/main/config.ts@@ -92,6 +92,18 @@ export interface CircuitBreakerConfig {tokenVelocityPerMin?: number;}+/** Enterprise Knowledge Graph (multimodal context store + agent access tool).+ * The user ingests their own documents/images/PDFs; agents query them on demand+ * via the `kg` CLI. Opt-in like the heartbeat/Slack features — `enabled` gates+ * everything (no env injected, no prompt line, no store touched when off). See+ * docs/design/knowledge-graph.md. */+export interface KnowledgeGraphConfig {+ /** Master switch. Default false = zero behaviour change (the feature is dark). */+ enabled?: boolean;+ /** Override the store location. Unset = <userData>/knowledge. */+ rootPath?: string;+}+export interface HarnessConfig {/** Has the user completed the first-run onboarding? */onboardingComplete: boolean;@@ -136,6 +148,8 @@ export interface HarnessConfig {maxTurns?: number;/** Circuit-breaker thresholds (Lane A #6.6b). Unset = conservative defaults. */circuitBreaker?: CircuitBreakerConfig;+ /** Enterprise Knowledge Graph (multimodal context for agents). Default OFF. */+ knowledgeGraph?: KnowledgeGraphConfig;/** Fire native desktop notifications on agent lifecycle events (idle finish / waiting for input). */notifications?: boolean;/** Terminal theme — mirrored into each agent's per-session Claude settings@@ -205,7 +219,9 @@ const DEFAULTS: HarnessConfig = {reflectByteTriggerPct: 50,reflectSectionTrigger: 50,reflectRecentKeep: 12,- reflectMinBytes: 16_384+ reflectMinBytes: 16_384,+ // Enterprise Knowledge Graph — opt-in; dark until the user enables it.+ knowledgeGraph: { enabled: false }};function configPath(): string {diff --git a/src/main/hive.ts b/src/main/hive.tsindex 4c0724bb..a56c7d79 100644--- a/src/main/hive.ts+++ b/src/main/hive.ts@@ -275,7 +275,7 @@ export class HiveManager {* Ensure an agent's workspace + registry entry, returning the spawn injection* (provider-specific args + env) that makes the process hive-aware.*/- ensureAgent(meta: AgentMeta, opts: { semanticMemory?: boolean; theme?: 'light' | 'dark' } = {}): SpawnInjection {+ ensureAgent(meta: AgentMeta, opts: { semanticMemory?: boolean; knowledgeGraph?: boolean; theme?: 'light' | 'dark' } = {}): SpawnInjection {const root = this.root();if (!root) return { args: [], env: {} };this.ensureHive();@@ -338,7 +338,7 @@ export class HiveManager {if (!isHiveAwareProvider(meta.provider)) {const preset = providerPreset(meta.provider ?? 'claude');const flag = preset.initialPromptFlag;- const prompt = this.injectedPrompt(meta, dir, root, opts.semanticMemory ?? false);+ const prompt = this.injectedPrompt(meta, dir, root, opts.semanticMemory ?? false, opts.knowledgeGraph ?? false);// Both agy and codex expose a Claude-style lifecycle-hook surface, so each// gets the SAME live status + Stop→inbox-drain Claude does — selected by the// preset's `hookBridge`. agy needs a translating shim (its hook stdin/stdout@@ -391,7 +391,7 @@ export class HiveManager {const args: string[] = [];if (!claudeProvider) return { args, env };- args.push('--append-system-prompt', this.injectedPrompt(meta, dir, root, opts.semanticMemory ?? false));+ args.push('--append-system-prompt', this.injectedPrompt(meta, dir, root, opts.semanticMemory ?? false, opts.knowledgeGraph ?? false));// Phase 1 — autonomy: attach lifecycle hooks via --settings (no edits to the// user's repo) so the agent reports activity and drains its inbox on Stop.@@ -544,10 +544,16 @@ export class HiveManager {* Volatile context belongs on the live channels — the inbox (hive messages) and* the PTY — never baked into this prefix. (Lane A #6.1.)*/- private injectedPrompt(meta: AgentMeta, dir: string, root: string, semanticMemory: boolean): string {+ private injectedPrompt(meta: AgentMeta, dir: string, root: string, semanticMemory: boolean, knowledgeGraph: boolean): string {const memoryLine = semanticMemory? 'Semantic memory: the whole hive shares a searchable MemPalace at $MEMPALACE_PALACE_PATH. To recall relevant past knowledge across the team, run `mempalace search "<query>"`; run `mempalace wake-up` at the start of a task for a memory digest. Your notes in memory.md are mined into the palace automatically — write durable facts there.': '';+ // Enterprise Knowledge Graph (opt-in). Volatile-free: references only the+ // stable $KG_CLI / $KG_ROOT env vars injected at spawn — no paths/counts that+ // would change per spawn and bust the prompt cache.+ const knowledgeLine = knowledgeGraph+ ? 'Enterprise knowledge: this organisation has a private Knowledge Graph of its own documents, policies, and business context. When a task needs that context — company-specific facts, house style, internal processes — query it instead of guessing: run `node "$KG_CLI" search "<query>"` for ranked passages, `node "$KG_CLI" list` to see what is available, and `node "$KG_CLI" get <id>` for a full document.'+ : '';const godLine = meta.isGod? 'You are the GOD / ORCHESTRATOR of this hive — your job is to ORCHESTRATE, not to implement: maintain live situational awareness and delegate the work. (1) AWARENESS — always know what is going on: keep an accurate picture of every agent (active vs archived/idle), the task board, and all in-flight work; drain your inbox continually and triage every other agent\'s requests, answering clarifications so the team runs autonomously. (2) DELEGATE — decompose work and fan it out to the hive agents via their inboxes (route messages and assign owners; do not do their jobs); do NOT take on grunt implementation yourself. (3) OWN ONLY THE IMPORTANT, high-leverage things — task decomposition, dispatch decisions, sign-offs, conflict resolution, branch integration, and final QA — and remain the sole scribe of board.md. You are otherwise fully autonomous — there is NO separate approval queue. For the genuinely critical (destructive actions, spending real money, scope changes, unresolvable conflicts), ask the human directly in your own session and let the tool-permission prompt gate the action; the human approves natively, including remotely from their phone via /remote-control. Keep the team unblocked. When you DISPATCH a task, write it as a 4-part contract so the agent can run autonomously: (1) OBJECTIVE — the concrete goal; (2) OUTPUT — the expected deliverable/format; (3) TOOLS — what to use or avoid, and any references to read instead of re-deriving; (4) BOUNDARIES — scope limits + the definition of done. Pass references (file paths, message ids, board sections), not pasted content — keep dispatches short.'+ ` MONITOR the floor by reading ${root}/fleet.json (live per-agent tokens, cost, status, last tool, breaker level, inbox backlog) and ${root}/registry.json — note that running 'claude agents' will NOT list your hive's sibling agents. A full Claude Code command reference is at ${root}/COMMANDS.md (slash commands act ONLY on your own session; CLI commands run in your shell and can target the fleet). You periodically receive scheduler / "Heartbeat" standup requests — on each, review every agent via fleet.json, re-engage anyone stalled, over-budget, or breaker-armed, and keep board.md and tasks.json accurate. In tasks.json, ALWAYS set each task's "assignee" to the worker's agent id the moment you dispatch it, and NEVER clear it on status changes — a done card must still say who did the work (the human reads the board by who-did-what). HUMAN FEEDBACK is first-class in the ledger: when a task can only proceed with the human's input — a QUESTION to answer OR an ACTION only the human can perform (create an account, approve a purchase, provide credentials/screenshots, test on their device) — set its status to "blocked" and append the concrete ask to the card's "humanQA" array (push {"q":"...","askedAt":"<iso>"}; phrase actions as clear to-dos; keep every past entry — the history documents the card's decisions). The harness surfaces open questions on the office floor's ASK ME board; the human's answer lands in the same entry ("a") AND arrives as an inbox message to you — read it, act on it, and unblock the card so work continues. Do NOT park human questions in separate files (no HumanQuestion.md) and never sit waiting on the human in your own session. Steward the token budget.`@@ -569,6 +575,7 @@ export class HiveManager {'4. At the END of a task, append what you learned to memory.md so future-you remembers.',guardrailsLine,memoryLine,+ knowledgeLine,godLine,slackLine,`Env vars available to you: AGENT_ID, AGENT_NAME, HIVE_ROOT, AGENT_DIR.`diff --git a/src/main/index.ts b/src/main/index.tsindex 23de3bdd..3326eb81 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -19,6 +19,7 @@ import { HookServer } from './hooks';import { CircuitBreaker, type BreakerInput } from './breaker';import type { UsageProvider } from './usage';import { MemoryManager } from './memory';+import { KnowledgeManager } from './knowledge';import { MemoryReflector, type ReflectSettings } from './reflect';import { PersistStore } from './db';import { readAgentUsage, readContextTokens } from './transcript';@@ -100,6 +101,8 @@ const memory = new MemoryManager(() => readConfig().harnessHome,() => { const c = readConfig(); return { enabled: c.semanticMemory !== false, model: c.embeddingModel ?? 'minilm' }; });+// Enterprise Knowledge Graph — file-backed store + agent CLI (default OFF).+const knowledge = new KnowledgeManager();/** Reads the reflect tunables from config each tick (defaults baked in here so a* pre-existing config.json without the keys still gets sane values). */function reflectSettings(): ReflectSettings {@@ -1248,11 +1251,16 @@ ipcMain.handle('pty:spawn', async (_evt, opts: SpawnOptions & { hive?: AgentMetatry {const inj = hive.ensureAgent({ ...opts.hive, cwd: opts.cwd, provider },- { semanticMemory: memory.active(), theme: readConfig().terminalTheme ?? 'light' }+ {+ semanticMemory: memory.active(),+ knowledgeGraph: knowledge.active(),+ theme: readConfig().terminalTheme ?? 'light'+ });opts.args = [...(opts.args ?? []), ...inj.args];- // Point the agent's mempalace CLI at the shared palace (no-op if inactive).- opts.env = { ...(opts.env ?? {}), ...inj.env, ...memory.env() };+ // Point the agent's mempalace CLI at the shared palace + the `kg` CLI at the+ // enterprise knowledge store (both no-ops / empty when their flags are off).+ opts.env = { ...(opts.env ?? {}), ...inj.env, ...memory.env(), ...knowledge.env() };} catch (e) {// Hive provisioning is best-effort; never block a spawn on it.console.error('[hive] ensureAgent failed:', e);@@ -1528,6 +1536,53 @@ ipcMain.handle('hive:mineNow', () => { memory.mineNow(); return { ok: true }; })ipcMain.handle('memory:reflectNow', (_evt, id: unknown) =>reflector.reflectNow(typeof id === 'string' && id ? id : undefined));+// ─── IPC: enterprise Knowledge Graph (multimodal context for agents) ─────────+ipcMain.handle('kg:status', () => knowledge.status());+ipcMain.handle('kg:list', () => knowledge.list());+ipcMain.handle('kg:search', (_evt, query: unknown, limit: unknown) => {+ if (typeof query !== 'string' || !query.trim()) return [];+ return knowledge.search(query, typeof limit === 'number' ? limit : undefined);+});+ipcMain.handle('kg:get', (_evt, id: unknown) =>+ (typeof id === 'string' && id ? knowledge.get(id) : null));+ipcMain.handle('kg:remove', (_evt, id: unknown) =>+ ({ ok: typeof id === 'string' && id ? knowledge.remove(id) : false }));+// Ingest one or more files from disk. Best-effort per file; returns per-file+// results so the UI can report partial success.+ipcMain.handle('kg:ingestFiles', (_evt, payload: unknown) => {+ const p = (payload ?? {}) as { paths?: unknown; tags?: unknown };+ const paths = Array.isArray(p.paths) ? p.paths.filter((x): x is string => typeof x === 'string') : [];+ const tags = Array.isArray(p.tags) ? p.tags.filter((x): x is string => typeof x === 'string') : undefined;+ const results = paths.map((srcPath) => {+ try {+ const r = knowledge.ingestFile(srcPath, { tags });+ return { ok: true as const, srcPath, docId: r.docId, chunkCount: r.chunkCount };+ } catch (e) {+ return { ok: false as const, srcPath, error: e instanceof Error ? e.message : String(e) };+ }+ });+ return { results };+});+// Open a multi-file picker and ingest the chosen artifacts in one round-trip.+ipcMain.handle('kg:addFiles', async (evt) => {+ const win = BrowserWindow.fromWebContents(evt.sender);+ if (!win) return { ok: false as const, error: 'no window' };+ const res = await dialog.showOpenDialog(win, {+ properties: ['openFile', 'multiSelections'],+ title: 'Add documents to the Knowledge Graph'+ });+ if (res.canceled || res.filePaths.length === 0) return { ok: false as const, error: 'cancelled' };+ const results = res.filePaths.map((srcPath) => {+ try {+ const r = knowledge.ingestFile(srcPath);+ return { ok: true as const, srcPath, docId: r.docId, chunkCount: r.chunkCount };+ } catch (e) {+ return { ok: false as const, srcPath, error: e instanceof Error ? e.message : String(e) };+ }+ });+ return { ok: true as const, results };+});+// ─── IPC: command history (SQLite — every prompt submitted to an agent) ──────ipcMain.handle('history:add', (_evt, payload: unknown) => {const p = (payload ?? {}) as { agentId?: unknown; cwd?: unknown; text?: unknown };diff --git a/src/main/kg-core.cjs b/src/main/kg-core.cjsnew file mode 100644index 00000000..84a5d859--- /dev/null+++ b/src/main/kg-core.cjs@@ -0,0 +1,359 @@+'use strict';+/**+ * kg-core.cjs — the Knowledge Graph core: ingest, index, and keyword-search a+ * local, file-backed enterprise knowledge store. PURE JS (only node:fs / path /+ * crypto) so it loads under BOTH the Electron main process AND a plain `node`+ * invocation from a spawned agent's shell — the same robustness reason+ * `slack-trigger.cjs` / `md-slack-reply.cjs` avoid the native better-sqlite3+ * module. See docs/design/knowledge-graph.md.+ *+ * Store layout (rooted at KG_ROOT, default <userData>/knowledge):+ * index.jsonl one JSON line per CHUNK (the search index)+ * docs/<docId>/+ * meta.json artifact metadata+ * original.<ext> raw artifact, copied verbatim (images/PDFs/binaries)+ * text.md full extracted/normalized searchable text+ *+ * Consumed by: src/main/knowledge.ts (in-app), resources/kg.cjs (agent CLI),+ * and test/kg-core.test.cjs — one implementation, three callers.+ */++const fs = require('node:fs');+const path = require('node:path');+const crypto = require('node:crypto');+const { spawnSync } = require('node:child_process');++// ─── Tunables ────────────────────────────────────────────────────────────────+const DEFAULT_CHUNK_SIZE = 1200; // chars per chunk (approx; broken on boundaries)+const DEFAULT_CHUNK_OVERLAP = 150; // chars of overlap between adjacent chunks+const MAX_INDEX_BYTES = 5 * 1024 * 1024; // per-doc text indexed before truncation+const DEFAULT_SEARCH_LIMIT = 8;+const SNIPPET_RADIUS = 160; // chars of context on each side of a match++// Tiny English stop-list — enough to stop the most common words from dominating+// term-frequency scores without pulling in an NLP dependency.+const STOPWORDS = new Set(+ ('a an and are as at be but by for from has have how in is it its of on or '+ + 'that the their this to was were what when where which who will with your '+ + 'you we our us they them he she his her i me my do does did not can could '+ + 'would should about into over than then there here so if no yes').split(' ')+);++const IMAGE_EXTS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'bmp', 'tif', 'tiff', 'heic']);+const CODE_EXTS = new Set(['ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'py', 'go', 'rs', 'java', 'rb',+ 'c', 'h', 'cc', 'cpp', 'hpp', 'cs', 'php', 'swift', 'kt', 'scala', 'sh', 'bash', 'zsh', 'sql']);+const SHEET_EXTS = new Set(['csv', 'tsv']);+const TEXT_EXTS = new Set(['md', 'markdown', 'mdx', 'txt', 'text', 'rst', 'json', 'jsonl',+ 'yaml', 'yml', 'toml', 'ini', 'log', 'html', 'htm', 'css', 'xml', 'env']);++const MIME_BY_EXT = {+ md: 'text/markdown', markdown: 'text/markdown', txt: 'text/plain', json: 'application/json',+ csv: 'text/csv', tsv: 'text/tab-separated-values', yaml: 'application/yaml', yml: 'application/yaml',+ html: 'text/html', htm: 'text/html', pdf: 'application/pdf', png: 'image/png', jpg: 'image/jpeg',+ jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', svg: 'image/svg+xml'+};++// ─── Small helpers ───────────────────────────────────────────────────────────+function genId() { return crypto.randomBytes(8).toString('hex'); }+function extOf(p) { return path.extname(String(p || '')).replace(/^\./, '').toLowerCase(); }+function mimeFor(p) { return MIME_BY_EXT[extOf(p)] || 'application/octet-stream'; }+function ensureDir(d) { fs.mkdirSync(d, { recursive: true }); }+function nowIso() { return new Date().toISOString(); }++function clampLimit(n, fallback) {+ const v = Math.floor(Number(n));+ if (!Number.isFinite(v) || v <= 0) return fallback;+ return Math.min(100, v);+}++/** Map a file (by extension) to a coarse modality bucket. */+function detectModality(filePath) {+ const e = extOf(filePath);+ if (IMAGE_EXTS.has(e)) return 'image';+ if (e === 'pdf') return 'pdf';+ if (SHEET_EXTS.has(e)) return 'sheet';+ if (CODE_EXTS.has(e)) return 'code';+ if (TEXT_EXTS.has(e)) return 'text';+ return 'text'; // unknown → best-effort treat as text+}++/** Lowercase alphanumeric tokens, stop-words and 1-char tokens dropped. */+function tokenize(s) {+ const m = String(s || '').toLowerCase().match(/[a-z0-9]+/g);+ if (!m) return [];+ return m.filter((t) => t.length > 1 && !STOPWORDS.has(t));+}++/** First markdown heading or first non-empty line, trimmed and length-capped. */+function deriveTitle(text) {+ const lines = String(text || '').split('\n');+ for (const raw of lines) {+ const line = raw.trim();+ if (!line) continue;+ const h = line.replace(/^#+\s*/, '').trim();+ return h.length > 80 ? h.slice(0, 80) + '…' : h;+ }+ return '';+}++/**+ * Split text into ~size-char chunks, preferring to break on paragraph / line /+ * word boundaries, with `overlap` chars carried into the next chunk so a passage+ * straddling a boundary is still findable. Deterministic; always terminates.+ */+function chunkText(text, opts = {}) {+ const size = Math.max(200, opts.size ?? DEFAULT_CHUNK_SIZE);+ const overlap = Math.min(opts.overlap ?? DEFAULT_CHUNK_OVERLAP, Math.floor(size / 2));+ const t = String(text || '').replace(/\r\n/g, '\n').trim();+ if (!t) return [];+ if (t.length <= size) return [t];+ const chunks = [];+ let i = 0;+ while (i < t.length) {+ let end = Math.min(i + size, t.length);+ if (end < t.length) {+ const window = t.slice(i, end);+ const br = Math.max(window.lastIndexOf('\n\n'), window.lastIndexOf('\n'), window.lastIndexOf(' '));+ if (br > size * 0.6) end = i + br; // only break late, never near the start+ }+ const piece = t.slice(i, end).trim();+ if (piece) chunks.push(piece);+ if (end >= t.length) break;+ i = Math.max(end - overlap, i + 1);+ }+ return chunks;+}++/**+ * Score one index record against the query. Term-frequency (log-damped) over+ * distinct query terms, a title-match boost, a distinct-term coverage bonus, and+ * an exact-phrase bonus. Returns 0 when no query term appears.+ */+function scoreChunk(rec, queryTerms, queryRaw) {+ if (!queryTerms.length) return 0;+ const text = String(rec.text || '');+ const titleLc = String(rec.title || '').toLowerCase();+ const tf = Object.create(null);+ for (const tok of tokenize(text)) tf[tok] = (tf[tok] || 0) + 1;+ let score = 0;+ let matched = 0;+ for (const term of queryTerms) {+ const c = tf[term] || 0;+ if (c > 0) { matched++; score += 1 + Math.log(1 + c); }+ if (titleLc.includes(term)) score += 2;+ }+ if (matched === 0) return 0;+ score += matched * 0.5; // reward breadth of distinct matches+ const q = String(queryRaw || '').trim().toLowerCase();+ if (q.length >= 3 && text.toLowerCase().includes(q)) score += 5; // exact phrase+ return score;+}++/** A short snippet of `text` centred on the first query-term hit. */+function makeSnippet(text, queryTerms) {+ const t = String(text || '').replace(/\s+/g, ' ').trim();+ if (!t) return '';+ const lc = t.toLowerCase();+ let at = -1;+ for (const term of queryTerms) {+ const idx = lc.indexOf(term);+ if (idx !== -1 && (at === -1 || idx < at)) at = idx;+ }+ if (at === -1) return t.length > SNIPPET_RADIUS * 2 ? t.slice(0, SNIPPET_RADIUS * 2) + '…' : t;+ const start = Math.max(0, at - SNIPPET_RADIUS);+ const end = Math.min(t.length, at + SNIPPET_RADIUS);+ return (start > 0 ? '…' : '') + t.slice(start, end).trim() + (end < t.length ? '…' : '');+}++// ─── Extraction (per modality) ───────────────────────────────────────────────+/**+ * Turn an artifact into searchable text. Returns { text, title, extractor, mime }.+ * v1 covers text-family (verbatim) and images (metadata-level); PDF is a+ * best-effort poppler hook; everything else is treated as text.+ */+function extractText(input) {+ const { srcPath, inlineText, modality, title, caption, tags, source } = input;++ if (typeof inlineText === 'string' && inlineText.length) {+ return { text: inlineText, title: title || deriveTitle(inlineText) || source, extractor: 'inline@1', mime: 'text/plain' };+ }++ if (modality === 'image') {+ // No OCR in v1: the searchable surface is the user-supplied metadata + filename.+ // The original bytes are retained (by ingest) for a future vision/OCR pass.+ const parts = [title, caption, ...(tags || []), source].filter(Boolean);+ return { text: parts.join('\n'), title: title || source, extractor: 'image-meta@1', mime: mimeFor(srcPath) };+ }++ if (modality === 'pdf') {+ const out = tryPdfToText(srcPath);+ if (out != null && out.trim()) {+ return { text: out, title: title || deriveTitle(out) || source, extractor: 'pdftotext@1', mime: 'application/pdf' };+ }+ // poppler absent → store metadata now; a later pass can enrich from the original.+ const parts = [title, caption, ...(tags || []), source].filter(Boolean);+ return { text: parts.join('\n'), title: title || source, extractor: 'pdf-pending@1', mime: 'application/pdf' };+ }++ // text / code / sheet — read UTF-8 verbatim.+ if (srcPath && fs.existsSync(srcPath)) {+ let raw = '';+ try { raw = fs.readFileSync(srcPath, 'utf8'); } catch { raw = ''; }+ return { text: raw, title: title || deriveTitle(raw) || source, extractor: 'text-utf8@1', mime: mimeFor(srcPath) };+ }++ return { text: inlineText || '', title: title || source || 'untitled', extractor: 'empty@1', mime: 'text/plain' };+}++/** Best-effort PDF → text via poppler's `pdftotext` if it's on PATH; else null. */+function tryPdfToText(srcPath) {+ if (!srcPath || !fs.existsSync(srcPath)) return null;+ try {+ const res = spawnSync('pdftotext', ['-q', srcPath, '-'], { encoding: 'utf8', timeout: 20000, maxBuffer: 32 * 1024 * 1024 });+ if (res.status === 0 && typeof res.stdout === 'string') return res.stdout;+ } catch { /* pdftotext not installed */ }+ return null;+}++// ─── Store operations ────────────────────────────────────────────────────────+/**+ * Ingest one artifact into the store at `kgRoot`.+ * input: { srcPath?, inlineText?/text?, title?, tags?, caption?, modality?, source?, id? }+ * Returns { docId, chunkCount, meta }.+ */+function ingest(kgRoot, input = {}) {+ ensureDir(kgRoot);+ ensureDir(path.join(kgRoot, 'docs'));++ const docId = input.id || genId();+ const docDir = path.join(kgRoot, 'docs', docId);+ ensureDir(docDir);++ const srcPath = input.srcPath || null;+ const inlineText = input.text != null ? input.text : input.inlineText;+ const source = input.source || (srcPath ? path.basename(srcPath) : (input.title || 'untitled'));+ const modality = input.modality || (srcPath ? detectModality(srcPath) : 'text');+ const origExt = srcPath ? (extOf(srcPath) || 'bin') : 'txt';+ const tags = Array.isArray(input.tags) ? input.tags.map(String) : [];++ // Copy the raw artifact verbatim (lossless record for future re-extraction).+ let bytes = 0;+ if (srcPath && fs.existsSync(srcPath)) {+ try {+ bytes = fs.statSync(srcPath).size;+ fs.copyFileSync(srcPath, path.join(docDir, 'original.' + origExt));+ } catch { /* best-effort copy */ }+ }++ const ex = extractText({ srcPath, inlineText, modality, title: input.title, caption: input.caption, tags, source });+ const fullText = String(ex.text || '');+ fs.writeFileSync(path.join(docDir, 'text.md'), fullText, 'utf8');++ let indexText = fullText;+ let truncated = false;+ if (indexText.length > MAX_INDEX_BYTES) { indexText = indexText.slice(0, MAX_INDEX_BYTES); truncated = true; }++ const title = input.title || ex.title || source;+ let chunks = chunkText(indexText);+ if (chunks.length === 0) chunks = [String(title)]; // images/empties: index the title so it's findable++ const lines = chunks.map((c, i) => JSON.stringify({ docId, title, source, modality, chunkIdx: i, text: c }));+ fs.appendFileSync(path.join(kgRoot, 'index.jsonl'), lines.join('\n') + '\n', 'utf8');++ const meta = {+ id: docId, title, source, modality, mime: ex.mime || null, origExt,+ bytes, tags, caption: input.caption || null, chunkCount: chunks.length,+ addedAt: nowIso(), extractor: ex.extractor, truncated+ };+ fs.writeFileSync(path.join(docDir, 'meta.json'), JSON.stringify(meta, null, 2), 'utf8');++ return { docId, chunkCount: chunks.length, meta };+}++/** Keyword-search the index. Returns ranked { docId, title, source, modality, chunkIdx, score, snippet }. */+function search(kgRoot, query, opts = {}) {+ const limit = clampLimit(opts.limit, DEFAULT_SEARCH_LIMIT);+ const queryTerms = tokenize(query);+ if (!queryTerms.length) return [];+ const idxPath = path.join(kgRoot, 'index.jsonl');+ if (!fs.existsSync(idxPath)) return [];++ const scored = [];+ const lines = fs.readFileSync(idxPath, 'utf8').split('\n');+ for (const line of lines) {+ const s = line.trim();+ if (!s) continue;+ let rec;+ try { rec = JSON.parse(s); } catch { continue; }+ const sc = scoreChunk(rec, queryTerms, query);+ if (sc > 0) scored.push({ rec, score: sc });+ }+ scored.sort((a, b) =>+ b.score - a.score+ || String(a.rec.docId).localeCompare(String(b.rec.docId))+ || (a.rec.chunkIdx - b.rec.chunkIdx));++ return scored.slice(0, limit).map(({ rec, score }) => ({+ docId: rec.docId, title: rec.title, source: rec.source, modality: rec.modality,+ chunkIdx: rec.chunkIdx, score: Math.round(score * 1000) / 1000,+ snippet: makeSnippet(rec.text, queryTerms)+ }));+}++/** All artifacts' metadata, newest first. */+function list(kgRoot) {+ const docsDir = path.join(kgRoot, 'docs');+ if (!fs.existsSync(docsDir)) return [];+ const out = [];+ for (const id of fs.readdirSync(docsDir)) {+ try { out.push(JSON.parse(fs.readFileSync(path.join(docsDir, id, 'meta.json'), 'utf8'))); } catch { /* skip */ }+ }+ return out.sort((a, b) => String(b.addedAt || '').localeCompare(String(a.addedAt || '')));+}++/** Full record for one artifact: { meta, text } or null. */+function getDoc(kgRoot, docId) {+ const docDir = path.join(kgRoot, 'docs', String(docId || ''));+ if (!docId || !fs.existsSync(docDir)) return null;+ let meta = null;+ try { meta = JSON.parse(fs.readFileSync(path.join(docDir, 'meta.json'), 'utf8')); } catch { /* none */ }+ if (!meta) return null;+ let text = '';+ try { text = fs.readFileSync(path.join(docDir, 'text.md'), 'utf8'); } catch { /* none */ }+ return { meta, text };+}++/** Delete one artifact's folder and drop its lines from the index. */+function removeDoc(kgRoot, docId) {+ const docDir = path.join(kgRoot, 'docs', String(docId || ''));+ if (!docId || !fs.existsSync(docDir)) return false;+ fs.rmSync(docDir, { recursive: true, force: true });+ const idxPath = path.join(kgRoot, 'index.jsonl');+ if (fs.existsSync(idxPath)) {+ const kept = fs.readFileSync(idxPath, 'utf8').split('\n').filter((line) => {+ const s = line.trim();+ if (!s) return false;+ try { return JSON.parse(s).docId !== docId; } catch { return false; }+ });+ fs.writeFileSync(idxPath, kept.length ? kept.join('\n') + '\n' : '', 'utf8');+ }+ return true;+}++/** Corpus counts for the UI/CLI status line. */+function stats(kgRoot) {+ const docs = list(kgRoot);+ let chunkCount = 0;+ const byModality = Object.create(null);+ for (const d of docs) {+ chunkCount += d.chunkCount || 0;+ byModality[d.modality] = (byModality[d.modality] || 0) + 1;+ }+ return { docCount: docs.length, chunkCount, byModality };+}++module.exports = {+ ingest, search, list, getDoc, removeDoc, stats,+ detectModality, extractText, chunkText, tokenize, scoreChunk, makeSnippet, deriveTitle,+ DEFAULT_CHUNK_SIZE, DEFAULT_CHUNK_OVERLAP+};diff --git a/src/main/knowledge.ts b/src/main/knowledge.tsnew file mode 100644index 00000000..696f7099--- /dev/null+++ b/src/main/knowledge.ts@@ -0,0 +1,122 @@+/**+ * KnowledgeManager — the Electron-main façade over the file-backed enterprise+ * Knowledge Graph store. Owns ingestion (in-app, over IPC) and exposes the same+ * keyword search the agent CLI uses; agents themselves query out-of-process via+ * `resources/kg.cjs` (see docs/design/knowledge-graph.md).+ *+ * All heavy lifting lives in the pure-JS `kg-core.cjs` sidecar (no native deps),+ * required the same way `slack.ts` requires `slack-trigger.cjs`. Mirrors the+ * MemoryManager surface (`active()` / `env()` / `status()`) so it slots into the+ * existing spawn-injection flow.+ */+import { app } from 'electron';+import { existsSync } from 'node:fs';+import { join } from 'node:path';+import { readConfig } from './config';++// Pure-JS core, copied to out/main at build (like slack-trigger.cjs) and shipped+// to process.resourcesPath for the agent CLI (electron-builder extraResources).+// eslint-disable-next-line @typescript-eslint/no-var-requires+const core = require('./kg-core.cjs') as KgCore;++interface KgMeta {+ id: string; title: string; source: string; modality: string; mime: string | null;+ origExt: string; bytes: number; tags: string[]; caption: string | null;+ chunkCount: number; addedAt: string; extractor: string; truncated: boolean;+}+interface KgHit {+ docId: string; title: string; source: string; modality: string;+ chunkIdx: number; score: number; snippet: string;+}+interface KgIngestInput {+ srcPath?: string; text?: string; title?: string; tags?: string[];+ caption?: string; modality?: string; source?: string;+}+interface KgCore {+ ingest(root: string, input: KgIngestInput): { docId: string; chunkCount: number; meta: KgMeta };+ search(root: string, query: string, opts?: { limit?: number }): KgHit[];+ list(root: string): KgMeta[];+ getDoc(root: string, docId: string): { meta: KgMeta; text: string } | null;+ removeDoc(root: string, docId: string): boolean;+ stats(root: string): { docCount: number; chunkCount: number; byModality: Record<string, number> };+}++export interface KnowledgeStatus {+ enabled: boolean;+ root: string;+ docCount: number;+ chunkCount: number;+ byModality: Record<string, number>;+}++export class KnowledgeManager {+ /** Whether the feature flag is on. */+ active(): boolean {+ return readConfig().knowledgeGraph?.enabled === true;+ }++ /** The store directory (config override or <userData>/knowledge). */+ root(): string {+ const override = readConfig().knowledgeGraph?.rootPath;+ if (override && override.trim()) return override;+ return join(app.getPath('userData'), 'knowledge');+ }++ /** Absolute path to the agent CLI (dev: repo resources/; packaged: resourcesPath). */+ private cliPath(): string {+ return app.isPackaged+ ? join(process.resourcesPath, 'kg.cjs')+ : join(app.getAppPath(), 'resources', 'kg.cjs');+ }++ /** Absolute path to the pure-JS core for the out-of-process CLI to require. */+ private corePath(): string {+ return app.isPackaged+ ? join(process.resourcesPath, 'kg-core.cjs')+ : join(app.getAppPath(), 'src', 'main', 'kg-core.cjs');+ }++ /** Env merged into each agent's spawn so its `kg` CLI hits this store. Empty+ * when off — so a default install injects nothing (zero behaviour change). */+ env(): Record<string, string> {+ if (!this.active()) return {};+ return { KG_ROOT: this.root(), KG_CLI: this.cliPath(), KG_CORE: this.corePath() };+ }++ status(): KnowledgeStatus {+ const enabled = this.active();+ const root = this.root();+ const s = enabled && existsSync(root)+ ? core.stats(root)+ : { docCount: 0, chunkCount: 0, byModality: {} };+ return { enabled, root, docCount: s.docCount, chunkCount: s.chunkCount, byModality: s.byModality };+ }++ /** Ingest a file from disk. No-op-safe when off (callers gate on status). */+ ingestFile(srcPath: string, opts: { title?: string; tags?: string[]; caption?: string } = {}) {+ return core.ingest(this.root(), { srcPath, ...opts });+ }++ /** Ingest inline text (e.g. pasted content). */+ ingestText(text: string, opts: { title?: string; tags?: string[] } = {}) {+ return core.ingest(this.root(), { text, ...opts });+ }++ search(query: string, limit?: number): KgHit[] {+ if (!existsSync(this.root())) return [];+ return core.search(this.root(), query, { limit });+ }++ list(): KgMeta[] {+ if (!existsSync(this.root())) return [];+ return core.list(this.root());+ }++ get(docId: string): { meta: KgMeta; text: string } | null {+ return core.getDoc(this.root(), docId);+ }++ remove(docId: string): boolean {+ return core.removeDoc(this.root(), docId);+ }+}diff --git a/src/preload/index.ts b/src/preload/index.tsindex df3c33c2..778afff5 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -133,6 +133,11 @@ export interface ScheduledMission {}/** Circuit-breaker thresholds (Lane A #6.6b). Mirrors src/main/config.ts. */+export interface KnowledgeGraphConfig {+ enabled?: boolean;+ rootPath?: string;+}+export interface CircuitBreakerConfig {enabled?: boolean;hardStop?: boolean;@@ -167,6 +172,8 @@ export interface HarnessConfig {agentTokenCaps?: Record<string, number>;maxTurns?: number;circuitBreaker?: CircuitBreakerConfig;+ /** Enterprise Knowledge Graph (multimodal context for agents). Default OFF. */+ knowledgeGraph?: KnowledgeGraphConfig;/** Terminal theme, mirrored into each agent's per-session Claude settings. */terminalTheme?: 'light' | 'dark';}@@ -181,6 +188,44 @@ export interface MemoryStatus {bin: string | null;}+/** Enterprise Knowledge Graph — corpus status, one document, and a search hit. */+export interface KnowledgeStatus {+ enabled: boolean;+ root: string;+ docCount: number;+ chunkCount: number;+ byModality: Record<string, number>;+}+export interface KnowledgeDoc {+ id: string;+ title: string;+ source: string;+ modality: string;+ mime: string | null;+ origExt: string;+ bytes: number;+ tags: string[];+ caption: string | null;+ chunkCount: number;+ addedAt: string;+ extractor: string;+ truncated: boolean;+}+export interface KnowledgeHit {+ docId: string;+ title: string;+ source: string;+ modality: string;+ chunkIdx: number;+ score: number;+ snippet: string;+}+export interface KnowledgeIngestResult {+ ok: boolean;+ results: Array<{ ok: boolean; srcPath: string; docId?: string; chunkCount?: number; error?: string }>;+ error?: string;+}+export interface DirEntry {name: string;isDir: boolean;@@ -403,6 +448,20 @@ const api = {reflectNow: (id?: string): Promise<Array<{ id: string; condensed: boolean; reason: string; oldBytes?: number; newBytes?: number }>> =>ipcRenderer.invoke('memory:reflectNow', id),+ // ─── Enterprise Knowledge Graph (multimodal context for agents) ───────────+ kgStatus: (): Promise<KnowledgeStatus> => ipcRenderer.invoke('kg:status'),+ kgList: (): Promise<KnowledgeDoc[]> => ipcRenderer.invoke('kg:list'),+ kgSearch: (query: string, limit?: number): Promise<KnowledgeHit[]> =>+ ipcRenderer.invoke('kg:search', query, limit),+ kgGet: (id: string): Promise<{ meta: KnowledgeDoc; text: string } | null> =>+ ipcRenderer.invoke('kg:get', id),+ kgRemove: (id: string): Promise<{ ok: boolean }> => ipcRenderer.invoke('kg:remove', id),+ /** Open an OS file picker and ingest the chosen artifacts in one round-trip. */+ kgAddFiles: (): Promise<KnowledgeIngestResult> => ipcRenderer.invoke('kg:addFiles'),+ /** Ingest explicit file paths (e.g. drag-and-drop). */+ kgIngestFiles: (paths: string[], tags?: string[]): Promise<KnowledgeIngestResult> =>+ ipcRenderer.invoke('kg:ingestFiles', { paths, tags }),+// ─── Command history (SQLite — every prompt submitted to an agent) ─────────/** Record one submitted prompt. Fire-and-forget from the prompt-detection hook. */historyAdd: (entry: { agentId: string; cwd?: string; text: string }): Promise<{ ok: boolean; error?: string }> =>diff --git a/src/renderer/src/components/SettingsModal.tsx b/src/renderer/src/components/SettingsModal.tsxindex 8d5533bc..ea63624b 100644--- a/src/renderer/src/components/SettingsModal.tsx+++ b/src/renderer/src/components/SettingsModal.tsx@@ -193,6 +193,41 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {const [showWebhookSecret, setShowWebhookSecret] = useState(false);const [showWebhookHelp, setShowWebhookHelp] = useState(false);+ // ─── Knowledge Graph (enterprise multimodal context for agents) ───────────+ const [kgEnabled, setKgEnabled] = useState<boolean>(+ (config as HarnessConfig & { knowledgeGraph?: { enabled?: boolean } }).knowledgeGraph?.enabled === true+ );+ const [kgDocCount, setKgDocCount] = useState(0);+ const [kgBusy, setKgBusy] = useState(false);+ const [kgNote, setKgNote] = useState('');++ const refreshKgStatus = async () => {+ try { const s = await window.cth.kgStatus(); setKgDocCount(s.docCount); }+ catch { /* status unavailable */ }+ };++ const toggleKg = async () => {+ const next = !kgEnabled;+ setKgEnabled(next);+ try {+ await window.cth.updateConfig({ knowledgeGraph: { enabled: next } });+ if (next) await refreshKgStatus();+ } catch { setKgEnabled(!next); }+ };++ const addKgFiles = async () => {+ setKgBusy(true); setKgNote('');+ try {+ const res = await window.cth.kgAddFiles();+ if (!res.ok) { setKgNote(res.error === 'cancelled' ? '' : (res.error ?? 'failed')); return; }+ const added = res.results.filter((r) => r.ok).length;+ const failed = res.results.length - added;+ setKgNote(`added ${added} document${added === 1 ? '' : 's'}${failed ? `, ${failed} failed` : ''}`);+ await refreshKgStatus();+ } catch (e) { setKgNote(e instanceof Error ? e.message : String(e)); }+ finally { setKgBusy(false); }+ };+// Re-seed every editable field from the on-disk config when the modal opens.// App's `config` prop is loaded once and never refreshed after a save, so// without this the saved budget / velocity / slack values show blank on reopen.@@ -212,7 +247,11 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {setWebhookEnabled(cc.webhookEnabled ?? false);setWebhookSecret(cc.webhookSecret ?? '');setWebhookPort(String(cc.webhookPort ?? 3849));+ const kgOn = (cc as { knowledgeGraph?: { enabled?: boolean } }).knowledgeGraph?.enabled === true;+ setKgEnabled(kgOn);}).catch(() => { /* keep prop-seeded values */ });+ window.cth.kgStatus().then((s) => { if (alive) setKgDocCount(s.docCount); })+ .catch(() => { /* status unavailable */ });// Hydrate live connection state + the persisted Request URL: the// tunnel URL lives in main, so reopening Settings while connected re-shows it.window.cth.slackStatus().then((s) => {@@ -660,6 +699,46 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {</div></div></div>++ <div style={{ height: 1, background: 'var(--cth-ink-300)' }} />++ {/* Knowledge Graph — enterprise multimodal context for agents */}+ <div>+ <div style={{+ fontFamily: 'var(--cth-font-display)', fontSize: 8, lineHeight: '12px',+ color: 'var(--cth-ink-500)', textTransform: 'uppercase', marginBottom: 10+ }}>+ Knowledge Graph+ </div>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>+ <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>+ <span style={{ fontSize: 14, lineHeight: '20px', color: 'var(--cth-ink-900)' }}>+ Enterprise knowledge base+ </span>+ <span style={{ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-500)' }}>+ Add your docs, images & PDFs; agents query them on demand via the <code>kg</code> tool.+ </span>+ </div>+ <PixelButton+ variant={kgEnabled ? 'primary' : 'secondary'}+ size="sm"+ onClick={toggleKg}+ >+ {kgEnabled ? 'on' : 'off'}+ </PixelButton>+ </div>+ {kgEnabled && (+ <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 10 }}>+ <PixelButton variant="secondary" size="sm" onClick={addKgFiles} disabled={kgBusy}>+ {kgBusy ? 'adding…' : 'add files…'}+ </PixelButton>+ <span style={{ fontSize: 12, color: 'var(--cth-ink-500)' }}>+ {kgDocCount} document{kgDocCount === 1 ? '' : 's'} indexed+ </span>+ {kgNote && <span style={{ fontSize: 12, color: 'var(--cth-mint)' }}>{kgNote}</span>}+ </div>+ )}+ </div></>)}diff --git a/src/renderer/src/store/config.ts b/src/renderer/src/store/config.tsindex bac031f1..1d6a4d6d 100644--- a/src/renderer/src/store/config.ts+++ b/src/renderer/src/store/config.ts@@ -39,6 +39,12 @@ export interface CircuitBreakerConfig {tokenVelocityPerMin?: number;}+/** Enterprise Knowledge Graph config (mirrors src/main/config.ts KnowledgeGraphConfig). */+export interface KnowledgeGraphConfig {+ enabled?: boolean;+ rootPath?: string;+}+export interface HarnessConfig {onboardingComplete: boolean;harnessHome: string | null;@@ -66,6 +72,8 @@ export interface HarnessConfig {agentTokenCaps?: Record<string, number>;maxTurns?: number;circuitBreaker?: CircuitBreakerConfig;+ /** Enterprise Knowledge Graph (multimodal context for agents). Default OFF. */+ knowledgeGraph?: KnowledgeGraphConfig;}/** The Sonnet model with the 1M-token context window — used for Michael's prepdiff --git a/test/kg-core.test.cjs b/test/kg-core.test.cjsnew file mode 100644index 00000000..eec0b254--- /dev/null+++ b/test/kg-core.test.cjs@@ -0,0 +1,204 @@+'use strict';+/**+ * Knowledge Graph core + agent-CLI tests. Self-contained, no test framework —+ * run with `node test/kg-core.test.cjs` (mirrors test/slack.test.cjs).+ * Exercises: tokenize/chunk/score, the ingest→store→search round-trip for the+ * two v1 modalities (text + image), list/get/remove, and the real `kg.cjs` CLI+ * an agent invokes (proving the out-of-process retrieval path end to end).+ */++const assert = require('node:assert');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { spawnSync } = require('node:child_process');++const kg = require('../src/main/kg-core.cjs');+const CLI = path.join(__dirname, '..', 'resources', 'kg.cjs');++let failures = 0;+function test(name, fn) {+ try { fn(); console.log(` ✓ ${name}`); }+ catch (err) { failures++; console.log(` ✗ ${name}\n ${err && err.message}`); }+}++function tmpRoot() {+ return fs.mkdtempSync(path.join(os.tmpdir(), 'kg-test-'));+}+function writeFixture(dir, name, content) {+ const p = path.join(dir, name);+ fs.writeFileSync(p, content, 'utf8');+ return p;+}++(async () => {+ console.log('knowledge-graph core tests');++ // ─── tokenize ───────────────────────────────────────────────────────────+ test('tokenize lowercases, splits on non-alphanumerics, drops stop-words and 1-char tokens', () => {+ const toks = kg.tokenize('The Refund-Policy is X, valid for 30 days!');+ assert.ok(toks.includes('refund'), 'has refund');+ assert.ok(toks.includes('policy'), 'has policy');+ assert.ok(toks.includes('30'), 'keeps numbers');+ assert.ok(!toks.includes('the'), 'drops stop-word "the"');+ assert.ok(!toks.includes('is'), 'drops stop-word "is"');+ assert.ok(!toks.includes('x'), 'drops 1-char token');+ });++ // ─── detectModality ─────────────────────────────────────────────────────+ test('detectModality buckets by extension', () => {+ assert.strictEqual(kg.detectModality('a/b/notes.md'), 'text');+ assert.strictEqual(kg.detectModality('logo.PNG'), 'image');+ assert.strictEqual(kg.detectModality('report.pdf'), 'pdf');+ assert.strictEqual(kg.detectModality('data.csv'), 'sheet');+ assert.strictEqual(kg.detectModality('main.ts'), 'code');+ assert.strictEqual(kg.detectModality('weird.xyz'), 'text'); // unknown → text+ });++ // ─── chunkText ──────────────────────────────────────────────────────────+ test('chunkText returns one chunk for short text and multiple for long text', () => {+ assert.deepStrictEqual(kg.chunkText(''), []);+ assert.deepStrictEqual(kg.chunkText('short note'), ['short note']);+ const long = ('paragraph alpha. '.repeat(120) + '\n\n').repeat(6); // ~12k chars+ const chunks = kg.chunkText(long, { size: 1000, overlap: 100 });+ assert.ok(chunks.length > 5, `expected several chunks, got ${chunks.length}`);+ for (const c of chunks) assert.ok(c.length <= 1500, `chunk under cap: ${c.length}`);+ });++ test('chunkText always terminates and covers the text (deterministic)', () => {+ const text = 'word '.repeat(5000);+ const a = kg.chunkText(text, { size: 800, overlap: 120 });+ const b = kg.chunkText(text, { size: 800, overlap: 120 });+ assert.deepStrictEqual(a, b, 'deterministic');+ assert.ok(a.join(' ').includes('word'), 'covers content');+ });++ // ─── scoreChunk ─────────────────────────────────────────────────────────+ test('scoreChunk: 0 when no term matches, higher for title + phrase matches', () => {+ const terms = kg.tokenize('refund policy');+ const none = kg.scoreChunk({ title: 'Holidays', text: 'office closed friday' }, terms, 'refund policy');+ assert.strictEqual(none, 0);+ const body = kg.scoreChunk({ title: 'Holidays', text: 'our refund policy is generous' }, terms, 'refund policy');+ const titled = kg.scoreChunk({ title: 'Refund Policy', text: 'our refund policy is generous' }, terms, 'refund policy');+ assert.ok(body > 0, 'body match scores');+ assert.ok(titled > body, 'title match boosts above body-only');+ });++ // ─── ingest → search round-trip: TEXT modality ──────────────────────────+ test('ingest a markdown doc, then search finds it with a snippet', () => {+ const root = tmpRoot();+ const src = writeFixture(root, 'refund-policy.md',+ '# Refund Policy 2026\n\nCustomers may request a full refund within 30 days of purchase. '+ + 'Refunds for enterprise plans require manager approval.\n');+ const { docId, chunkCount, meta } = kg.ingest(root, { srcPath: src, tags: ['policy', 'support'] });+ assert.ok(docId, 'returns a docId');+ assert.ok(chunkCount >= 1, 'at least one chunk');+ assert.strictEqual(meta.modality, 'text');+ assert.strictEqual(meta.title, 'Refund Policy 2026', 'title derived from heading');+ // store layout exists+ assert.ok(fs.existsSync(path.join(root, 'index.jsonl')), 'index.jsonl written');+ assert.ok(fs.existsSync(path.join(root, 'docs', docId, 'text.md')), 'text.md written');+ assert.ok(fs.existsSync(path.join(root, 'docs', docId, 'meta.json')), 'meta.json written');+ assert.ok(fs.existsSync(path.join(root, 'docs', docId, 'original.md')), 'original copied');++ const hits = kg.search(root, 'refund within 30 days');+ assert.ok(hits.length >= 1, 'finds the doc');+ assert.strictEqual(hits[0].docId, docId);+ assert.ok(/refund/i.test(hits[0].snippet), 'snippet contains the match');+ });++ // ─── ingest → search round-trip: IMAGE modality (metadata-level) ────────+ test('ingest an image by metadata (no OCR) and find it by caption/tags', () => {+ const root = tmpRoot();+ // a tiny fake binary file standing in for an image artifact+ const img = path.join(root, 'org-chart.png');+ fs.writeFileSync(img, Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));+ const { docId, meta } = kg.ingest(root, {+ srcPath: img, title: 'Company Org Chart',+ caption: 'Engineering reports to the CTO; Sales reports to the CRO.',+ tags: ['orgchart', 'leadership']+ });+ assert.strictEqual(meta.modality, 'image');+ assert.strictEqual(meta.extractor, 'image-meta@1');+ assert.ok(fs.existsSync(path.join(root, 'docs', docId, 'original.png')), 'binary retained for future OCR');++ const byCaption = kg.search(root, 'who does engineering report to');+ assert.ok(byCaption.some((h) => h.docId === docId), 'found via caption text');+ const byTag = kg.search(root, 'orgchart leadership');+ assert.ok(byTag.some((h) => h.docId === docId), 'found via tags');+ });++ // ─── list / getDoc / removeDoc ──────────────────────────────────────────+ test('list, get, and remove manage the corpus and prune the index', () => {+ const root = tmpRoot();+ const a = kg.ingest(root, { text: 'Alpha document about onboarding new hires.', title: 'Onboarding' });+ const b = kg.ingest(root, { text: 'Beta document about the deployment runbook.', title: 'Runbook' });++ const docs = kg.list(root);+ assert.strictEqual(docs.length, 2, 'two docs listed');++ const got = kg.getDoc(root, a.docId);+ assert.ok(got && /onboarding/i.test(got.text), 'getDoc returns full text');+ assert.strictEqual(kg.getDoc(root, 'nope'), null, 'unknown id → null');++ assert.strictEqual(kg.removeDoc(root, a.docId), true);+ assert.strictEqual(kg.list(root).length, 1, 'one doc after remove');+ assert.strictEqual(kg.search(root, 'onboarding').length, 0, 'removed doc no longer searchable');+ assert.ok(kg.search(root, 'deployment runbook').some((h) => h.docId === b.docId), 'other doc intact');++ const s = kg.stats(root);+ assert.strictEqual(s.docCount, 1);+ });++ test('search returns [] for empty query or empty store', () => {+ const root = tmpRoot();+ assert.deepStrictEqual(kg.search(root, 'anything'), [], 'empty store');+ kg.ingest(root, { text: 'hello world', title: 'Greeting' });+ assert.deepStrictEqual(kg.search(root, ' '), [], 'blank query');+ });++ // ─── the real agent CLI (out-of-process retrieval path) ─────────────────+ console.log('knowledge-graph agent CLI (kg.cjs) tests');++ test('agent runs `kg search` against KG_ROOT and gets ranked, attributed results', () => {+ const root = tmpRoot();+ kg.ingest(root, {+ srcPath: writeFixture(root, 'pto.md',+ '# PTO Policy\n\nFull-time employees accrue 20 days of paid time off per year. '+ + 'Unused PTO rolls over up to 5 days.\n'),+ tags: ['hr', 'pto']+ });+ const res = spawnSync(process.execPath, [CLI, 'search', 'how much paid time off'],+ { encoding: 'utf8', env: { ...process.env, KG_ROOT: root } });+ assert.strictEqual(res.status, 0, `exit 0 (stderr: ${res.stderr})`);+ assert.ok(/PTO Policy/.test(res.stdout), 'CLI surfaces the title');+ assert.ok(/20 days/.test(res.stdout), 'CLI surfaces the matching passage');+ assert.ok(/id:/.test(res.stdout), 'CLI surfaces a doc id for `kg get`');+ });++ test('agent `kg search --json` is machine-parseable', () => {+ const root = tmpRoot();+ kg.ingest(root, { text: 'The wifi password is hunter2 for the guest network.', title: 'Wifi' });+ const res = spawnSync(process.execPath, [CLI, 'search', 'guest wifi password', '--json'],+ { encoding: 'utf8', env: { ...process.env, KG_ROOT: root } });+ assert.strictEqual(res.status, 0, `exit 0 (stderr: ${res.stderr})`);+ const parsed = JSON.parse(res.stdout);+ assert.ok(Array.isArray(parsed) && parsed.length >= 1, 'JSON array of hits');+ assert.strictEqual(parsed[0].title, 'Wifi');+ });++ test('agent CLI degrades gracefully when KG_ROOT is unset (flag off)', () => {+ const env = { ...process.env };+ delete env.KG_ROOT;+ const res = spawnSync(process.execPath, [CLI, 'search', 'anything'], { encoding: 'utf8', env });+ assert.strictEqual(res.status, 0, 'exits 0 (non-fatal) when KG is off');+ assert.ok(/not configured|off|unavailable/i.test(res.stderr + res.stdout), 'explains it is off');+ });++ // ─── summary ────────────────────────────────────────────────────────────+ if (failures > 0) {+ console.log(`\n${failures} test(s) failed`);+ process.exit(1);+ }+ console.log('\nAll knowledge-graph tests passed');+})();diff --git a/tools/copy-main-assets.cjs b/tools/copy-main-assets.cjsindex 3f5faa26..d5582ca4 100644--- a/tools/copy-main-assets.cjs+++ b/tools/copy-main-assets.cjs@@ -6,6 +6,8 @@ const { dirname, join } = require('node:path');const ROOT = join(__dirname, '..');const MAIN_ASSETS = [['src/main/slack-trigger.cjs', 'out/main/slack-trigger.cjs'],+ // Knowledge Graph core (pure-JS, no native deps) — required by knowledge.ts.+ ['src/main/kg-core.cjs', 'out/main/kg-core.cjs'],];for (const [fromRel, toRel] of MAIN_ASSETS) {