agentix-cli 0.69.4 → 0.70.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-IDAWXA3K.js → agent-V223TG6H.js} +2 -2
- package/dist/{board-dashboard-MAP6A2N7.js → board-dashboard-HR3PQPFW.js} +2 -2
- package/dist/{board-dashboard-MAP6A2N7.js.map → board-dashboard-HR3PQPFW.js.map} +1 -1
- package/dist/{chunk-CKBAVCGU.js → chunk-3IY2YWXP.js} +2 -2
- package/dist/{chunk-J7HA7ZTU.js → chunk-3RC4LO2G.js} +2 -2
- package/dist/{chunk-M6GPRMCQ.js → chunk-6QDOUOKD.js} +2 -2
- package/dist/{chunk-64P4QHSZ.js → chunk-CECHWYJ2.js} +1 -1
- package/dist/{chunk-64P4QHSZ.js.map → chunk-CECHWYJ2.js.map} +1 -1
- package/dist/{chunk-K63IOY6A.js → chunk-FBDIJEKL.js} +4 -4
- package/dist/chunk-FBDIJEKL.js.map +1 -0
- package/dist/{chunk-OHRTBD7U.js → chunk-LHLNARRW.js} +9 -9
- package/dist/chunk-ML6CNRBK.js +105 -0
- package/dist/chunk-ML6CNRBK.js.map +1 -0
- package/dist/{chunk-5ONI54E6.js → chunk-PHDS2HIN.js} +118 -118
- package/dist/chunk-PHDS2HIN.js.map +1 -0
- package/dist/{chunk-2UYV24UD.js → chunk-SN5N2FPG.js} +2 -2
- package/dist/chunk-TLDQWTSW.js +49 -0
- package/dist/chunk-TLDQWTSW.js.map +1 -0
- package/dist/chunk-TTVVXBCM.js +2 -0
- package/dist/chunk-TTVVXBCM.js.map +1 -0
- package/dist/{chunk-IU6L4V3A.js → chunk-W7SEPJFH.js} +2 -2
- package/dist/chunk-WLMQ5JMX.js +6 -0
- package/dist/chunk-WLMQ5JMX.js.map +1 -0
- package/dist/{chunk-DQQ3BCJW.js → chunk-YK7GFEGO.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/graph-FJ53FDWK.js +2 -0
- package/dist/index.d.ts +20 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/migrate-v2-ZOIMGITH.js +4 -0
- package/dist/{migrate-v2-KOMPDC6U.js.map → migrate-v2-ZOIMGITH.js.map} +1 -1
- package/dist/program-UTELWTXC.js +2 -0
- package/dist/promote-B5AOKPQR.js +2 -0
- package/dist/query-QLJNQUUP.js +2 -0
- package/dist/registry-CTZFLXGB.js +2 -0
- package/dist/types-NZOBHQGS.js +2 -0
- package/dist/wiki-X76JUHXT.js +2 -0
- package/dist/wiki-X76JUHXT.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-4DRNEOOW.js +0 -2
- package/dist/chunk-4DRNEOOW.js.map +0 -1
- package/dist/chunk-535MLOSB.js +0 -109
- package/dist/chunk-535MLOSB.js.map +0 -1
- package/dist/chunk-5ONI54E6.js.map +0 -1
- package/dist/chunk-K63IOY6A.js.map +0 -1
- package/dist/chunk-V2TLFYKH.js +0 -45
- package/dist/chunk-V2TLFYKH.js.map +0 -1
- package/dist/migrate-v2-KOMPDC6U.js +0 -4
- package/dist/program-T275Y2V6.js +0 -2
- package/dist/promote-VZAUTV6E.js +0 -2
- package/dist/query-7QQZPMXM.js +0 -2
- package/dist/registry-WQ65MQEY.js +0 -2
- package/dist/types-S6NHM5C3.js +0 -2
- package/dist/wiki-J4MMCONT.js +0 -2
- /package/dist/{agent-IDAWXA3K.js.map → agent-V223TG6H.js.map} +0 -0
- /package/dist/{chunk-CKBAVCGU.js.map → chunk-3IY2YWXP.js.map} +0 -0
- /package/dist/{chunk-J7HA7ZTU.js.map → chunk-3RC4LO2G.js.map} +0 -0
- /package/dist/{chunk-M6GPRMCQ.js.map → chunk-6QDOUOKD.js.map} +0 -0
- /package/dist/{chunk-OHRTBD7U.js.map → chunk-LHLNARRW.js.map} +0 -0
- /package/dist/{chunk-2UYV24UD.js.map → chunk-SN5N2FPG.js.map} +0 -0
- /package/dist/{chunk-IU6L4V3A.js.map → chunk-W7SEPJFH.js.map} +0 -0
- /package/dist/{chunk-DQQ3BCJW.js.map → chunk-YK7GFEGO.js.map} +0 -0
- /package/dist/{program-T275Y2V6.js.map → graph-FJ53FDWK.js.map} +0 -0
- /package/dist/{promote-VZAUTV6E.js.map → program-UTELWTXC.js.map} +0 -0
- /package/dist/{query-7QQZPMXM.js.map → promote-B5AOKPQR.js.map} +0 -0
- /package/dist/{registry-WQ65MQEY.js.map → query-QLJNQUUP.js.map} +0 -0
- /package/dist/{types-S6NHM5C3.js.map → registry-CTZFLXGB.js.map} +0 -0
- /package/dist/{wiki-J4MMCONT.js.map → types-NZOBHQGS.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/graph/migrate-v2.ts"],"sourcesContent":["import { readFileSync, writeFileSync, existsSync, copyFileSync } from \"fs\"\nimport { join } from \"path\"\nimport type { GraphStore } from \"./store\"\nimport { type IndexFile, indexFileSchema, type Classification, classificationSchema } from \"./types\"\n\n// --- Phase 2 of classifier-retire — bulk remap of past classifications ---\n//\n// The Phase 1 schema migration auto-converts schema.json + nodes.json from\n// v1 (scope/location/org/unit/activity) → v2 (category/verb). It does NOT\n// touch the two stores that hold real classification history:\n//\n// classifications.jsonl — append-only audit log of every decision\n// index.json — fingerprint → path cache used at hot-path\n//\n// Without remapping those, every recurring message keeps hitting the cache\n// and resolving to a v1 path that no longer exists in nodes.json. The UI\n// then renders raw ids (\"activity-rotate-tokens\") instead of the verb\n// label (\"Rotate credential\"). This module rewrites them in-place via\n// keyword heuristics — no LLM calls, no paid path.\n//\n// Idempotent: re-running on already-v2 data is a no-op.\n\nconst CATEGORY_SET = new Set([\n \"code\", \"ops\", \"support\", \"admin\", \"knowledge\", \"social\", \"system\",\n])\n\n/** Best-effort keyword mapping from a v1 leaf slug to a v2 (category, verb)\n * pair. Patterns are checked in order; first match wins. Anything that\n * doesn't hit a pattern is left alone (the next live classification will\n * re-classify the fingerprint with the new prompt). */\nconst PATTERNS: Array<{ test: RegExp; category: string; verb: string }> = [\n // --- code ---\n { test: /\\b(review[-_.]?(merge[-_.]?request|mr|pull[-_.]?request|pr))\\b/i, category: \"code\", verb: \"review.merge-request\" },\n { test: /\\breview[-_.]?(code|change|diff|snippet)\\b/i, category: \"code\", verb: \"review.code-change\" },\n { test: /\\b(fix|patch)[-_.]/i, category: \"code\", verb: \"fix.bug\" },\n { test: /\\b(implement|build|add)[-_.]?(feature|cli|api|endpoint)\\b/i, category: \"code\", verb: \"implement.feature\" },\n { test: /\\bimplement[-_.]/i, category: \"code\", verb: \"implement.feature\" },\n { test: /\\b(debug|investigate)[-_.]/i, category: \"code\", verb: \"investigate.error\" },\n { test: /\\brefactor\\b/i, category: \"code\", verb: \"refactor.code\" },\n { test: /\\b(plan|spec|rfc|design)[-_.]/i, category: \"code\", verb: \"spec.feature\" },\n { test: /\\b(handle|triage)[-_.]?(github|gitlab)?[-_.]?(issue|push|pr|mr|webhook|comment)\\b/i, category: \"code\", verb: \"triage.issue\" },\n { test: /\\btriage[-_.]?(issue|ticket)?\\b/i, category: \"code\", verb: \"triage.issue\" },\n { test: /\\banswer[-_.]?(code[-_.]?question|technical[-_.]?question)\\b/i, category: \"code\", verb: \"answer.code-question\" },\n { test: /\\b(commit|push|checkout|sync|merge)[-_.]/i, category: \"code\", verb: \"refactor.code\" },\n { test: /\\bauthor[-_.]?(workflow|spec|rfc)\\b/i, category: \"code\", verb: \"spec.feature\" },\n\n // --- ops ---\n { test: /\\bdeploy[-_.]?(staging|preview|qa|test)\\b/i, category: \"ops\", verb: \"deploy.staging\" },\n { test: /\\bdeploy[-_.]?(prod|production|live|release)\\b/i, category: \"ops\", verb: \"deploy.production\" },\n { test: /\\bdeploy[-_.]/i, category: \"ops\", verb: \"deploy.staging\" },\n { test: /\\brollback\\b/i, category: \"ops\", verb: \"rollback.release\" },\n { test: /\\binvestigate[-_.]?incident\\b/i, category: \"ops\", verb: \"investigate.incident\" },\n { test: /\\b(monitor|status|health[-_.]?check|metrics)\\b/i, category: \"ops\", verb: \"monitor.system\" },\n { test: /\\b(restart|stop|start)[-_.]?(daemon|service|server)\\b/i, category: \"ops\", verb: \"monitor.system\" },\n { test: /\\brun[-_.]?(server|infra)?[-_.]?(security|audit)\\b/i, category: \"ops\", verb: \"audit.security\" },\n { test: /\\brotate[-_.]?(token|tokens|credential|credentials|key|cert|secret)s?\\b/i, category: \"ops\", verb: \"rotate.credential\" },\n { test: /\\baudit\\b/i, category: \"ops\", verb: \"audit.security\" },\n { test: /\\bsetup[-_.]/i, category: \"ops\", verb: \"monitor.system\" },\n\n // --- support ---\n { test: /\\b(greet(ing)?|hello|hi[-_.]?there)\\b/i, category: \"support\", verb: \"chat.greeting\" },\n { test: /\\b(support[-_.]?request|help[-_.]?request|customer[-_.]?question)\\b/i, category: \"support\", verb: \"chat.support-request\" },\n { test: /\\b(casual|chitchat|smalltalk)\\b/i, category: \"support\", verb: \"chat.casual\" },\n { test: /\\b(query|ask|clarify|confirm)[-_.]/i, category: \"support\", verb: \"answer.question\" },\n { test: /\\b(reply|respond)[-_.]/i, category: \"support\", verb: \"route.request\" },\n { test: /\\banswer[-_.]?question\\b/i, category: \"support\", verb: \"answer.question\" },\n { test: /\\broute[-_.]?(request|message|to[-_.]?agent)\\b/i, category: \"support\", verb: \"route.request\" },\n\n // --- admin ---\n { test: /\\bconfig[-_.]?(change|update|edit)?\\b/i, category: \"admin\", verb: \"config.change\" },\n { test: /\\bconfigure[-_.]/i, category: \"admin\", verb: \"config.change\" },\n { test: /\\b(schedule|cron)[-_.]?(add|create|new)\\b/i, category: \"admin\", verb: \"schedule.add\" },\n { test: /\\b(reminder|remind)\\b/i, category: \"admin\", verb: \"schedule.add\" },\n { test: /\\b(schedule|cron)[-_.]?(remove|delete|disable)\\b/i, category: \"admin\", verb: \"schedule.remove\" },\n { test: /\\b(provide|assign|copy)[-_.]?(token|tokens|credential|credentials|cert|secret)s?\\b/i, category: \"admin\", verb: \"token.create\" },\n { test: /\\b(token[-_.]?(create|mint|issue)|mint[-_.]?token)\\b/i, category: \"admin\", verb: \"token.create\" },\n { test: /\\bagent[-_.]?(add|onboard|new|configure)\\b/i, category: \"admin\", verb: \"agent.add\" },\n { test: /\\bchannel[-_.]?(add|wire|new|configure)\\b/i, category: \"admin\", verb: \"channel.add\" },\n { test: /\\bauthorize[-_.]/i, category: \"admin\", verb: \"config.change\" },\n { test: /\\bcorrect[-_.]/i, category: \"admin\", verb: \"config.change\" },\n\n // --- knowledge ---\n { test: /\\b(document|docs|readme|wiki[-_.]?write)\\b/i, category: \"knowledge\", verb: \"document.feature\" },\n { test: /\\bsummariz?e\\b/i, category: \"knowledge\", verb: \"summarize.thread\" },\n { test: /\\b(research|analyze|compare|investigate[-_.]?repo)\\b/i, category: \"knowledge\", verb: \"research.topic\" },\n { test: /\\bwiki[-_.]?(absorb|ingest|import|run)\\b/i, category: \"knowledge\", verb: \"wiki.absorb\" },\n { test: /\\bcompile[-_.]?(brief|report|digest)\\b/i, category: \"knowledge\", verb: \"summarize.thread\" },\n\n // --- social ---\n { test: /\\b(daily[-_.]?brief|brief[-_.]?daily|morning[-_.]?digest)\\b/i, category: \"social\", verb: \"brief.daily\" },\n { test: /\\b(draft[-_.]?(social|post|tweet|announcement|blog|article)|social[-_.]?post)\\b/i, category: \"social\", verb: \"draft.post\" },\n { test: /\\bcreate[-_.]?(blog|article|post)\\b/i, category: \"social\", verb: \"draft.post\" },\n { test: /\\bcompile[-_.]?(marketing|social)\\b/i, category: \"social\", verb: \"brief.daily\" },\n { test: /\\b(weekly[-_.]?report|report[-_.]?weekly|status[-_.]?report)\\b/i, category: \"social\", verb: \"report.weekly\" },\n\n // --- system ---\n { test: /\\b(classify[-_.]?intent|graph[-_.]?classify)\\b/i, category: \"system\", verb: \"classify.intent\" },\n]\n\nexport interface MigrateOptions {\n /** When true, log the would-be changes and exit without writing. */\n dryRun?: boolean\n log?: (...args: unknown[]) => void\n}\n\nexport interface MigrateResult {\n /** How many fingerprint cache entries we touched. */\n indexRemapped: number\n /** Cache entries already in v2 shape (no change). */\n indexSkippedV2: number\n /** Cache entries we couldn't map (left untouched; will re-classify on next event). */\n indexUnmapped: number\n /** Classification log rows rewritten. */\n jsonlRemapped: number\n jsonlSkippedV2: number\n jsonlUnmapped: number\n /** Backup file paths created. */\n backups: string[]\n /** Per-pattern hit counts, useful for tuning the heuristic. */\n patternHits: Record<string, number>\n}\n\n/** Run the v1 → v2 remap on the given graph store dir. */\nexport function migrateV2(store: GraphStore, opts: MigrateOptions = {}): MigrateResult {\n const log = opts.log ?? console.error.bind(console, \"[graph-migrate]\")\n const baseDir = store.baseDir\n\n const result: MigrateResult = {\n indexRemapped: 0,\n indexSkippedV2: 0,\n indexUnmapped: 0,\n jsonlRemapped: 0,\n jsonlSkippedV2: 0,\n jsonlUnmapped: 0,\n backups: [],\n patternHits: {},\n }\n\n // ----- index.json -----\n const indexPath = join(baseDir, \"index.json\")\n if (existsSync(indexPath)) {\n const raw = readFileSync(indexPath, \"utf-8\")\n const parsed = indexFileSchema.parse(JSON.parse(raw))\n const updated: IndexFile = { version: parsed.version, entries: {} }\n for (const [fp, entry] of Object.entries(parsed.entries)) {\n const remapped = remapPath(entry.path, result.patternHits)\n if (remapped === \"v2\") {\n updated.entries[fp] = entry\n result.indexSkippedV2++\n continue\n }\n if (remapped === null) {\n updated.entries[fp] = entry\n result.indexUnmapped++\n continue\n }\n updated.entries[fp] = {\n ...entry,\n path: remapped,\n updatedAt: new Date().toISOString(),\n }\n result.indexRemapped++\n }\n if (!opts.dryRun) {\n const backup = `${indexPath}.v1.bak.${Date.now()}.json`\n copyFileSync(indexPath, backup)\n result.backups.push(backup)\n writeFileSync(indexPath, JSON.stringify(updated, null, 2), \"utf-8\")\n }\n }\n\n // ----- classifications.jsonl -----\n const jsonlPath = join(baseDir, \"classifications.jsonl\")\n if (existsSync(jsonlPath)) {\n const raw = readFileSync(jsonlPath, \"utf-8\")\n const lines = raw.split(\"\\n\")\n const out: string[] = []\n for (const line of lines) {\n if (!line.trim()) { out.push(line); continue }\n let parsed: Classification\n try {\n parsed = classificationSchema.parse(JSON.parse(line))\n } catch {\n // Pass through anything we can't parse — better to keep the audit\n // log intact than drop unrecognized rows.\n out.push(line)\n continue\n }\n const remapped = remapPath(parsed.path, result.patternHits)\n if (remapped === \"v2\") {\n result.jsonlSkippedV2++\n out.push(line)\n continue\n }\n if (remapped === null) {\n result.jsonlUnmapped++\n out.push(line)\n continue\n }\n const next: Classification = {\n ...parsed,\n path: remapped,\n // Strip v1 axes — they reference nodes that no longer exist post-migration.\n proposedAxes: {},\n }\n out.push(JSON.stringify(next))\n result.jsonlRemapped++\n }\n if (!opts.dryRun) {\n const backup = `${jsonlPath}.v1.bak.${Date.now()}.jsonl`\n copyFileSync(jsonlPath, backup)\n result.backups.push(backup)\n writeFileSync(jsonlPath, out.join(\"\\n\"), \"utf-8\")\n }\n }\n\n log(\n `index: ${result.indexRemapped} remapped, ${result.indexSkippedV2} already v2, ${result.indexUnmapped} unmapped`,\n )\n log(\n `jsonl: ${result.jsonlRemapped} remapped, ${result.jsonlSkippedV2} already v2, ${result.jsonlUnmapped} unmapped`,\n )\n if (opts.dryRun) log(\"(dry-run — no files written)\")\n else log(`backups: ${result.backups.join(\", \")}`)\n return result\n}\n\n/** Map a v1 path to a v2 path, OR detect that it's already v2, OR give up.\n * \"v2\" → path is already in v2 shape (length 1–2, root in CATEGORY_SET)\n * null → no pattern matched; caller should leave the entry alone\n * array → the new v2 path */\nfunction remapPath(path: string[], hits: Record<string, number>): string[] | \"v2\" | null {\n if (!Array.isArray(path) || path.length === 0) return null\n // Already v2 if the root is one of the closed categories.\n if (CATEGORY_SET.has(path[0])) return \"v2\"\n\n // The leaf carries the verb information in v1 (e.g. \"activity-review-mr\").\n // We also try the full path joined, because some leaves are just numeric ids.\n const haystack = `${path.join(\" \")} ${path[path.length - 1] ?? \"\"}`\n for (const p of PATTERNS) {\n if (p.test.test(haystack)) {\n hits[p.verb] = (hits[p.verb] ?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AAWH,CAAM,EAC9Bb,EAAO,QAAQ,KAAKa,CAAM,EAC1BE,EAAcC,EAAWE,EAAI,KAAK;AAAA,CAAI,EAAG,OAAO,GAIpD,OAAApB,EACE,UAAUE,EAAO,2BAA2BA,EAAO,8BAA8BA,EAAO,wBAC1F,EACAF,EACE,UAAUE,EAAO,2BAA2BA,EAAO,8BAA8BA,EAAO,wBAC1F,EACIH,EAAK,OAAQC,EAAI,mCAA8B,EAC9CA,EAAI,YAAYE,EAAO,QAAQ,KAAK,IAAI,GAAG,EACzCA,CACT,CAMA,SAASY,EAAUU,EAAgBC,EAAsD,CACvF,GAAI,CAAC,MAAM,QAAQD,CAAI,GAAKA,EAAK,SAAW,EAAG,OAAO,KAEtD,GAAI7B,EAAa,IAAI6B,EAAK,CAAC,CAAC,EAAG,MAAO,KAItC,IAAME,EAAW,GAAGF,EAAK,KAAK,GAAG,KAAKA,EAAKA,EAAK,OAAS,CAAC,GAAK,KAC/D,QAAWG,KAAK/B,EACd,GAAI+B,EAAE,KAAK,KAAKD,CAAQ,EACtB,OAAAD,EAAKE,EAAE,IAAI,GAAKF,EAAKE,EAAE,IAAI,GAAK,GAAK,EAC9B,CAACA,EAAE,SAAUA,EAAE,IAAI,EAG9B,OAAO,IACT","names":["readFileSync","writeFileSync","existsSync","copyFileSync","join","CATEGORY_SET","PATTERNS","migrateV2","store","opts","log","baseDir","result","indexPath","join","existsSync","raw","readFileSync","parsed","indexFileSchema","updated","fp","entry","remapped","remapPath","backup","copyFileSync","writeFileSync","jsonlPath","lines","out","line","classificationSchema","next","path","hits","haystack","p"]}
|
|
1
|
+
{"version":3,"sources":["../src/graph/migrate-v2.ts"],"sourcesContent":["import { readFileSync, writeFileSync, existsSync, copyFileSync } from \"fs\"\nimport { join } from \"path\"\nimport type { GraphStore } from \"./store\"\nimport { type IndexFile, indexFileSchema, type Classification, classificationSchema } from \"./types\"\n\n// --- Phase 2 of classifier-retire — bulk remap of past classifications ---\n//\n// The Phase 1 schema migration auto-converts schema.json + nodes.json from\n// v1 (scope/location/org/unit/activity) → v2 (category/verb). It does NOT\n// touch the two stores that hold real classification history:\n//\n// classifications.jsonl — append-only audit log of every decision\n// index.json — fingerprint → path cache used at hot-path\n//\n// Without remapping those, every recurring message keeps hitting the cache\n// and resolving to a v1 path that no longer exists in nodes.json. The UI\n// then renders raw ids (\"activity-rotate-tokens\") instead of the verb\n// label (\"Rotate credential\"). This module rewrites them in-place via\n// keyword heuristics — no LLM calls, no paid path.\n//\n// Idempotent: re-running on already-v2 data is a no-op.\n\nconst CATEGORY_SET = new Set([\n \"code\", \"ops\", \"support\", \"admin\", \"knowledge\", \"social\", \"system\",\n])\n\n/** Best-effort keyword mapping from a v1 leaf slug to a v2 (category, verb)\n * pair. Patterns are checked in order; first match wins. Anything that\n * doesn't hit a pattern is left alone (the next live classification will\n * re-classify the fingerprint with the new prompt). */\nconst PATTERNS: Array<{ test: RegExp; category: string; verb: string }> = [\n // --- code ---\n { test: /\\b(review[-_.]?(merge[-_.]?request|mr|pull[-_.]?request|pr))\\b/i, category: \"code\", verb: \"review.merge-request\" },\n { test: /\\breview[-_.]?(code|change|diff|snippet)\\b/i, category: \"code\", verb: \"review.code-change\" },\n { test: /\\b(fix|patch)[-_.]/i, category: \"code\", verb: \"fix.bug\" },\n { test: /\\b(implement|build|add)[-_.]?(feature|cli|api|endpoint)\\b/i, category: \"code\", verb: \"implement.feature\" },\n { test: /\\bimplement[-_.]/i, category: \"code\", verb: \"implement.feature\" },\n { test: /\\b(debug|investigate)[-_.]/i, category: \"code\", verb: \"investigate.error\" },\n { test: /\\brefactor\\b/i, category: \"code\", verb: \"refactor.code\" },\n { test: /\\b(plan|spec|rfc|design)[-_.]/i, category: \"code\", verb: \"spec.feature\" },\n { test: /\\b(handle|triage)[-_.]?(github|gitlab)?[-_.]?(issue|push|pr|mr|webhook|comment)\\b/i, category: \"code\", verb: \"triage.issue\" },\n { test: /\\btriage[-_.]?(issue|ticket)?\\b/i, category: \"code\", verb: \"triage.issue\" },\n { test: /\\banswer[-_.]?(code[-_.]?question|technical[-_.]?question)\\b/i, category: \"code\", verb: \"answer.code-question\" },\n { test: /\\b(commit|push|checkout|sync|merge)[-_.]/i, category: \"code\", verb: \"refactor.code\" },\n { test: /\\bauthor[-_.]?(workflow|spec|rfc)\\b/i, category: \"code\", verb: \"spec.feature\" },\n\n // --- ops ---\n { test: /\\bdeploy[-_.]?(staging|preview|qa|test)\\b/i, category: \"ops\", verb: \"deploy.staging\" },\n { test: /\\bdeploy[-_.]?(prod|production|live|release)\\b/i, category: \"ops\", verb: \"deploy.production\" },\n { test: /\\bdeploy[-_.]/i, category: \"ops\", verb: \"deploy.staging\" },\n { test: /\\brollback\\b/i, category: \"ops\", verb: \"rollback.release\" },\n { test: /\\binvestigate[-_.]?incident\\b/i, category: \"ops\", verb: \"investigate.incident\" },\n { test: /\\b(monitor|status|health[-_.]?check|metrics)\\b/i, category: \"ops\", verb: \"monitor.system\" },\n { test: /\\b(restart|stop|start)[-_.]?(daemon|service|server)\\b/i, category: \"ops\", verb: \"monitor.system\" },\n { test: /\\brun[-_.]?(server|infra)?[-_.]?(security|audit)\\b/i, category: \"ops\", verb: \"audit.security\" },\n { test: /\\brotate[-_.]?(token|tokens|credential|credentials|key|cert|secret)s?\\b/i, category: \"ops\", verb: \"rotate.credential\" },\n { test: /\\baudit\\b/i, category: \"ops\", verb: \"audit.security\" },\n { test: /\\bsetup[-_.]/i, category: \"ops\", verb: \"monitor.system\" },\n\n // --- support ---\n { test: /\\b(greet(ing)?|hello|hi[-_.]?there)\\b/i, category: \"support\", verb: \"chat.greeting\" },\n { test: /\\b(support[-_.]?request|help[-_.]?request|customer[-_.]?question)\\b/i, category: \"support\", verb: \"chat.support-request\" },\n { test: /\\b(casual|chitchat|smalltalk)\\b/i, category: \"support\", verb: \"chat.casual\" },\n { test: /\\b(query|ask|clarify|confirm)[-_.]/i, category: \"support\", verb: \"answer.question\" },\n { test: /\\b(reply|respond)[-_.]/i, category: \"support\", verb: \"route.request\" },\n { test: /\\banswer[-_.]?question\\b/i, category: \"support\", verb: \"answer.question\" },\n { test: /\\broute[-_.]?(request|message|to[-_.]?agent)\\b/i, category: \"support\", verb: \"route.request\" },\n\n // --- admin ---\n { test: /\\bconfig[-_.]?(change|update|edit)?\\b/i, category: \"admin\", verb: \"config.change\" },\n { test: /\\bconfigure[-_.]/i, category: \"admin\", verb: \"config.change\" },\n { test: /\\b(schedule|cron)[-_.]?(add|create|new)\\b/i, category: \"admin\", verb: \"schedule.add\" },\n { test: /\\b(reminder|remind)\\b/i, category: \"admin\", verb: \"schedule.add\" },\n { test: /\\b(schedule|cron)[-_.]?(remove|delete|disable)\\b/i, category: \"admin\", verb: \"schedule.remove\" },\n { test: /\\b(provide|assign|copy)[-_.]?(token|tokens|credential|credentials|cert|secret)s?\\b/i, category: \"admin\", verb: \"token.create\" },\n { test: /\\b(token[-_.]?(create|mint|issue)|mint[-_.]?token)\\b/i, category: \"admin\", verb: \"token.create\" },\n { test: /\\bagent[-_.]?(add|onboard|new|configure)\\b/i, category: \"admin\", verb: \"agent.add\" },\n { test: /\\bchannel[-_.]?(add|wire|new|configure)\\b/i, category: \"admin\", verb: \"channel.add\" },\n { test: /\\bauthorize[-_.]/i, category: \"admin\", verb: \"config.change\" },\n { test: /\\bcorrect[-_.]/i, category: \"admin\", verb: \"config.change\" },\n\n // --- knowledge ---\n { test: /\\b(document|docs|readme|wiki[-_.]?write)\\b/i, category: \"knowledge\", verb: \"document.feature\" },\n { test: /\\bsummariz?e\\b/i, category: \"knowledge\", verb: \"summarize.thread\" },\n { test: /\\b(research|analyze|compare|investigate[-_.]?repo)\\b/i, category: \"knowledge\", verb: \"research.topic\" },\n { test: /\\bwiki[-_.]?(absorb|ingest|import|run)\\b/i, category: \"knowledge\", verb: \"wiki.absorb\" },\n { test: /\\bcompile[-_.]?(brief|report|digest)\\b/i, category: \"knowledge\", verb: \"summarize.thread\" },\n\n // --- social ---\n { test: /\\b(daily[-_.]?brief|brief[-_.]?daily|morning[-_.]?digest)\\b/i, category: \"social\", verb: \"brief.daily\" },\n { test: /\\b(draft[-_.]?(social|post|tweet|announcement|blog|article)|social[-_.]?post)\\b/i, category: \"social\", verb: \"draft.post\" },\n { test: /\\bcreate[-_.]?(blog|article|post)\\b/i, category: \"social\", verb: \"draft.post\" },\n { test: /\\bcompile[-_.]?(marketing|social)\\b/i, category: \"social\", verb: \"brief.daily\" },\n { test: /\\b(weekly[-_.]?report|report[-_.]?weekly|status[-_.]?report)\\b/i, category: \"social\", verb: \"report.weekly\" },\n\n // --- system ---\n { test: /\\b(classify[-_.]?intent|graph[-_.]?classify)\\b/i, category: \"system\", verb: \"classify.intent\" },\n]\n\nexport interface MigrateOptions {\n /** When true, log the would-be changes and exit without writing. */\n dryRun?: boolean\n log?: (...args: unknown[]) => void\n}\n\nexport interface MigrateResult {\n /** How many fingerprint cache entries we touched. */\n indexRemapped: number\n /** Cache entries already in v2 shape (no change). */\n indexSkippedV2: number\n /** Cache entries we couldn't map (left untouched; will re-classify on next event). */\n indexUnmapped: number\n /** Classification log rows rewritten. */\n jsonlRemapped: number\n jsonlSkippedV2: number\n jsonlUnmapped: number\n /** Backup file paths created. */\n backups: string[]\n /** Per-pattern hit counts, useful for tuning the heuristic. */\n patternHits: Record<string, number>\n}\n\n/** Run the v1 → v2 remap on the given graph store dir. */\nexport function migrateV2(store: GraphStore, opts: MigrateOptions = {}): MigrateResult {\n const log = opts.log ?? console.error.bind(console, \"[graph-migrate]\")\n const baseDir = store.baseDir\n\n const result: MigrateResult = {\n indexRemapped: 0,\n indexSkippedV2: 0,\n indexUnmapped: 0,\n jsonlRemapped: 0,\n jsonlSkippedV2: 0,\n jsonlUnmapped: 0,\n backups: [],\n patternHits: {},\n }\n\n // ----- index.json -----\n const indexPath = join(baseDir, \"index.json\")\n if (existsSync(indexPath)) {\n const raw = readFileSync(indexPath, \"utf-8\")\n const parsed = indexFileSchema.parse(JSON.parse(raw))\n const updated: IndexFile = { version: parsed.version, entries: {} }\n for (const [fp, entry] of Object.entries(parsed.entries)) {\n const remapped = remapPath(entry.path, result.patternHits)\n if (remapped === \"v2\") {\n updated.entries[fp] = entry\n result.indexSkippedV2++\n continue\n }\n if (remapped === null) {\n updated.entries[fp] = entry\n result.indexUnmapped++\n continue\n }\n updated.entries[fp] = {\n ...entry,\n path: remapped,\n updatedAt: new Date().toISOString(),\n }\n result.indexRemapped++\n }\n if (!opts.dryRun) {\n const backup = `${indexPath}.v1.bak.${Date.now()}.json`\n copyFileSync(indexPath, backup)\n result.backups.push(backup)\n writeFileSync(indexPath, JSON.stringify(updated, null, 2), \"utf-8\")\n }\n }\n\n // ----- classifications.jsonl -----\n const jsonlPath = join(baseDir, \"classifications.jsonl\")\n if (existsSync(jsonlPath)) {\n const raw = readFileSync(jsonlPath, \"utf-8\")\n const lines = raw.split(\"\\n\")\n const out: string[] = []\n for (const line of lines) {\n if (!line.trim()) { out.push(line); continue }\n let parsed: Classification\n try {\n parsed = classificationSchema.parse(JSON.parse(line))\n } catch {\n // Pass through anything we can't parse — better to keep the audit\n // log intact than drop unrecognized rows.\n out.push(line)\n continue\n }\n const remapped = remapPath(parsed.path, result.patternHits)\n if (remapped === \"v2\") {\n result.jsonlSkippedV2++\n out.push(line)\n continue\n }\n if (remapped === null) {\n result.jsonlUnmapped++\n out.push(line)\n continue\n }\n const next: Classification = {\n ...parsed,\n path: remapped,\n // Strip v1 axes — they reference nodes that no longer exist post-migration.\n proposedAxes: {},\n }\n out.push(JSON.stringify(next))\n result.jsonlRemapped++\n }\n if (!opts.dryRun) {\n const backup = `${jsonlPath}.v1.bak.${Date.now()}.jsonl`\n copyFileSync(jsonlPath, backup)\n result.backups.push(backup)\n writeFileSync(jsonlPath, out.join(\"\\n\"), \"utf-8\")\n }\n }\n\n log(\n `index: ${result.indexRemapped} remapped, ${result.indexSkippedV2} already v2, ${result.indexUnmapped} unmapped`,\n )\n log(\n `jsonl: ${result.jsonlRemapped} remapped, ${result.jsonlSkippedV2} already v2, ${result.jsonlUnmapped} unmapped`,\n )\n if (opts.dryRun) log(\"(dry-run — no files written)\")\n else log(`backups: ${result.backups.join(\", \")}`)\n return result\n}\n\n/** Map a v1 path to a v2 path, OR detect that it's already v2, OR give up.\n * \"v2\" → path is already in v2 shape (length 1–2, root in CATEGORY_SET)\n * null → no pattern matched; caller should leave the entry alone\n * array → the new v2 path */\nfunction remapPath(path: string[], hits: Record<string, number>): string[] | \"v2\" | null {\n if (!Array.isArray(path) || path.length === 0) return null\n // Already v2 if the root is one of the closed categories.\n if (CATEGORY_SET.has(path[0])) return \"v2\"\n\n // The leaf carries the verb information in v1 (e.g. \"activity-review-mr\").\n // We also try the full path joined, because some leaves are just numeric ids.\n const haystack = `${path.join(\" \")} ${path[path.length - 1] ?? \"\"}`\n for (const p of PATTERNS) {\n if (p.test.test(haystack)) {\n hits[p.verb] = (hits[p.verb] ?? 0) + 1\n return [p.category, p.verb]\n }\n }\n return null\n}\n"],"mappings":"sEAAA,OAAS,gBAAAA,EAAc,iBAAAC,EAAe,cAAAC,EAAY,gBAAAC,MAAoB,KACtE,OAAS,QAAAC,MAAY,OAqBrB,IAAMC,EAAe,IAAI,IAAI,CAC3B,OAAQ,MAAO,UAAW,QAAS,YAAa,SAAU,QAC5D,CAAC,EAMKC,EAAoE,CAExE,CAAE,KAAM,kEAAmE,SAAU,OAAQ,KAAM,sBAAuB,EAC1H,CAAE,KAAM,8CAAmE,SAAU,OAAQ,KAAM,oBAAqB,EACxH,CAAE,KAAM,sBAAoE,SAAU,OAAQ,KAAM,SAAU,EAC9G,CAAE,KAAM,6DAAoE,SAAU,OAAQ,KAAM,mBAAoB,EACxH,CAAE,KAAM,oBAAoE,SAAU,OAAQ,KAAM,mBAAoB,EACxH,CAAE,KAAM,8BAAoE,SAAU,OAAQ,KAAM,mBAAoB,EACxH,CAAE,KAAM,gBAAoE,SAAU,OAAQ,KAAM,eAAgB,EACpH,CAAE,KAAM,iCAAoE,SAAU,OAAQ,KAAM,cAAe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GAAKF,EAAKE,EAAE,IAAI,GAAK,GAAK,EAC9B,CAACA,EAAE,SAAUA,EAAE,IAAI,EAG9B,OAAO,IACT","names":["readFileSync","writeFileSync","existsSync","copyFileSync","join","CATEGORY_SET","PATTERNS","migrateV2","store","opts","log","baseDir","result","indexPath","join","existsSync","raw","readFileSync","parsed","indexFileSchema","updated","fp","entry","remapped","remapPath","backup","copyFileSync","writeFileSync","jsonlPath","lines","out","line","classificationSchema","next","path","hits","haystack","p"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a}from"./chunk-LHLNARRW.js";import"./chunk-OVX6NRMD.js";import"./chunk-KLHG5ZQH.js";import"./chunk-6QDOUOKD.js";import"./chunk-Z3IP66SL.js";import"./chunk-C4CDVE2E.js";import"./chunk-RKPAVWXF.js";import"./chunk-SZDACK6O.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-PHDS2HIN.js";import"./chunk-3IY2YWXP.js";import"./chunk-YBF2QVZ7.js";import"./chunk-BYJ3A55Y.js";import"./chunk-NMFXY3QU.js";import"./chunk-LQRBGQIR.js";import"./chunk-ZVP6GB4G.js";import"./chunk-YK7GFEGO.js";import"./chunk-AQASR6KR.js";import"./chunk-2D3RYIDU.js";import"./chunk-EKJG63EJ.js";import"./chunk-FBDIJEKL.js";import"./chunk-W7SEPJFH.js";import"./chunk-WP6KLXTP.js";import"./chunk-N6EWZGIX.js";import"./chunk-DP7RTNDM.js";import"./chunk-3RC4LO2G.js";import"./chunk-SFQUP3BP.js";import"./chunk-FSYA4GNU.js";import"./chunk-2AXFYDWF.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-OPUPVGYP.js";import"./chunk-YL223TEU.js";import"./chunk-VWTBHLMX.js";import"./chunk-SN5N2FPG.js";import"./chunk-ML6CNRBK.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-P2RYUODK.js";import"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-TLDQWTSW.js";import"./chunk-TFVUOC2C.js";import"./chunk-2GIDVZ4H.js";import"./chunk-QOYAX2FT.js";import"./chunk-WLMQ5JMX.js";import"./chunk-TTVVXBCM.js";import"./chunk-BBIWAJRX.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import"./chunk-DTX4I5LQ.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{a as buildProgram};
|
|
2
|
+
//# sourceMappingURL=program-UTELWTXC.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i,k as j,l as k,m as l,n as m,o as n,p as o,q as p,r as q,s as r,t as s,u as t}from"./chunk-YK7GFEGO.js";import"./chunk-AQASR6KR.js";import"./chunk-DP7RTNDM.js";import"./chunk-2AXFYDWF.js";import"./chunk-ML6CNRBK.js";import"./chunk-CECHWYJ2.js";import"./chunk-TFVUOC2C.js";import"./chunk-QOYAX2FT.js";import"./chunk-WLMQ5JMX.js";import"./chunk-TTVVXBCM.js";import"./chunk-BBIWAJRX.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-DTX4I5LQ.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{b as DEFAULT_PROMOTE_TYPES,a as PROMOTER_OWNER,c as PROMOTION_LEDGER_FILE,j as appendPromotionLedger,s as approveProposal,n as callPromotionLlm,p as estimateTokens,r as evidenceFor,m as getUnpromotedMemories,k as groupCandidates,h as listAllAgentMemories,d as memoryKey,e as memoryStamp,g as mergeSources,f as parseMemoryStamp,l as parsePromotionResponse,i as readPromotionLedger,t as rejectProposal,o as runPromotion,q as sourceKind};
|
|
2
|
+
//# sourceMappingURL=promote-B5AOKPQR.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a,b,c}from"./chunk-TLDQWTSW.js";import"./chunk-TFVUOC2C.js";import"./chunk-2GIDVZ4H.js";import"./chunk-QOYAX2FT.js";import"./chunk-WLMQ5JMX.js";import"./chunk-TTVVXBCM.js";import"./chunk-BBIWAJRX.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-DTX4I5LQ.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{b as DEFAULT_GRAPH_WEIGHT,a as agenticQuery,c as rankCatalogPool};
|
|
2
|
+
//# sourceMappingURL=query-QLJNQUUP.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{I as a,J as b,K as c,L as d,M as e,N as f,O as g,P as h,Q as i,R as j,S as k,T as l}from"./chunk-FBDIJEKL.js";import"./chunk-W7SEPJFH.js";import"./chunk-WP6KLXTP.js";import"./chunk-N6EWZGIX.js";import"./chunk-DP7RTNDM.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-OPUPVGYP.js";import"./chunk-YL223TEU.js";import"./chunk-VWTBHLMX.js";import"./chunk-SN5N2FPG.js";import"./chunk-ML6CNRBK.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-P2RYUODK.js";import"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-TLDQWTSW.js";import"./chunk-TFVUOC2C.js";import"./chunk-2GIDVZ4H.js";import"./chunk-QOYAX2FT.js";import"./chunk-WLMQ5JMX.js";import"./chunk-TTVVXBCM.js";import"./chunk-BBIWAJRX.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-DSYKYZMT.js";import"./chunk-DTX4I5LQ.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{k as AgentRegistry,f as TRACE_STEP_SUMMARY_BYTES,c as buildEntryMeta,d as buildEventDigest,e as buildWikiContext,g as clipForTrace,j as emitTraceStepsFromStreamEvent,i as firstMissingRequiredTool,b as getGlobalRegistry,l as richReplyPrompt,a as setGlobalRegistry,h as tallyToolUses};
|
|
2
|
+
//# sourceMappingURL=registry-CTZFLXGB.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import"./chunk-VWTBHLMX.js";import{a as b}from"./chunk-SN5N2FPG.js";import{a}from"./chunk-ML6CNRBK.js";import"./chunk-CECHWYJ2.js";import{a as c}from"./chunk-TLDQWTSW.js";import"./chunk-TFVUOC2C.js";import"./chunk-2GIDVZ4H.js";import"./chunk-QOYAX2FT.js";import"./chunk-WLMQ5JMX.js";import"./chunk-TTVVXBCM.js";import"./chunk-BBIWAJRX.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-DTX4I5LQ.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{b as WikiHub,a as WikiStore,c as agenticQuery};
|
|
2
|
+
//# sourceMappingURL=wiki-X76JUHXT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentix-cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.70.0",
|
|
4
4
|
"description": "AI operations layer for small and medium businesses. Routes Telegram, WhatsApp, GitLab, GitHub, crons, webhooks, and mesh tasks to AI agents. Web wizard for operators, CLI for engineers. Self-hosted.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": {
|
package/dist/chunk-4DRNEOOW.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{z as e}from"zod";var i=e.enum(["enum","free","ref"]),a=e.object({name:e.string().regex(/^[a-z][a-z0-9_]*$/i,"axis name must be a simple identifier"),type:i,values:e.array(e.string()).optional(),refLevel:e.string().optional(),optional:e.boolean().optional(),description:e.string().optional()}),r=e.object({id:e.string().regex(/^[a-z][a-z0-9_-]*$/,"level id must be lowercase slug"),axes:e.array(a).min(1),description:e.string().optional()}),f=e.object({version:e.number().int().default(1),levels:e.array(r).min(1).max(5),leafInput:a.optional(),leafOutput:a.optional()}),t=e.string().regex(/^[a-z0-9][a-z0-9._-]*$/,"node id must be lowercase slug (alnum, '.', '_', '-')"),n=e.object({id:t,level:e.string(),parentId:t.nullable(),axes:e.record(e.string(),e.string()),createdAt:e.string(),createdBy:e.string().optional()}),o=e.enum(["llm","user","cache"]),s=e.enum(["pending","approved","rejected"]),p=e.object({ts:e.string(),msgHash:e.string(),agentId:e.string().optional(),channel:e.string().optional(),sender:e.string().optional(),path:e.array(t),proposedAxes:e.record(e.string(),e.record(e.string(),e.string())).default({}),leaf:e.object({input:e.string().optional(),output:e.string().optional()}).partial().default({}),source:o,status:s,confidence:e.number().min(0).max(1).optional(),preview:e.string().optional()}),c=e.object({fingerprint:e.string(),path:e.array(t),leaf:p.shape.leaf,updatedAt:e.string()}),m=e.object({version:e.number().int().default(1),nodes:e.array(n).default([])}),d=e.object({version:e.number().int().default(1),entries:e.record(e.string(),c).default({})});export{f as a,p as b,c,m as d,d as e};
|
|
2
|
-
//# sourceMappingURL=chunk-4DRNEOOW.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/graph/types.ts"],"sourcesContent":["import { z } from \"zod\"\n\n// --- Intent Knowledge Graph types + Zod schemas ---\n//\n// A hierarchical, enumerable intent taxonomy with fixed axes per level.\n// See plan: /Users/you/.claude/plans/delightful-floating-diffie.md\n//\n// Shape on disk (.agentx/graph/):\n// schema.json — level definitions + required axes per level\n// nodes.json — tree of nodes: { id, level, parentId, axes }\n// classifications.jsonl — append-only log of message → path decisions\n// index.json — fingerprint → pathId snap-to-path cache\n\nexport const axisTypeSchema = z.enum([\"enum\", \"free\", \"ref\"])\nexport type AxisType = z.infer<typeof axisTypeSchema>\n\nexport const axisDefSchema = z.object({\n name: z.string().regex(/^[a-z][a-z0-9_]*$/i, \"axis name must be a simple identifier\"),\n type: axisTypeSchema,\n /** For type=\"enum\": closed set of allowed values. */\n values: z.array(z.string()).optional(),\n /** For type=\"ref\": which level's nodes may be referenced. */\n refLevel: z.string().optional(),\n /** If true, this axis may be absent from a node without failing validation.\n * Use for axes that apply conditionally (e.g. a department's \"lead\" ref\n * doesn't apply to a person-kind unit). Absent/false = required. */\n optional: z.boolean().optional(),\n /** Optional human-readable help, shown as tooltip in the admin UI. */\n description: z.string().optional(),\n})\nexport type AxisDef = z.infer<typeof axisDefSchema>\n\nexport const levelDefSchema = z.object({\n id: z.string().regex(/^[a-z][a-z0-9_-]*$/, \"level id must be lowercase slug\"),\n /** Axes every node at this level MUST carry. Order matters for UI rendering. */\n axes: z.array(axisDefSchema).min(1),\n description: z.string().optional(),\n})\nexport type LevelDef = z.infer<typeof levelDefSchema>\n\nexport const graphSchemaSchema = z.object({\n version: z.number().int().default(1),\n /** Ordered from root to leaf. Max 5 to keep the taxonomy scannable. */\n levels: z.array(levelDefSchema).min(1).max(5),\n /** Axis describing where a leaf classification came from (channel, cron, etc.). */\n leafInput: axisDefSchema.optional(),\n /** Free-form description of the expected result of a leaf classification. */\n leafOutput: axisDefSchema.optional(),\n})\nexport type GraphSchema = z.infer<typeof graphSchemaSchema>\n\n// Allow dots so verb-level node ids like \"review.merge-request\" or\n// \"deploy.staging\" parse cleanly (Phase 1 of the classifier-retire plan).\n// Dots are dot-namespaced verbs only — never the leading char.\nexport const nodeIdSchema = z.string().regex(/^[a-z0-9][a-z0-9._-]*$/, \"node id must be lowercase slug (alnum, '.', '_', '-')\")\n\nexport const graphNodeSchema = z.object({\n id: nodeIdSchema,\n /** Matches a `levels[*].id` from the schema. */\n level: z.string(),\n /** null for root-level nodes (level[0]); otherwise the id of a node at level-1. */\n parentId: nodeIdSchema.nullable(),\n /** Values for every axis declared at this level's schema entry. `ref` axes\n * hold the id of another node; `enum` axes hold one of the declared values;\n * `free` axes hold any string. */\n axes: z.record(z.string(), z.string()),\n createdAt: z.string(),\n createdBy: z.string().optional(),\n})\nexport type GraphNode = z.infer<typeof graphNodeSchema>\n\nexport const classificationSourceSchema = z.enum([\"llm\", \"user\", \"cache\"])\nexport type ClassificationSource = z.infer<typeof classificationSourceSchema>\n\nexport const classificationStatusSchema = z.enum([\"pending\", \"approved\", \"rejected\"])\nexport type ClassificationStatus = z.infer<typeof classificationStatusSchema>\n\nexport const classificationSchema = z.object({\n ts: z.string(),\n msgHash: z.string(),\n agentId: z.string().optional(),\n channel: z.string().optional(),\n sender: z.string().optional(),\n /** Node ids from root to leaf, one per level. Shorter-than-full paths are\n * allowed if the classifier was only confident down to a certain depth. */\n path: z.array(nodeIdSchema),\n /** Axis values asserted by the classifier for new nodes it proposed along\n * the path. Keyed by node id. */\n proposedAxes: z.record(z.string(), z.record(z.string(), z.string())).default({}),\n /** Leaf-level extras. */\n leaf: z.object({\n input: z.string().optional(),\n output: z.string().optional(),\n }).partial().default({}),\n source: classificationSourceSchema,\n status: classificationStatusSchema,\n confidence: z.number().min(0).max(1).optional(),\n /** Redacted first ~200 chars of the message, for the approval UI. */\n preview: z.string().optional(),\n})\nexport type Classification = z.infer<typeof classificationSchema>\n\n/** Row in the fingerprint → path snap cache. */\nexport const fingerprintEntrySchema = z.object({\n fingerprint: z.string(),\n path: z.array(nodeIdSchema),\n leaf: classificationSchema.shape.leaf,\n updatedAt: z.string(),\n})\nexport type FingerprintEntry = z.infer<typeof fingerprintEntrySchema>\n\n/** Nodes file is a plain list, not a nested tree — lookups are by id. */\nexport const nodesFileSchema = z.object({\n version: z.number().int().default(1),\n nodes: z.array(graphNodeSchema).default([]),\n})\nexport type NodesFile = z.infer<typeof nodesFileSchema>\n\n/** Index file — record of fingerprints. Hot path; kept as a map on disk. */\nexport const indexFileSchema = z.object({\n version: z.number().int().default(1),\n entries: z.record(z.string(), fingerprintEntrySchema).default({}),\n})\nexport type IndexFile = z.infer<typeof indexFileSchema>\n"],"mappings":"AAAA,OAAS,KAAAA,MAAS,MAaX,IAAMC,EAAiBD,EAAE,KAAK,CAAC,OAAQ,OAAQ,KAAK,CAAC,EAG/CE,EAAgBF,EAAE,OAAO,CACpC,KAAMA,EAAE,OAAO,EAAE,MAAM,qBAAsB,uCAAuC,EACpF,KAAMC,EAEN,OAAQD,EAAE,MAAMA,EAAE,OAAO,CAAC,EAAE,SAAS,EAErC,SAAUA,EAAE,OAAO,EAAE,SAAS,EAI9B,SAAUA,EAAE,QAAQ,EAAE,SAAS,EAE/B,YAAaA,EAAE,OAAO,EAAE,SAAS,CACnC,CAAC,EAGYG,EAAiBH,EAAE,OAAO,CACrC,GAAIA,EAAE,OAAO,EAAE,MAAM,qBAAsB,iCAAiC,EAE5E,KAAMA,EAAE,MAAME,CAAa,EAAE,IAAI,CAAC,EAClC,YAAaF,EAAE,OAAO,EAAE,SAAS,CACnC,CAAC,EAGYI,EAAoBJ,EAAE,OAAO,CACxC,QAASA,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,EAEnC,OAAQA,EAAE,MAAMG,CAAc,EAAE,IAAI,CAAC,EAAE,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AMI,EAAqB,MAAM,KACjC,UAAWT,EAAE,OAAO,CACtB,CAAC,EAIYW,EAAkBX,EAAE,OAAO,CACtC,QAASA,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,EACnC,MAAOA,EAAE,MAAMM,CAAe,EAAE,QAAQ,CAAC,CAAC,CAC5C,CAAC,EAIYM,EAAkBZ,EAAE,OAAO,CACtC,QAASA,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,EACnC,QAASA,EAAE,OAAOA,EAAE,OAAO,EAAGU,CAAsB,EAAE,QAAQ,CAAC,CAAC,CAClE,CAAC","names":["z","axisTypeSchema","axisDefSchema","levelDefSchema","graphSchemaSchema","nodeIdSchema","graphNodeSchema","classificationSourceSchema","classificationStatusSchema","classificationSchema","fingerprintEntrySchema","nodesFileSchema","indexFileSchema"]}
|
package/dist/chunk-535MLOSB.js
DELETED
|
@@ -1,109 +0,0 @@
|
|
|
1
|
-
import{a as T,b as R,c as re,d as L,e as _}from"./chunk-4DRNEOOW.js";import{b as X}from"./chunk-64P4QHSZ.js";import{a as Q,b as Z,c as ee,d as te,e as se}from"./chunk-TFVUOC2C.js";import{v as Y,w as he}from"./chunk-BBIWAJRX.js";import{a as V,b as pe}from"./chunk-FX3D7YON.js";import{c as O,d as M}from"./chunk-QOYAX2FT.js";import{o as K,p as de}from"./chunk-5MUJZODV.js";var A={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},G=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as D,writeFileSync as F,appendFileSync as ue,existsSync as W,mkdirSync as B,renameSync as ge,statSync as ie}from"fs";import{resolve as P,dirname as oe}from"path";import{createHash as fe}from"crypto";var J=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??P(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),B(this.baseDir,{recursive:!0})}schemaPath(){return P(this.baseDir,"schema.json")}nodesPath(){return P(this.baseDir,"nodes.json")}indexPath(){return P(this.baseDir,"index.json")}classificationsPath(){return P(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!W(e))return this.saveSchema(A),this.log("seeded starter schema at",e),A;let t=D(e,"utf-8"),s=T.safeParse(JSON.parse(t));if(!s.success)throw new Error(`Invalid ${e}: ${s.error.issues.map(r=>r.message).join("; ")}`);if((s.data.version??1)<(A.version??2)){let r=e.replace(/\.json$/,`.v${s.data.version??1}.bak.json`);try{F(r,t),this.log(`migrated graph schema v${s.data.version??1} -> v${A.version}; old saved at ${r}`)}catch(a){this.log(`could not back up old schema: ${a?.message??a}`)}this.saveSchema(A);let n=this.nodesPath();if(W(n)){let a=n.replace(/\.json$/,".v1.bak.json");try{F(a,D(n,"utf-8")),this.log(`archived v1 nodes.json -> ${a}`)}catch(i){this.log(`could not back up old nodes: ${i?.message??i}`)}try{let i=ae();this.saveNodes(i)}catch(i){this.log(`could not seed v2 nodes: ${i?.message??i}`)}}return A}return s.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(s=>s.message).join("; ")}`);ne(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!W(e)){let t=ae();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let s=L.safeParse(JSON.parse(t));if(!s.success)throw new Error(`Invalid ${e}: ${s.error.issues.map(r=>r.message).join("; ")}`);return s.data}))}saveNodes(e){let t=L.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(s=>s.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:s,size:r}=ie(e),n=this.parsed.get(e);if(n&&n.mtimeMs===s&&n.size===r)return n.data;let a=t(D(e,"utf-8"));return this.parsed.set(e,{mtimeMs:s,size:r,data:a}),a}writeParsed(e,t){this.parsed.delete(e),ne(e,t);let{mtimeMs:s,size:r}=ie(e);this.parsed.set(e,{mtimeMs:s,size:r,data:t})}validateNode(e,t,s){let r=t.levels.find(i=>i.id===e.level);if(!r)throw new Error(`Unknown level: "${e.level}"`);let n=r.axes.filter(i=>!i.optional).filter(i=>!(i.name in e.axes));if(n.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${n.map(i=>i.name).join(", ")}`);for(let i of r.axes){let o=e.axes[i.name];if(o!=null){if(i.type==="enum"&&i.values&&!i.values.includes(o))throw new Error(`Node ${e.id}: axis ${i.name}="${o}" not in enum ${JSON.stringify(i.values)}`);if(i.type==="ref"){if(!s.some(c=>c.id===o))throw new Error(`Node ${e.id}: axis ${i.name}="${o}" refers to unknown node`);if(i.refLevel){let c=s.find(l=>l.id===o);if(c.level!==i.refLevel)throw new Error(`Node ${e.id}: axis ${i.name} expected level "${i.refLevel}" but got "${c.level}"`)}}}}let a=t.levels.findIndex(i=>i.id===e.level);if(a===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let i=s.find(c=>c.id===e.parentId);if(!i)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let o=t.levels.findIndex(c=>c.id===i.level);if(o<0||o>=a)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${i.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,s,r){let n=[],a=[],i=new Date().toISOString();for(let o=0;o<e.length;o++){let c=e[o],l=this.loadNodes().nodes;if(l.find(m=>m.id===c)){a.push(c);continue}let p=0;for(let m=o-1;m>=0;m--){let b=e[m],C=l.find(k=>k.id===b)||n.find(k=>k.id===b);if(C){p=s.levels.findIndex(k=>k.id===C.level)+1;break}}let u=t[c]??{},d=null;for(let m=p;m<s.levels.length;m++){let b=s.levels[m];if(b.axes.filter(k=>!k.optional).filter(k=>!(k.name in u)).length===0){d=b.id,p=m+1;break}}if(!d&&p<s.levels.length&&(d=s.levels[p].id,p++),!d)throw new Error(`Can't place node ${c} \u2014 no schema level left (cursor=${p}, levels=${s.levels.length})`);let h=null,f=s.levels.findIndex(m=>m.id===d);for(let m=o-1;m>=0;m--){let b=e[m],C=l.find(I=>I.id===b)||n.find(I=>I.id===b);if(!C)continue;let k=s.levels.findIndex(I=>I.id===C.level);if(k>=0&&k<f){h=b;break}}let g={id:c,level:d,parentId:h,axes:u,createdAt:i,createdBy:r};this.addNode(g),n.push(g)}return{added:n,skipped:a}}addNode(e){let t=this.loadSchema(),s=this.loadNodes();if(s.nodes.some(r=>r.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...s.nodes,e]),s.nodes.push(e),this.saveNodes(s),e}appendClassification(e){let t=R.safeParse(e);if(!t.success){let n=t.error.issues.map(a=>`${a.path.join(".")}: ${a.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${n} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let s=JSON.stringify(t.data)+`
|
|
2
|
-
`,r=this.classificationsPath();return W(r)||B(oe(r),{recursive:!0}),ue(r,s),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(r=>r.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!W(e))return[];let s=D(e,"utf-8").split(`
|
|
3
|
-
`).filter(Boolean),r=new Map;for(let n of s)try{let a=R.safeParse(JSON.parse(n));if(!a.success)continue;r.set(a.data.msgHash,a.data)}catch{}return Array.from(r.values()).sort((n,a)=>n.ts<a.ts?1:-1)}updateClassificationStatus(e,t){let r=this.readAllCollapsed().find(a=>a.msgHash===e);if(!r)return null;let n={...r,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let a=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;n.preview=((r.preview||"")+a).slice(0,500)}return this.appendClassification(n),n}readRecentClassifications(e=50){let t=this.classificationsPath();if(!W(t))return[];let r=D(t,"utf-8").split(`
|
|
4
|
-
`).filter(Boolean),n=[];for(let a=r.length-1;a>=0&&n.length<e;a--)try{let i=R.safeParse(JSON.parse(r[a]));i.success&&n.push(i.data)}catch{}return n}fingerprint(e){let s=[me(e.text),e.channel??""].join("");return fe("sha256").update(s).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=_.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(s=>s.message).join("; ")}`);this.writeParsed(this.indexPath(),t.data)}index(){let e=this.indexPath();return W(e)?this.readParsed(e,t=>{let s=_.safeParse(JSON.parse(t));if(!s.success)throw new Error(`Invalid ${e}: ${s.error.issues.map(r=>r.message).join("; ")}`);return s.data}):{version:1,entries:{}}}getFingerprint(e){let t=this.index().entries[e];return t&&structuredClone(t)}setFingerprint(e,t){let s=re.safeParse({...t,fingerprint:e,updatedAt:new Date().toISOString()});if(!s.success)throw new Error(`Refusing to save invalid index entry: ${s.error.issues.map(n=>n.message).join("; ")}`);let r=this.index();this.writeParsed(this.indexPath(),{...r,entries:{...r.entries,[e]:s.data}})}updateNodeAxes(e,t){let s=this.loadSchema(),r=this.loadNodes(),n=r.nodes.find(i=>i.id===e);if(!n)throw new Error(`Node not found: ${e}`);let a={...n,axes:t};return this.validateNode(a,s,r.nodes.map(i=>i.id===e?a:i)),r.nodes=r.nodes.map(i=>i.id===e?a:i),this.saveNodes(r),a}deleteNode(e){let t=this.loadNodes(),s=t.nodes.find(n=>n.parentId===e);if(s)throw new Error(`Cannot delete "${e}" \u2014 child node "${s.id}" still points to it`);let r=t.nodes.find(n=>Object.values(n.axes).some(a=>a===e));if(r)throw new Error(`Cannot delete "${e}" \u2014 node "${r.id}" references it via an axis`);t.nodes=t.nodes.filter(n=>n.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),s=new Set(this.loadNodes().nodes.map(r=>r.id));for(let r=0;r<e.path.length;r++){let n=e.path[r];if(s.has(n))continue;let a=t.levels[r]?.id;if(!a)break;let i=e.proposedAxes?.[n]??{},o=r===0?null:e.path[r-1];this.addNode({id:n,level:a,parentId:o,axes:i,createdAt:new Date().toISOString(),createdBy:e.agentId}),s.add(n)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function ne(y,e){B(oe(y),{recursive:!0});let t=`${y}.tmp-${process.pid}`;F(t,JSON.stringify(e,null,2)),ge(t,y)}function ae(){let y=new Date().toISOString(),e=[],t=new Set;for(let s of G)t.has(s.category)||(e.push({id:s.category,level:"category",parentId:null,axes:{kind:s.category},createdAt:y,createdBy:"starter"}),t.add(s.category));for(let s of G)e.push({id:s.verb,level:"verb",parentId:s.category,axes:{name:s.verb,...s.description?{description:s.description}:{}},createdAt:y,createdBy:"starter"});return{version:1,nodes:e}}function me(y){return y.toLowerCase().replace(/https?:\/\/\S+/g," url ").replace(/[@#][\w.\/-]+/g," ref ").replace(/\b[0-9a-f]{7,}\b/g," id ").replace(/\d+/g," num ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim().slice(0,400)}pe();de();import{createHash as ve}from"crypto";var H=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=K(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),s=this.store.getFingerprint(t);if(s)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,path:s.path,proposedAxes:{},leaf:s.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:s.path,pathId:U(s.path),pathLabel:q(s.path,this.store.loadNodes().nodes),axes:{},leaf:s.leaf,source:"cache",status:"approved"};let r=this.store.loadSchema(),n=this.store.loadNodes().nodes,a=await this.proposePath(e,r,n).catch(g=>(this.log("LLM proposal failed:",g?.message||g),null));if(!a)return null;let{path:i,proposedAxes:o,confidence:c,leaf:l}=a;if(i.length===0)return null;let v={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,path:i,proposedAxes:o,leaf:l,source:"llm",status:"pending",confidence:c,preview:e.text.slice(0,200)},p=new Set(n.map(g=>g.id)),u=i.map((g,m)=>p.has(g)?-1:m).filter(g=>g>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let g=u.length===0,m=u.length===1&&u[0]===i.length-1;d=g||m}let h=c!==void 0&&c>=this.autoApprove,f="pending";if(d||h)try{this.commitNewNodes(i,o,r,n,e.sender),this.store.setFingerprint(t,{path:i,leaf:l}),f="approved"}catch(g){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(i)}`,`reason=${(g?.message||g).toString().slice(0,200)}`)}return v.status=f,this.store.appendClassification(v),{path:i,pathId:U(i),pathLabel:q(i,this.store.loadNodes().nodes),axes:o,leaf:l,source:"llm",status:f,confidence:c}}async proposePath(e,t,s){let r=s.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),n=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(t,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(r,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
|
|
5
|
-
`),a=await this.callProvider(n),i=V(a);if(!i||!Array.isArray(i.path))return null;let o=/^[a-z0-9][a-z0-9._-]*$/,c=new Map,l=i.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let h=d.trim(),f=ce(h);return h!==f&&c.set(h,f),f}).filter(d=>o.test(d));if(l.length===0)return null;let v={};if(i.proposedAxes&&typeof i.proposedAxes=="object")for(let[d,h]of Object.entries(i.proposedAxes)){if(!h||typeof h!="object")continue;let f=c.get(d)??ce(d);if(!f)continue;let g={};for(let[m,b]of Object.entries(h))typeof b=="string"&&(g[m]=b);!g.name&&d!==f&&(g.name=d.trim()),v[f]=g}let p={};i.leaf&&typeof i.leaf=="object"&&(typeof i.leaf.input=="string"&&(p.input=i.leaf.input),typeof i.leaf.output=="string"&&(p.output=i.leaf.output));let u=typeof i.confidence=="number"?Math.max(0,Math.min(1,i.confidence)):void 0;return{path:l,proposedAxes:v,confidence:u,leaf:p}}commitNewNodes(e,t,s,r,n){this.store.commitNodesAlongPath(e,t,s,n)}async callProvider(e){let t=this.getProvider(),s=new AbortController,r=setTimeout(()=>s.abort(),3e4);try{return(await t.generate([{role:"system",content:"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences."},{role:"user",content:e}],{model:this.classifierModel,maxTokens:800,abortSignal:s.signal,bare:!0})).content||""}finally{clearTimeout(r)}}};function ce(y){let e=y.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function U(y){return ve("sha1").update(y.join("")).digest("hex").slice(0,16)}function q(y,e){return y.map(t=>{let s=e.find(n=>n.id===t);return s&&(s.axes?.name||s.axes?.what)||t}).join(" \u203A ")}function z(y,e){if(y.length===0||e.length===0)return 0;let t=0;for(let r=0;r<Math.min(y.length,e.length)&&y[r]===e[r];r++)t++;if(t===0)return 0;let s=Math.max(y.length,e.length);return t/s}import{readFileSync as N,writeFileSync as x,appendFileSync as we,existsSync as $,mkdirSync as j,readdirSync as E,statSync as ye}from"fs";import{resolve as w,join as be,relative as S,dirname as ke}from"path";he();var le=class{baseDir;rawDir;log;constructor(e=w(process.cwd(),".agentx/wiki"),t=console.error.bind(console,"[wiki]")){this.baseDir=e,this.rawDir=w(e,"raw/entries"),this.log=t,j(this.rawDir,{recursive:!0}),j(w(e,"raw"),{recursive:!0}),this.ensureSchema()}canRead(e,t){return e.access==="public"?!0:t?!!(e.owner===t||e.access==="shared"&&e.sharedWith?.includes(t)):!1}canWrite(e,t){return e.owner===t}addEntry(e){let t=`${e.date}_${e.id}.md`,s=w(this.rawDir,t),r=["---",`id: ${e.id}`,`date: ${e.date}`,`agent: ${e.agentId}`,`source: ${e.source}`];if(e.sourceContext&&r.push(`context: ${e.sourceContext}`),e.meta)for(let[n,a]of Object.entries(e.meta))r.push(`${n}: ${JSON.stringify(a)}`);return r.push("---","",e.content),x(s,r.join(`
|
|
6
|
-
`)),this.appendLog("ingest",`${e.id} from ${e.agentId} via ${e.source}`),t}listEntries(e){if(!$(this.rawDir))return[];let t=E(this.rawDir).filter(r=>r.endsWith(".md")).sort(),s=[];for(let r of t){let n=N(w(this.rawDir,r),"utf-8"),a=this.parseEntry(n,r);a&&(e?.agentId&&a.agentId!==e.agentId||e?.after&&a.date<e.after||e?.before&&a.date>e.before||s.push(a))}return s}parseEntry(e,t){let s=e.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let r=s[1],n=s[2].trim(),a=c=>r.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",i=new Set(["id","date","agent","source","context"]),o={};for(let c of r.split(`
|
|
7
|
-
`)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||i.has(l[1])))try{o[l[1]]=JSON.parse(l[2])}catch{o[l[1]]=l[2].trim()}}return{id:a("id")||t.replace(".md",""),date:a("date"),agentId:a("agent"),source:a("source"),sourceContext:a("context")||void 0,content:n,meta:Object.keys(o).length>0?o:void 0}}writeArticle(e,t,s,r){let n=this.readArticle(e);if(n&&!this.canWrite(n.meta,r))return this.log(`Permission denied: "${r}" cannot write "${e}" (owner: ${n.meta.owner})`),!1;t.type&&!X(t.type)&&(this.log(`Dropping invalid article type "${t.type}" for "${e}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),t={...t,type:void 0});let a=w(this.baseDir,e);n&&this.saveVersion(e,a),j(ke(a),{recursive:!0});let i=["---",`title: "${t.title}"`];t.type&&i.push(`type: ${t.type}`),t.related?.length&&i.push(`related: [${t.related.map(c=>`"${c}"`).join(", ")}]`),i.push(`tags: [${(t.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${t.owner}`,`access: ${t.access}`),t.sharedWith?.length&&i.push(`shared_with: [${t.sharedWith.map(c=>`"${c}"`).join(", ")}]`),i.push(`created: ${t.created}`,`last_updated: ${t.lastUpdated}`,`sources: [${t.sources.map(c=>`"${c}"`).join(", ")}]`),t.graphPath?.length&&i.push(`graph_path: [${t.graphPath.map(c=>`"${c}"`).join(", ")}]`),i.push("---","",s),x(a,i.join(`
|
|
8
|
-
`));let o=n?"update":"create";return this.appendLog(o,`${t.title} [${(t.tags||[]).slice(0,5).join(", ")}] by ${r} at ${e}`),!0}saveVersion(e,t){try{if(!$(t))return;let s=N(t,"utf-8"),r=new Date().toISOString().replace(/[:.]/g,"-"),n=w(this.baseDir,"_versions",e.replace(/\.md$/,""));j(n,{recursive:!0}),x(w(n,`${r}.md`),s)}catch{}}getVersions(e){let t=w(this.baseDir,"_versions",e.replace(/\.md$/,""));if(!$(t))return[];try{return E(t).filter(s=>s.endsWith(".md")).sort().reverse().map(s=>({timestamp:s.replace(/\.md$/,"").replace(/-/g,(r,n)=>n<19?n===10?"T":n===13||n===16?":":"-":r),path:w(t,s)}))}catch{return[]}}restoreVersion(e,t){let r=this.getVersions(e).find(n=>n.timestamp.startsWith(t));if(!r)return!1;try{let n=N(r.path,"utf-8"),a=w(this.baseDir,e);return this.saveVersion(e,a),x(a,n),this.appendLog("restore",`${e} restored to ${t}`),!0}catch{return!1}}readArticle(e){let t=w(this.baseDir,e);if(!$(t))return null;let s=N(t,"utf-8");return this.parseArticle(s,e)}readArticleAs(e,t){let s=this.readArticle(e);return!s||!this.canRead(s.meta,t)?null:s}parseArticle(e,t){let s=e.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let r=s[1],n=s[2].trim(),a=d=>r.match(new RegExp(`^${d}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",i=d=>{let h=r.match(new RegExp(`^${d}:\\s*\\[(.*)\\]$`,"m"));return h?h[1].split(",").map(f=>f.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[]},o=a("type")||a("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(o)?o:void 0,v=i("tags").filter((d,h,f)=>d&&f.indexOf(d)===h),p=i("related"),u=i("graph_path");return{meta:{title:a("title"),type:l,related:p.length?p:void 0,tags:v,owner:a("owner"),access:a("access")||"public",sharedWith:i("shared_with"),created:a("created"),lastUpdated:a("last_updated"),sources:i("sources"),graphPath:u.length?u:void 0},content:n,path:t}}listCache=new Map;listArticles(e){let t=[],s=[];this.walkDir(this.baseDir,(i,o)=>{if(!i.endsWith(".md"))return;let c=S(this.baseDir,i);c.startsWith("raw/")||c.startsWith("_")||(t.push(c),s.push(`${c}:${o?.mtimeMs??"?"}:${o?.size??"?"}`))});let r=s.join("|"),n=this.listCache.get(e);if(n&&n.signature===r)return n.articles.slice();let a=[];for(let i of t){let o=this.readArticle(i);o&&this.canRead(o.meta,e)&&a.push(o)}return this.listCache.set(e,{signature:r,articles:a}),a.slice()}search(e,t,s=10){let r=e.toLowerCase(),n=[];if(this.walkDir(this.baseDir,p=>{if(!p.endsWith(".md"))return;let u=S(this.baseDir,p);if(u.startsWith("raw/")||u.startsWith("_"))return;let d=this.readArticle(u);!d||!this.canRead(d.meta,t)||n.push(d)}),n.length===0)return[];let a=n.map(p=>p.content),i=w(this.baseDir,"_bm25_cache.json"),o=M(a,i),c=O(e,o),l=new Map(c.map(p=>[p.docIndex,p.score]));return n.map((p,u)=>{let d=l.get(u)??0;return p.meta.title.toLowerCase().includes(r)&&(d+=10),p.meta.tags?.some(h=>h.toLowerCase().includes(r))&&(d+=5),{article:p,score:d}}).filter(p=>p.score>0).sort((p,u)=>u.score-p.score).slice(0,s).map(p=>p.article)}async findRelevantReranked(e,t,s=10,r={}){let n=Math.max(s,r.shortlist??Z),a=this.findRelevant(e,t,n);if(a.length<2)return a.slice(0,s);let i=a.map((l,v)=>({id:`c${v}`,title:l.meta.title||`(untitled ${v})`,tags:l.meta.tags,excerpt:l.content})),o=await Y(Q,ee({query:e,candidates:i,excerptChars:r.excerptChars}),te(i),{incumbent:{best:i[0].id},features:{agent:t??"unknown"}});return!o||o.mode!=="active"?a.slice(0,s):se(o.answers,i).ranked.map(l=>a[Number(l.slice(1))]).filter(l=>!!l).slice(0,s)}findRelevant(e,t,s=3,r,n={graph:.6,bm25:.4}){let a=[];if(this.walkDir(this.baseDir,h=>{if(!h.endsWith(".md"))return;let f=S(this.baseDir,h);if(f.startsWith("raw/")||f.startsWith("_"))return;let g=this.readArticle(f);!g||!this.canRead(g.meta,t)||a.push(g)}),a.length===0)return[];let i=a.map(h=>`${h.meta.title} ${(h.meta.tags||[]).join(" ")} ${h.content}`),o=w(this.baseDir,"_bm25_relevance_cache.json"),c=M(i,o),l=O(e,c),v=l.reduce((h,f)=>Math.max(h,f.score),0)||1,p=new Map(l.map(h=>[h.docIndex,h.score/v])),u=!!(r&&r.length>0);return a.map((h,f)=>{let g=p.get(f)??0,m=0;u&&h.meta.graphPath?.length&&(m=z(r,h.meta.graphPath));let b=u?n.graph*m+n.bm25*g:g;return{article:h,score:b}}).filter(h=>h.score>0).sort((h,f)=>f.score-h.score).slice(0,s).map(h=>h.article)}buildContext(e,t=4e3){if(e.length===0)return"";let s=["[Wiki Knowledge]"],r=0;for(let n of e){let a=`
|
|
9
|
-
## ${n.meta.title} [${(n.meta.tags||[]).slice(0,3).join(", ")}]`,i=n.content.length>600?n.content.slice(0,600)+"...":n.content,o=a+`
|
|
10
|
-
`+i;if(r+o.length>t)break;s.push(o),r+=o.length}return s.push(`
|
|
11
|
-
[End Wiki Knowledge]`),s.join(`
|
|
12
|
-
`)}rebuildIndex(){let e=[],t=new Map;this.walkDir(this.baseDir,a=>{if(!a.endsWith(".md"))return;let i=S(this.baseDir,a);if(i.startsWith("raw/")||i.startsWith("_"))return;let o=this.readArticle(i);if(!o)return;let c=o.content.match(/\[\[([^\]]+)\]\]/g)||[];for(let v of c){let p=v.replace(/\[\[|\]\]/g,"");t.set(p,(t.get(p)||0)+1)}let l=[o.meta.title.toLowerCase()];o.meta.tags&&l.push(...o.meta.tags.map(v=>v.toLowerCase())),e.push({path:i,title:o.meta.title,type:o.meta.type,related:o.meta.related,tags:o.meta.tags||[],owner:o.meta.owner,access:o.meta.access,sharedWith:o.meta.sharedWith,aliases:l,backlinks:t.get(o.meta.title)||0,sources:o.meta.sources,lastUpdated:o.meta.lastUpdated})});let s={articles:e,lastRebuilt:new Date().toISOString()};x(w(this.baseDir,"_index.json"),JSON.stringify(s,null,2)),this.writeCatalog(e,s.lastRebuilt);let r=["# Wiki Index","",`Last rebuilt: ${s.lastRebuilt}`,""],n=new Map;for(let a of e){let i=a.access||"public",o=n.get(i)||[];o.push(a),n.set(i,o)}for(let[a,i]of Array.from(n.entries()).sort()){r.push(`## ${a}`,"");for(let o of i.sort((c,l)=>c.title.localeCompare(l.title))){let c=o.type?` [${o.type}]`:"";r.push(`- [${o.title}](${o.path})${c} \u2014 owner: ${o.owner}`)}r.push("")}return x(w(this.baseDir,"WIKI.md"),r.join(`
|
|
13
|
-
`)),this.log(`Index rebuilt: ${e.length} articles`),this.appendLog("rebuild-index",`${e.length} articles indexed`),s}writeCatalog(e,t){let s=["person","project","place","concept","event","decision","pattern","untyped"],r={person:"## People",project:"## Projects",place:"## Places",concept:"## Concepts",event:"## Events",decision:"## Decisions",pattern:"## Patterns",untyped:"## Untyped (needs migration)"},n=new Map;for(let i of e){let o=i.type||"untyped",c=n.get(o)||[];c.push(i),n.set(o,c)}let a=["# Wiki Content Catalog","",`_Last rebuilt: ${t}_`,"","Articles grouped by type. Agentic query walks this file first to pick candidates.",""];for(let i of s){let o=n.get(i);if(!(!o||o.length===0)){a.push(r[i]||`## ${i}`,"");for(let c of o.sort((l,v)=>l.title.localeCompare(v.title))){let l=c.access==="private"?" (private)":c.access==="shared"?" (shared)":"",v=c.related?.length?` \u2192 [[${c.related.slice(0,3).join("]], [[")}]]${c.related.length>3?", \u2026":""}`:"";a.push(`- [${c.title}](${c.path})${l}${v}`)}a.push("")}}x(w(this.baseDir,"_index.md"),a.join(`
|
|
14
|
-
`))}stats(){let e=0,t={},s={},r={};this.walkDir(this.baseDir,a=>{if(!a.endsWith(".md"))return;let i=S(this.baseDir,a);if(i.startsWith("raw/")||i.startsWith("_")||i==="WIKI.md")return;let o=this.readArticle(i);if(o){e++;for(let c of o.meta.tags||[])t[c]=(t[c]||0)+1;s[o.meta.access]=(s[o.meta.access]||0)+1,r[o.meta.owner]=(r[o.meta.owner]||0)+1}});let n=$(this.rawDir)?E(this.rawDir).filter(a=>a.endsWith(".md")).length:0;return{totalArticles:e,totalEntries:n,articlesByType:t,articlesByAccess:s,articlesByOwner:r}}appendLog(e,t){let s=w(this.baseDir,"log.md"),n=`## [${new Date().toISOString().replace("T"," ").slice(0,16)}] ${e} | ${t}
|
|
15
|
-
|
|
16
|
-
`;$(s)||x(s,`# Wiki Log
|
|
17
|
-
|
|
18
|
-
Chronological record of all wiki operations.
|
|
19
|
-
|
|
20
|
-
`),we(s,n)}getLog(e=20){let t=w(this.baseDir,"log.md");return $(t)?N(t,"utf-8").split(/^## /m).filter(n=>n.startsWith("[")).slice(-e).map(n=>n.trim()):[]}ensureSchema(){let e=w(this.baseDir,"_schema.md");if($(e))return;x(e,`# Wiki Schema
|
|
21
|
-
|
|
22
|
-
A personal wiki maintained by LLMs. Karpathy pattern: plain files, aggressive tagging,
|
|
23
|
-
structure emerges from data. The wiki is a compounding artifact.
|
|
24
|
-
|
|
25
|
-
## Structure
|
|
26
|
-
|
|
27
|
-
\`\`\`
|
|
28
|
-
wiki/
|
|
29
|
-
_schema.md # This file
|
|
30
|
-
worldview.md # YOUR mental model \u2014 the LLM reads this during absorb
|
|
31
|
-
raw/entries/ # Immutable raw sources (conversations, imports, anything)
|
|
32
|
-
[LLM-chosen dirs] # Structure emerges from data \u2014 the LLM picks paths
|
|
33
|
-
\`\`\`
|
|
34
|
-
|
|
35
|
-
The LLM decides how to organize articles. You describe YOUR world in worldview.md.
|
|
36
|
-
|
|
37
|
-
## Article Format
|
|
38
|
-
|
|
39
|
-
\`\`\`yaml
|
|
40
|
-
---
|
|
41
|
-
title: "Staging Deployment Process"
|
|
42
|
-
tags: ["deploy", "staging", "devops", "process", "2026-04-06"]
|
|
43
|
-
owner: devops-agent
|
|
44
|
-
access: public
|
|
45
|
-
created: 2026-04-06
|
|
46
|
-
last_updated: 2026-04-06
|
|
47
|
-
sources: ["entry-id-1", "entry-id-2"]
|
|
48
|
-
---
|
|
49
|
-
|
|
50
|
-
Article content with [[wikilinks]] and section tags.
|
|
51
|
-
|
|
52
|
-
## Deploy Steps
|
|
53
|
-
<!-- tags: process, runbook, staging -->
|
|
54
|
-
Content specific to this section...
|
|
55
|
-
\`\`\`
|
|
56
|
-
|
|
57
|
-
## Tags
|
|
58
|
-
|
|
59
|
-
Tags are the primary context-narrowing mechanism. The more tags, the better.
|
|
60
|
-
|
|
61
|
-
Tag aggressively:
|
|
62
|
-
- **Who**: people, agents, teams involved
|
|
63
|
-
- **What**: project, client, topic, technology
|
|
64
|
-
- **When**: dates, periods, milestones
|
|
65
|
-
- **Where**: server, environment, channel
|
|
66
|
-
- **How**: process, decision, pattern
|
|
67
|
-
- **Your terms**: whatever vocabulary makes sense in YOUR world
|
|
68
|
-
|
|
69
|
-
Section tags (\`<!-- tags: ... -->\`) let different parts of an article
|
|
70
|
-
match different queries. A deploy article might have sections tagged
|
|
71
|
-
"runbook" and "incident" separately.
|
|
72
|
-
|
|
73
|
-
## Operations
|
|
74
|
-
|
|
75
|
-
### Absorb
|
|
76
|
-
Read raw entries \u2192 read worldview.md \u2192 tag aggressively \u2192 create/update articles.
|
|
77
|
-
Also identify GAPS: "We mention X but have no article for it."
|
|
78
|
-
|
|
79
|
-
### Query
|
|
80
|
-
Match by tags first \u2192 then keyword within matched articles \u2192 synthesize.
|
|
81
|
-
If agent is working on a specific project, only send content tagged for that project.
|
|
82
|
-
|
|
83
|
-
### Lint
|
|
84
|
-
Check for: orphan articles, broken [[wikilinks]], untagged articles,
|
|
85
|
-
articles over 100 lines that should split, mentioned-but-missing topics.
|
|
86
|
-
|
|
87
|
-
## Worldview
|
|
88
|
-
|
|
89
|
-
Edit \`worldview.md\` to describe YOUR world. This is not a schema \u2014 it's your
|
|
90
|
-
mental model. The LLM reads it during absorb to understand where things go.
|
|
91
|
-
|
|
92
|
-
Example worldview.md:
|
|
93
|
-
\`\`\`
|
|
94
|
-
I'm the founder of Acme Corp.
|
|
95
|
-
We build software products.
|
|
96
|
-
Our agents: Marketing Bot, DevOps Bot, Coordinator.
|
|
97
|
-
Clients: ClientA (enterprise), ClientB (startup).
|
|
98
|
-
Infrastructure: local dev machine, cloud server.
|
|
99
|
-
We use GitLab for version control.
|
|
100
|
-
\`\`\`
|
|
101
|
-
`),this.log("Created _schema.md")}extractWikilinks(e){return(e.match(/\[\[([^\]]+)\]\]/g)||[]).map(s=>s.replace(/\[\[|\]\]/g,""))}buildBacklinks(){let e={};return this.walkDir(this.baseDir,t=>{if(!t.endsWith(".md"))return;let s=S(this.baseDir,t);if(s.startsWith("raw/")||s.startsWith("_")||s==="WIKI.md"||s==="log.md")return;let r=N(t,"utf-8"),n=this.extractWikilinks(r);for(let a of n)e[a]||(e[a]=[]),e[a].push(s)}),x(w(this.baseDir,"_backlinks.json"),JSON.stringify(e,null,2)),e}getBacklinks(e){let t=w(this.baseDir,"_backlinks.json");if(!$(t))return[];try{return JSON.parse(N(t,"utf-8"))[e]||[]}catch{return[]}}findByTags(e,t,s=10){let r=e.map(a=>a.toLowerCase()),n=[];return this.walkDir(this.baseDir,a=>{if(!a.endsWith(".md"))return;let i=S(this.baseDir,a);if(i.startsWith("raw/")||i.startsWith("_"))return;let o=this.readArticle(i);if(!o||t&&!this.canRead(o.meta,t))return;let c=(o.meta.tags||[]).map(u=>u.toLowerCase()),l=(o.content.match(/<!--\s*tags?:\s*([^>]+)\s*-->/gi)||[]).flatMap(u=>u.replace(/<!--\s*tags?:\s*|\s*-->/gi,"").split(",").map(d=>d.trim().toLowerCase())),v=[...c,...l],p=r.filter(u=>v.includes(u)).length;p>0&&n.push({article:o,score:p})}),n.sort((a,i)=>i.score-a.score).slice(0,s).map(a=>a.article)}getAllTags(){let e=new Map;return this.walkDir(this.baseDir,t=>{if(!t.endsWith(".md"))return;let s=S(this.baseDir,t);if(s.startsWith("raw/")||s.startsWith("_"))return;let r=this.readArticle(s);if(r?.meta.tags)for(let n of r.meta.tags)e.set(n,(e.get(n)||0)+1)}),e}getWorldview(){let e=w(this.baseDir,"worldview.md");return $(e)?N(e,"utf-8"):null}setWorldview(e){x(w(this.baseDir,"worldview.md"),e),this.appendLog("worldview","Updated worldview")}lint(){let e=[],t=new Set,s=new Map,r=new Map;this.walkDir(this.baseDir,a=>{if(!a.endsWith(".md"))return;let i=S(this.baseDir,a);if(i.startsWith("raw/")||i.startsWith("_")||i==="WIKI.md"||i==="log.md")return;let o=this.readArticle(i);if(!o)return;t.add(o.meta.title),r.set(o.meta.title,i);let c=this.extractWikilinks(o.content);s.set(i,c);let l=o.content.split(`
|
|
102
|
-
`).length;l>100&&e.push({type:"bloated",article:i,message:`${l} lines \u2014 consider splitting`}),o.meta.sources?.length||e.push({type:"unsourced",article:i,message:"No sources listed in frontmatter"}),l<10&&o.content.trim().length<100&&e.push({type:"stub",article:i,message:"Very short article \u2014 needs enrichment"})});for(let[a,i]of s)for(let o of i)t.has(o)||e.push({type:"broken-link",article:a,message:`[[${o}]] \u2014 target article not found`});let n=this.buildBacklinks();for(let[a,i]of r)(!n[a]||n[a].length===0)&&e.push({type:"orphan",article:i,message:`No other articles link to "${a}"`});return this.appendLog("lint",`Found ${e.length} issues`),e}getUnabsorbedEntries(){let e=new Set;return this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let r=S(this.baseDir,s);if(r.startsWith("raw/")||r.startsWith("_"))return;let n=this.readArticle(r);if(n?.meta.sources)for(let a of n.meta.sources)e.add(a)}),this.listEntries().filter(s=>!e.has(s.id))}buildAbsorbPrompt(e=20){let t=this.getUnabsorbedEntries().slice(0,e);if(t.length===0)return null;let s=t.map(r=>`[${r.date} ${r.agentId} via ${r.source}] ${r.content.slice(0,200)}`).join(`
|
|
103
|
-
|
|
104
|
-
`);return`/wiki absorb
|
|
105
|
-
|
|
106
|
-
There are ${t.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
|
|
107
|
-
|
|
108
|
-
${s}`}walkDir(e,t){if($(e))for(let s of E(e)){let r=be(e,s),n=ye(r);n.isDirectory()?this.walkDir(r,t):t(r,n)}}};export{A as a,J as b,H as c,q as d,le as e};
|
|
109
|
-
//# sourceMappingURL=chunk-535MLOSB.js.map
|