chain-insights 0.19.0 → 0.22.2

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.
Files changed (138) hide show
  1. package/README.md +44 -121
  2. package/bin/cli.js +4 -4
  3. package/bin/install.cjs +137 -113
  4. package/bin/mcp-proxy.cjs +7 -5
  5. package/dist/{action-log-Dfe88TwV.cjs → action-log-HniMMF7f.cjs} +1 -1
  6. package/dist/action-log-diTHyMbV.mjs.map +1 -1
  7. package/dist/active-BQopLul8.mjs.map +1 -1
  8. package/dist/{active-Bj6dohpc.cjs → active-Bc13hJIm.cjs} +1 -1
  9. package/dist/{app-CJwx_2Rr.mjs → app-7NRCqx_Q.mjs} +2 -2
  10. package/dist/app-7NRCqx_Q.mjs.map +1 -0
  11. package/dist/{app-D4Cm69ob.cjs → app-l9JE6bt3.cjs} +5 -5
  12. package/dist/{artifact-server-sJBFGcum.cjs → artifact-server-CH-asxF5.cjs} +3 -2
  13. package/dist/{artifact-server-D1D-_t5l.mjs → artifact-server-DoxJr0z8.mjs} +4 -3
  14. package/dist/artifact-server-DoxJr0z8.mjs.map +1 -0
  15. package/dist/{capabilities-CxvK7LKZ.mjs → capabilities-BZI6qROg.mjs} +2 -2
  16. package/dist/capabilities-BZI6qROg.mjs.map +1 -0
  17. package/dist/{capabilities-CZYijWbg.cjs → capabilities-CPcrxodx.cjs} +2 -2
  18. package/dist/cli.cjs +42 -216
  19. package/dist/cli.mjs +36 -210
  20. package/dist/cli.mjs.map +1 -1
  21. package/dist/{client-Bjxo7AEa.cjs → client-CqAzD519.cjs} +4 -4
  22. package/dist/{client-i3WtsKA4.mjs → client-D4aM4bzP.mjs} +4 -4
  23. package/dist/client-D4aM4bzP.mjs.map +1 -0
  24. package/dist/{config-DE0dUT3P.cjs → config-BVFf3v8-.cjs} +2 -2
  25. package/dist/{config-DA6KRx60.mjs → config-CnNMdt4M.mjs} +2 -2
  26. package/dist/config-CnNMdt4M.mjs.map +1 -0
  27. package/dist/graph-normalizer-BA3Rbd6l.mjs.map +1 -1
  28. package/dist/graph-reports-B6yoYbPq.mjs.map +1 -1
  29. package/dist/{graph-reports-DSHSp5HL.cjs → graph-reports-_gqzxvvs.cjs} +2 -2
  30. package/dist/{html-generator-Ui29DLSD.cjs → html-generator-B9f_GIi2.cjs} +4 -3
  31. package/dist/{html-generator-ClysZjfY.mjs → html-generator-D2BDzLED.mjs} +3 -2
  32. package/dist/{html-generator-ClysZjfY.mjs.map → html-generator-D2BDzLED.mjs.map} +1 -1
  33. package/dist/index.cjs +9 -9
  34. package/dist/index.d.cts +3 -0
  35. package/dist/index.d.cts.map +1 -1
  36. package/dist/index.d.mts +3 -0
  37. package/dist/index.d.mts.map +1 -1
  38. package/dist/index.mjs +9 -9
  39. package/dist/{init-BT3STWBv.mjs → init-Djhml4ih.mjs} +3 -3
  40. package/dist/init-Djhml4ih.mjs.map +1 -0
  41. package/dist/{init-BR4SRTAY.cjs → init-DvrKxK15.cjs} +3 -3
  42. package/dist/limits-D3Mn-gig.mjs.map +1 -1
  43. package/dist/mcp-endpoint-DbWtLcba.mjs.map +1 -1
  44. package/dist/mcp-proxy.cjs +19 -18
  45. package/dist/mcp-proxy.d.cts.map +1 -1
  46. package/dist/mcp-proxy.d.mts.map +1 -1
  47. package/dist/mcp-proxy.mjs +13 -12
  48. package/dist/mcp-proxy.mjs.map +1 -1
  49. package/dist/{merge-CJRZpuZ4.mjs → merge-BZw-pMPN.mjs} +2 -2
  50. package/dist/merge-BZw-pMPN.mjs.map +1 -0
  51. package/dist/{merge-B_5kxbGv.cjs → merge-C52eaAGU.cjs} +1 -1
  52. package/dist/{output-root-C1PFNCqb.cjs → output-root-BewoQaTx.cjs} +2 -2
  53. package/dist/{public-tools-CgiKgYgf.cjs → public-tools-BFs_7U_Z.cjs} +8 -7
  54. package/dist/{public-tools-B9_wXs2o.mjs → public-tools-BjqZGGAC.mjs} +7 -6
  55. package/dist/public-tools-BjqZGGAC.mjs.map +1 -0
  56. package/dist/{rolldown-runtime-DakpK96I.cjs → rolldown-runtime-C0BPl7ul.cjs} +1 -1
  57. package/dist/{schema-DF0aOXII.cjs → schema-BpeV3xDV.cjs} +5 -2
  58. package/dist/{schema-0BVyF-aL.mjs → schema-DOJA2nNi.mjs} +5 -2
  59. package/dist/schema-DOJA2nNi.mjs.map +1 -0
  60. package/dist/{schema-cache-DwDvPy4e.mjs → schema-cache-DJdU4MIP.mjs} +2 -2
  61. package/dist/{schema-cache-DwDvPy4e.mjs.map → schema-cache-DJdU4MIP.mjs.map} +1 -1
  62. package/dist/{schema-cache-CX0r2UQp.cjs → schema-cache-n7Gbhvsj.cjs} +2 -2
  63. package/dist/{server-ta1oyJ2a.cjs → server-CmvzYu7v.cjs} +4 -3
  64. package/dist/{server-BXj6BRI1.mjs → server-mDSRgk1X.mjs} +4 -3
  65. package/dist/server-mDSRgk1X.mjs.map +1 -0
  66. package/dist/tool-visibility-C0ALejXI.mjs.map +1 -1
  67. package/dist/{tool-visibility-DMIEexib.cjs → tool-visibility-DZBAP62b.cjs} +1 -1
  68. package/dist/{tools-CWwX4yth.mjs → tools-BKLnlBG1.mjs} +8 -6
  69. package/dist/tools-BKLnlBG1.mjs.map +1 -0
  70. package/dist/{tools-BPfUpCUR.cjs → tools-lPY6k-vJ.cjs} +8 -6
  71. package/dist/{topup-server-VGl8-Fz5.cjs → topup-server-DAqmAuu1.cjs} +23 -21
  72. package/dist/{topup-server-D2X7My7i.mjs → topup-server-rqI7bqem.mjs} +23 -21
  73. package/dist/topup-server-rqI7bqem.mjs.map +1 -0
  74. package/dist/update-CJUfGCxs.mjs.map +1 -1
  75. package/dist/{usage-status-H1xgCu99.cjs → usage-status-BdwwgYsu.cjs} +2 -2
  76. package/dist/{usage-status-D2uosC7s.mjs → usage-status-CHiOPA-2.mjs} +2 -2
  77. package/dist/usage-status-CHiOPA-2.mjs.map +1 -0
  78. package/dist/version-BA3J8hu4.mjs.map +1 -1
  79. package/dist/{viz-HSwLcKr6.cjs → viz-BJ_kyRjI.cjs} +7 -5
  80. package/dist/{viz-Cq1jSWSH.mjs → viz-Uh_EF-qB.mjs} +6 -4
  81. package/dist/viz-Uh_EF-qB.mjs.map +1 -0
  82. package/dist/{wallet-C2yVjcSY.cjs → wallet-BEvHrHi3.cjs} +3 -2
  83. package/dist/{wallet-BrTTnf7w.mjs → wallet-fMbhvKXT.mjs} +3 -2
  84. package/dist/wallet-fMbhvKXT.mjs.map +1 -0
  85. package/docs/architecture.md +18 -18
  86. package/docs/debugging.md +2 -42
  87. package/docs/development.md +0 -27
  88. package/docs/graph-query-compatibility.md +66 -57
  89. package/docs/graph-tools.md +6 -6
  90. package/docs/investigation-workspaces.md +0 -35
  91. package/docs/mcp-proxy.md +8 -9
  92. package/docs/search-limits.md +8 -8
  93. package/docs/stability.md +4 -5
  94. package/package.json +1 -5
  95. package/skills/chain-insights-cypher/SKILL.md +7 -7
  96. package/skills/chain-insights-cypher/agents/openai.yaml +3 -3
  97. package/skills/chain-insights-schema-bittensor/SKILL.md +26 -26
  98. package/skills/chain-insights-schema-evm/SKILL.md +37 -37
  99. package/dist/app-CJwx_2Rr.mjs.map +0 -1
  100. package/dist/artifact-server-D1D-_t5l.mjs.map +0 -1
  101. package/dist/capabilities-CxvK7LKZ.mjs.map +0 -1
  102. package/dist/cases-C1XewLdx.mjs +0 -155
  103. package/dist/cases-C1XewLdx.mjs.map +0 -1
  104. package/dist/cases-CVtc7Rf8.cjs +0 -160
  105. package/dist/client-i3WtsKA4.mjs.map +0 -1
  106. package/dist/config-CwIb-tav.mjs +0 -33
  107. package/dist/config-CwIb-tav.mjs.map +0 -1
  108. package/dist/config-Cy-qzx4W.cjs +0 -33
  109. package/dist/config-DA6KRx60.mjs.map +0 -1
  110. package/dist/init-9jY5rCcH.cjs +0 -24
  111. package/dist/init-BT3STWBv.mjs.map +0 -1
  112. package/dist/init-BiRfMQcA.mjs +0 -26
  113. package/dist/init-BiRfMQcA.mjs.map +0 -1
  114. package/dist/lock-Cs-a3Ng1.cjs +0 -38
  115. package/dist/lock-D_sWGS7W.mjs +0 -40
  116. package/dist/lock-D_sWGS7W.mjs.map +0 -1
  117. package/dist/merge-CJRZpuZ4.mjs.map +0 -1
  118. package/dist/paths-CffVTUCv.cjs +0 -31
  119. package/dist/paths-_3isihzD.mjs +0 -21
  120. package/dist/paths-_3isihzD.mjs.map +0 -1
  121. package/dist/public-tools-B9_wXs2o.mjs.map +0 -1
  122. package/dist/render-TmSq0f4f.cjs +0 -207
  123. package/dist/render-mxE0Tdsf.mjs +0 -206
  124. package/dist/render-mxE0Tdsf.mjs.map +0 -1
  125. package/dist/report-BFXFrJmj.mjs +0 -36
  126. package/dist/report-BFXFrJmj.mjs.map +0 -1
  127. package/dist/report-BwKQqOCR.cjs +0 -36
  128. package/dist/runner-CSss8Hvy.mjs +0 -33
  129. package/dist/runner-CSss8Hvy.mjs.map +0 -1
  130. package/dist/runner-aErdz2zn.cjs +0 -31
  131. package/dist/schema-0BVyF-aL.mjs.map +0 -1
  132. package/dist/server-BXj6BRI1.mjs.map +0 -1
  133. package/dist/tools-CWwX4yth.mjs.map +0 -1
  134. package/dist/topup-server-D2X7My7i.mjs.map +0 -1
  135. package/dist/usage-status-D2uosC7s.mjs.map +0 -1
  136. package/dist/viz-Cq1jSWSH.mjs.map +0 -1
  137. package/dist/wallet-BrTTnf7w.mjs.map +0 -1
  138. package/docs/monitoring.md +0 -277
@@ -0,0 +1 @@
1
+ {"version":3,"file":"viz-Uh_EF-qB.mjs","names":[],"sources":["../src/viz/graph-model.ts","../src/viz/data-extractor.ts","../src/viz/index.ts"],"sourcesContent":["import * as z from 'zod'\nimport { LIMIT_SPECS, resolveLimit } from '../config/limits.js'\n\nexport const EntityType = z.enum(['eoa', 'contract', 'exchange', 'mixer', 'hub', 'unknown'])\nexport type EntityType = z.infer<typeof EntityType>\n\nexport const RiskLevel = z.enum(['low', 'medium', 'high', 'critical', 'unscored', 'unknown'])\nexport type RiskLevel = z.infer<typeof RiskLevel>\n\nexport const GraphNode = z.object({\n id: z.string().min(1),\n label: z.string().optional(),\n entityType: EntityType.default('unknown'),\n riskLevel: RiskLevel.default('unknown'),\n totalIn: z.number().default(0),\n totalOut: z.number().default(0),\n txCount: z.number().int().default(0),\n firstSeen: z.string().optional(),\n lastSeen: z.string().optional(),\n})\nexport type GraphNode = z.infer<typeof GraphNode>\n\nexport const GraphEdge = z.object({\n source: z.string().min(1),\n target: z.string().min(1),\n value: z.number(),\n // Distinct visual layer for money-trail edges (MONEY_TRAIL / TRAIL_ENDS_AT);\n // absent-layer callers never set this and keep rendering as flows_to.\n edgeType: z.string().default('flows_to'),\n txHash: z.string().optional(),\n blockNumber: z.number().int().optional(),\n timestamp: z.string().optional(),\n})\nexport type GraphEdge = z.infer<typeof GraphEdge>\n\nexport const GraphData = z.object({\n nodes: z.array(GraphNode),\n edges: z.array(GraphEdge),\n metadata: z.object({\n title: z.string().default('Money Flow'),\n generatedAt: z.string(),\n truncated: z.boolean().default(false),\n totalNodes: z.number().int().optional(),\n hiddenNodes: z.number().int().optional(),\n }),\n})\nexport type GraphData = z.infer<typeof GraphData>\n\n// Built-in default; ceiling in config/limits.ts. `maxNodes` lets a caller\n// render a denser view of a case they are actively working without changing\n// what any other view produces.\nconst MAX_NODES = LIMIT_SPECS.viz_max_nodes.builtin\n\nexport function truncateGraph(data: GraphData, maxNodes: number = MAX_NODES): GraphData {\n const cap = resolveLimit('viz_max_nodes', maxNodes === MAX_NODES ? null : maxNodes)\n if (data.nodes.length <= cap) return data\n const sorted = [...data.nodes].sort((a, b) => b.totalIn + b.totalOut - (a.totalIn + a.totalOut))\n const kept = sorted.slice(0, cap)\n const keptIds = new Set(kept.map((n) => n.id))\n const filteredEdges = data.edges.filter((e) => keptIds.has(e.source) && keptIds.has(e.target))\n return {\n nodes: kept,\n edges: filteredEdges,\n metadata: {\n ...data.metadata,\n truncated: true,\n totalNodes: data.nodes.length,\n hiddenNodes: data.nodes.length - cap,\n },\n }\n}\n","import { readFile } from 'node:fs/promises'\nimport { GraphData, GraphNode, GraphEdge } from './graph-model.js'\n\n/**\n * Extracts all items from ```json code blocks in a markdown string.\n * If the parsed value is an array, spreads all items.\n * If the parsed value has 'nodes' and 'edges', wraps it as a single item.\n * Returns empty array if no JSON blocks found or parsing fails.\n */\nexport function parseEvidenceJson(markdown: string): unknown[] {\n const results: unknown[] = []\n const re = /```json\\s*\\n([\\s\\S]*?)```/g\n let match: RegExpExecArray | null\n while ((match = re.exec(markdown)) !== null) {\n const raw = match[1]\n if (!raw) continue\n try {\n const parsed: unknown = JSON.parse(raw)\n if (Array.isArray(parsed)) {\n results.push(...parsed)\n } else if (\n parsed !== null &&\n typeof parsed === 'object' &&\n 'nodes' in (parsed as object) &&\n 'edges' in (parsed as object)\n ) {\n // Full GraphData object embedded in evidence\n results.push(parsed)\n }\n // Ignore other object types\n } catch {\n // Malformed JSON in evidence — skip gracefully (T-04-06: no crash)\n }\n }\n if (results.length > 0) return results\n\n const rawJson = extractEmbeddedJson(markdown)\n if (rawJson) {\n try {\n const parsed: unknown = JSON.parse(rawJson)\n if (Array.isArray(parsed)) return parsed\n if (parsed !== null && typeof parsed === 'object') return [parsed]\n } catch {\n // Ignore non-JSON evidence bodies.\n }\n }\n return results\n}\n\nfunction extractEmbeddedJson(text: string): string | null {\n const trimmed = text.trim()\n const start = [...trimmed]\n .map((char, index) => (char === '{' || char === '[' ? index : -1))\n .find((index) => index >= 0)\n if (start === undefined) return null\n return trimmed.slice(start)\n}\n\ntype SimpleTx = {\n from: string\n to: string\n value: number\n txHash?: string\n blockNumber?: number\n timestamp?: string\n}\n\ntype CompactEvidence = {\n schema?: string\n outgoing_flows?: Array<{\n src?: string\n dst?: string\n amount_usd_sum?: number\n tx_count?: number\n first_tx_id?: string\n }>\n}\n\nfunction isSimpleTx(item: unknown): item is SimpleTx {\n return (\n item !== null &&\n typeof item === 'object' &&\n 'from' in (item as object) &&\n 'to' in (item as object) &&\n 'value' in (item as object)\n )\n}\n\nfunction isGraphDataLike(input: unknown): input is { nodes: unknown[]; edges: unknown[] } {\n return (\n input !== null &&\n typeof input === 'object' &&\n Array.isArray((input as Record<string, unknown>)['nodes']) &&\n Array.isArray((input as Record<string, unknown>)['edges'])\n )\n}\n\nfunction compactEvidenceToSimpleTxs(item: unknown): SimpleTx[] {\n const compact = item as CompactEvidence\n if (\n !compact ||\n typeof compact !== 'object' ||\n compact.schema !== 'chain-insights.compact_evidence.v1' ||\n !Array.isArray(compact.outgoing_flows)\n ) {\n return []\n }\n\n return compact.outgoing_flows\n .filter(\n (flow) =>\n typeof flow.src === 'string' &&\n typeof flow.dst === 'string' &&\n typeof flow.amount_usd_sum === 'number'\n )\n .map((flow) => ({\n from: flow.src!,\n to: flow.dst!,\n value: flow.amount_usd_sum!,\n txHash: flow.first_tx_id,\n }))\n}\n\n/**\n * Converts simple [{from, to, value}] transaction arrays into graph nodes.\n * Computes totalIn, totalOut, txCount per node from edges.\n */\nfunction buildGraphFromSimpleTxs(items: SimpleTx[]): { nodes: GraphNode[]; edges: GraphEdge[] } {\n // Build edges first\n const edges: GraphEdge[] = items.map((tx) =>\n GraphEdge.parse({\n source: tx.from,\n target: tx.to,\n value: tx.value,\n txHash: tx.txHash,\n blockNumber: tx.blockNumber,\n timestamp: tx.timestamp,\n })\n )\n\n // Collect unique addresses\n const addresses = new Set<string>()\n for (const tx of items) {\n addresses.add(tx.from)\n addresses.add(tx.to)\n }\n\n // Compute totals per address\n const totals: Record<string, { totalIn: number; totalOut: number; txCount: number }> = {}\n for (const addr of addresses) {\n totals[addr] = { totalIn: 0, totalOut: 0, txCount: 0 }\n }\n for (const tx of items) {\n const out = totals[tx.from]\n const inp = totals[tx.to]\n if (out) {\n out.totalOut += tx.value\n out.txCount += 1\n }\n if (inp) {\n inp.totalIn += tx.value\n inp.txCount += 1\n }\n }\n\n const nodes: GraphNode[] = [...addresses].map((addr) =>\n GraphNode.parse({\n id: addr,\n entityType: 'unknown',\n riskLevel: 'unknown',\n totalIn: totals[addr]?.totalIn ?? 0,\n totalOut: totals[addr]?.totalOut ?? 0,\n txCount: totals[addr]?.txCount ?? 0,\n })\n )\n\n return { nodes, edges }\n}\n\n/**\n * Handles two input formats:\n * 1. Full GraphData object (has nodes + edges) — parse with Zod\n * 2. Array of {from, to, value, ...} transaction objects — auto-derive nodes\n *\n * Throws \"Invalid transaction data\" for any other input.\n */\nexport function extractGraphFromJson(input: unknown): GraphData {\n if (isGraphDataLike(input)) {\n // Full GraphData: parse and validate through Zod\n return GraphData.parse(input)\n }\n\n if (Array.isArray(input)) {\n const simpleTxs: SimpleTx[] = []\n for (const item of input) {\n if (isSimpleTx(item)) {\n simpleTxs.push(item)\n } else {\n simpleTxs.push(...compactEvidenceToSimpleTxs(item))\n }\n }\n const { nodes, edges } = buildGraphFromSimpleTxs(simpleTxs)\n return GraphData.parse({\n nodes,\n edges,\n metadata: {\n title: 'Money Flow',\n generatedAt: new Date().toISOString(),\n },\n })\n }\n\n throw new Error(\n 'Invalid transaction data. The input file must contain a JSON array of transaction objects with `from`, `to`, and `value` fields.'\n )\n}\n\n/**\n * Merges two sets of nodes, deduplicating by id.\n * For duplicate nodes, sums totalIn, totalOut, txCount; keeps earliest firstSeen, latest lastSeen.\n */\nfunction mergeNodes(existing: GraphNode[], incoming: GraphNode[]): GraphNode[] {\n const map = new Map<string, GraphNode>()\n for (const node of existing) {\n map.set(node.id, { ...node })\n }\n for (const node of incoming) {\n const prev = map.get(node.id)\n if (prev) {\n map.set(node.id, {\n ...prev,\n totalIn: prev.totalIn + node.totalIn,\n totalOut: prev.totalOut + node.totalOut,\n txCount: prev.txCount + node.txCount,\n firstSeen: pickEarlier(prev.firstSeen, node.firstSeen),\n lastSeen: pickLater(prev.lastSeen, node.lastSeen),\n })\n } else {\n map.set(node.id, { ...node })\n }\n }\n return [...map.values()]\n}\n\nfunction pickEarlier(a: string | undefined, b: string | undefined): string | undefined {\n if (!a) return b\n if (!b) return a\n return a < b ? a : b\n}\n\nfunction pickLater(a: string | undefined, b: string | undefined): string | undefined {\n if (!a) return b\n if (!b) return a\n return a > b ? a : b\n}\n\n/**\n * Aggregates edges: for duplicate (source, target) pairs, sums value; keeps last txHash/timestamp.\n */\nfunction aggregateEdges(edges: GraphEdge[]): GraphEdge[] {\n const map = new Map<string, GraphEdge>()\n for (const edge of edges) {\n const key = `${edge.source}::${edge.target}`\n const prev = map.get(key)\n if (prev) {\n map.set(key, { ...edge, value: prev.value + edge.value })\n } else {\n map.set(key, { ...edge })\n }\n }\n return [...map.values()]\n}\n\n/**\n * Reads evidence files from a case directory, extracts JSON transaction data\n * from markdown code blocks, enriches nodes with entity types from dossiers,\n * and returns a merged GraphData.\n */\nexport const DataExtractor = {\n extractGraphFromJson,\n parseEvidenceJson,\n}\n","export {\n GraphData,\n GraphNode,\n GraphEdge,\n EntityType,\n RiskLevel,\n truncateGraph,\n} from './graph-model.js'\nexport type {\n GraphData as GraphDataType,\n GraphNode as GraphNodeType,\n GraphEdge as GraphEdgeType,\n} from './graph-model.js'\nexport { generateHtml, writeVizHtml, transformToGraphHtml } from './html-generator.js'\nexport { DataExtractor, extractGraphFromJson } from './data-extractor.js'\n\nimport { readFile } from 'node:fs/promises'\nimport path from 'node:path'\nimport { truncateGraph } from './graph-model.js'\nimport { extractGraphFromJson } from './data-extractor.js'\nimport { generateHtml, writeVizHtml } from './html-generator.js'\nimport { workspaceOutputPaths } from '../workspace/output-root.js'\n\nfunction sanitizeSourceId(sourceId: string): string {\n if (!/^[A-Za-z0-9._-]+$/.test(sourceId) || sourceId.includes('..')) {\n throw new Error(`Invalid visualization source ID: ${sourceId}`)\n }\n return sourceId\n}\n\nexport async function generateVisualization(opts: {\n sourceId?: string\n dataFile?: string\n}): Promise<{ vizId: string; htmlPath: string }> {\n let rawData: unknown\n let vizId: string\n let title: string\n\n if (opts.dataFile) {\n const content = await readFile(opts.dataFile, 'utf-8')\n let parsed: unknown\n try {\n parsed = JSON.parse(content)\n } catch {\n throw new Error(\n 'Invalid transaction data. The input file must contain a JSON array of transaction objects with `from`, `to`, and `value` fields.'\n )\n }\n rawData = extractGraphFromJson(parsed)\n vizId = `adhoc_${Date.now()}`\n title = 'Ad-hoc Visualization'\n } else if (opts.sourceId) {\n const sourceId = sanitizeSourceId(opts.sourceId)\n const paths = workspaceOutputPaths()\n const graphPath = path.join(paths.reportGraphsRoot, `${sourceId}.graph.json`)\n const content = await readFile(graphPath, 'utf-8')\n rawData = JSON.parse(content) as unknown\n vizId = sourceId\n title = `${sourceId} - Workspace Graph`\n } else {\n throw new Error('Provide either a visualization source ID or --data <file.json>')\n }\n\n const data = truncateGraph(rawData as Parameters<typeof truncateGraph>[0])\n const html = generateHtml(data, title)\n const htmlPath = await writeVizHtml(vizId, html)\n\n return { vizId, htmlPath }\n}\n"],"mappings":";;;;;;;;AAGA,MAAa,aAAa,EAAE,KAAK;CAAC;CAAO;CAAY;CAAY;CAAS;CAAO;AAAS,CAAC;AAG3F,MAAa,YAAY,EAAE,KAAK;CAAC;CAAO;CAAU;CAAQ;CAAY;CAAY;AAAS,CAAC;AAG5F,MAAa,YAAY,EAAE,OAAO;CAChC,IAAI,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CACpB,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,YAAY,WAAW,QAAQ,SAAS;CACxC,WAAW,UAAU,QAAQ,SAAS;CACtC,SAAS,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC;CAC7B,UAAU,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC;CAC9B,SAAS,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC;CACnC,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,UAAU,EAAE,OAAO,CAAC,CAAC,SAAS;AAChC,CAAC;AAGD,MAAa,YAAY,EAAE,OAAO;CAChC,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CACxB,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CAC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,IAAI;EAC1B,QAAQ;CACV,OAAO,IAAI,KAAK,UAAU;EACxB,MAAM,WAAW,iBAAiB,KAAK,QAAQ;EAC/C,MAAM,QAAQ,qBAAqB;EACnC,MAAM,YAAY,KAAK,KAAK,MAAM,kBAAkB,GAAG,SAAS,YAAY;EAC5E,MAAM,UAAU,MAAM,SAAS,WAAW,OAAO;EACjD,UAAU,KAAK,MAAM,OAAO;EAC5B,QAAQ;EACR,QAAQ,GAAG,SAAS;CACtB,OACE,MAAM,IAAI,MAAM,gEAAgE;CAGlF,MAAM,OAAO,cAAc,OAA8C;CACzE,MAAM,OAAO,aAAa,MAAM,KAAK;CACrC,MAAM,WAAW,MAAM,aAAa,OAAO,IAAI;CAE/C,OAAO;EAAE;EAAO;CAAS;AAC3B"}
@@ -1,4 +1,4 @@
1
- const require_rolldown_runtime = require("./rolldown-runtime-DakpK96I.cjs");
1
+ const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
2
  let node_path = require("node:path");
3
3
  node_path = require_rolldown_runtime.__toESM(node_path, 1);
4
4
  let node_fs_promises = require("node:fs/promises");
@@ -80,7 +80,8 @@ async function backupExistingWallet() {
80
80
  if (err.code === "ENOENT") return;
81
81
  throw err;
82
82
  }
83
- await (0, node_fs_promises.writeFile)(`${p}.bak-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`, raw, { mode: 384 });
83
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
84
+ await (0, node_fs_promises.writeFile)(`${p}.bak-${stamp}`, raw, { mode: 384 });
84
85
  }
85
86
  /**
86
87
  * Encrypts and stores a private key, refusing to overwrite an existing wallet
@@ -77,7 +77,8 @@ async function backupExistingWallet() {
77
77
  if (err.code === "ENOENT") return;
78
78
  throw err;
79
79
  }
80
- await writeFile(`${p}.bak-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`, raw, { mode: 384 });
80
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
81
+ await writeFile(`${p}.bak-${stamp}`, raw, { mode: 384 });
81
82
  }
82
83
  /**
83
84
  * Encrypts and stores a private key, refusing to overwrite an existing wallet
@@ -142,4 +143,4 @@ async function isWalletConfigured() {
142
143
  //#endregion
143
144
  export { setWalletPrivateKey as a, normalizeWalletPrivateKey as i, encryptKey as n, walletAddressFromPrivateKey as o, isWalletConfigured as r, wallet_exports as s, decryptKey as t };
144
145
 
145
- //# sourceMappingURL=wallet-BrTTnf7w.mjs.map
146
+ //# sourceMappingURL=wallet-fMbhvKXT.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wallet-fMbhvKXT.mjs","names":["nodeErr"],"sources":["../src/wallet/index.ts"],"sourcesContent":["import crypto from 'node:crypto'\nimport os from 'node:os'\nimport path from 'node:path'\nimport { readFile, writeFile, mkdir, stat } from 'node:fs/promises'\nimport type { Address, Hex } from 'viem'\nimport { privateKeyToAccount } from 'viem/accounts'\n\n// Path derived at call time so tests can override HOME.\nexport function walletPath(): string {\n return path.join(os.homedir(), '.chain-insights', 'wallet.json')\n}\n\n// Derive a 32-byte key from the machine identity (hostname + username) and a\n// random per-wallet salt. The salt prevents precomputation attacks across wallets.\nfunction deriveKey(salt: Buffer): Buffer {\n return crypto.scryptSync(`${os.hostname()}:${os.userInfo().username}`, salt, 32)\n}\n\ninterface WalletData {\n salt: string\n iv: string\n tag: string\n data: string\n}\n\nexport function normalizeWalletPrivateKey(value: string): Hex {\n if (!/^0x[0-9a-fA-F]{64}$/.test(value)) {\n throw new Error('Stored wallet private key is not a valid 0x-prefixed EVM private key')\n }\n return value as Hex\n}\n\nexport function walletAddressFromPrivateKey(privateKey: string): Address {\n return privateKeyToAccount(normalizeWalletPrivateKey(privateKey)).address\n}\n\n/**\n * Encrypts a private key and writes it to ~/.chain-insights/wallet.json.\n * Uses AES-256-GCM with a machine-identity-derived key and a random per-wallet salt.\n * File is written with 0o600 permissions (owner read/write only).\n *\n * @param privateKey - The EVM private key to encrypt (0x-prefixed)\n */\nexport async function encryptKey(privateKey: string): Promise<void> {\n const normalizedPrivateKey = normalizeWalletPrivateKey(privateKey)\n const salt = crypto.randomBytes(16)\n const key = deriveKey(salt)\n const iv = crypto.randomBytes(12)\n const cipher = crypto.createCipheriv('aes-256-gcm', key, iv)\n\n const encrypted = Buffer.concat([cipher.update(normalizedPrivateKey, 'utf8'), cipher.final()])\n\n // getAuthTag() MUST be called after final()\n const tag = cipher.getAuthTag()\n\n const walletData: WalletData = {\n salt: salt.toString('hex'),\n iv: iv.toString('hex'),\n tag: tag.toString('hex'),\n data: encrypted.toString('hex'),\n }\n\n const p = walletPath()\n await mkdir(path.dirname(p), { recursive: true })\n await writeFile(p, JSON.stringify(walletData, null, 2) + '\\n', { mode: 0o600 })\n}\n\nexport interface SetWalletPrivateKeyOptions {\n /** Overwrite an existing wallet. The previous ciphertext is backed up first. */\n force?: boolean\n}\n\n/**\n * Best-effort address of the currently stored wallet, for overwrite messaging.\n * Returns null when the wallet can't be decrypted (e.g. hostname/username\n * changed) — the overwrite is still refused, just without naming the address.\n */\nasync function existingWalletAddress(): Promise<Address | null> {\n try {\n return walletAddressFromPrivateKey(await decryptKey())\n } catch {\n return null\n }\n}\n\n/**\n * Copies the existing wallet.json to a timestamped `.bak-*` sibling before it\n * is overwritten, preserving the 0o600 permission. No-op when absent.\n */\nasync function backupExistingWallet(): Promise<void> {\n const p = walletPath()\n let raw: string\n try {\n raw = await readFile(p, 'utf8')\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return\n throw err\n }\n const stamp = new Date().toISOString().replace(/[:.]/g, '-')\n await writeFile(`${p}.bak-${stamp}`, raw, { mode: 0o600 })\n}\n\n/**\n * Encrypts and stores a private key, refusing to overwrite an existing wallet\n * unless `force` is set. Importing a new key over a funded wallet discards the\n * only local copy of the old key, so the overwrite is guarded and the previous\n * ciphertext is backed up.\n */\nexport async function setWalletPrivateKey(\n privateKey: string,\n options: SetWalletPrivateKeyOptions = {}\n): Promise<Address> {\n const normalizedPrivateKey = normalizeWalletPrivateKey(privateKey)\n const address = walletAddressFromPrivateKey(normalizedPrivateKey)\n\n if (await isWalletConfigured()) {\n if (!options.force) {\n const existing = await existingWalletAddress()\n const which = existing ? ` (${existing})` : ''\n throw new Error(\n `A payment wallet already exists${which}. Importing a new key overwrites it and permanently ` +\n `discards the old key. Re-run \\`chain-insights wallet import <key> --force\\` to replace it; ` +\n `the previous encrypted key is backed up next to wallet.json first.`\n )\n }\n await backupExistingWallet()\n }\n\n await encryptKey(normalizedPrivateKey)\n return address\n}\n\n/**\n * Reads and decrypts the private key from ~/.chain-insights/wallet.json.\n * Throws a human-readable error if wallet is absent or decryption fails.\n *\n * @returns The decrypted EVM private key string\n */\nexport async function decryptKey(): Promise<string> {\n let raw: string\n try {\n raw = await readFile(walletPath(), 'utf8')\n } catch (err: unknown) {\n const nodeErr = err as NodeJS.ErrnoException\n if (nodeErr.code === 'ENOENT') {\n throw new Error(\n 'Wallet not configured. Run `chain-insights wallet import <private-key>`, then `chain-insights wallet ready`.'\n )\n }\n throw err\n }\n\n try {\n const stored = JSON.parse(raw) as WalletData\n const salt = Buffer.from(stored.salt, 'hex')\n const key = deriveKey(salt)\n const iv = Buffer.from(stored.iv, 'hex')\n const tag = Buffer.from(stored.tag, 'hex')\n const encrypted = Buffer.from(stored.data, 'hex')\n\n const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv)\n // setAuthTag() MUST be called before update()\n decipher.setAuthTag(tag)\n\n const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()])\n\n return decrypted.toString('utf8')\n } catch {\n throw new Error(\n 'Wallet decryption failed. If you changed your hostname or username, re-import it with `chain-insights wallet import <private-key>`.'\n )\n }\n}\n\n/**\n * Returns true if wallet.json exists, false if absent.\n * Does not validate the wallet contents.\n */\nexport async function isWalletConfigured(): Promise<boolean> {\n try {\n await stat(walletPath())\n return true\n } catch (err: unknown) {\n const nodeErr = err as NodeJ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OAAO,iBAAiB,eAAe,KAAK,EAAE;EAE/D,SAAS,WAAW,GAAG;EAIvB,OAFkB,OAAO,OAAO,CAAC,SAAS,OAAO,SAAS,GAAG,SAAS,MAAM,CAAC,CAE9D,CAAC,CAAC,SAAS,MAAM;CAClC,QAAQ;EACN,MAAM,IAAI,MACR,qIACF;CACF;AACF;;;;;AAMA,eAAsB,qBAAuC;CAC3D,IAAI;EACF,MAAM,KAAK,WAAW,CAAC;EACvB,OAAO;CACT,SAAS,KAAc;EAErB,IAAIA,IAAQ,SAAS,UAAU,OAAO;EACtC,MAAM;CACR;AACF"}
@@ -26,16 +26,16 @@ against the unified topology graph and facts.
26
26
 
27
27
  ## Module Responsibilities
28
28
 
29
- | Module area | Responsibility |
30
- | --- | --- |
31
- | CLI | Command routing and user-facing workflows |
32
- | Config | Local config schema and owner-only storage |
33
- | Wallet | Encrypted EVM wallet and Base USDC balance checks |
34
- | MCP client/proxy | x402, debug-token, test-key auth, schema cache, stdio proxy |
35
- | Workspace evidence | Evidence, dossiers, reports, and workspace sessions |
36
- | Visualization | Graph data model and self-contained HTML generation |
37
- | Server | Local report and visualization server |
38
- | Workspace init | Investigation workspace scaffold and runtime schema notes |
29
+ | Module area | Responsibility |
30
+ | ------------------ | ----------------------------------------------------------- |
31
+ | CLI | Command routing and user-facing workflows |
32
+ | Config | Local config schema and owner-only storage |
33
+ | Wallet | Encrypted EVM wallet and Base USDC balance checks |
34
+ | MCP client/proxy | x402, debug-token, test-key auth, schema cache, stdio proxy |
35
+ | Workspace evidence | Evidence, dossiers, reports, and workspace sessions |
36
+ | Visualization | Graph data model and self-contained HTML generation |
37
+ | Server | Local report and visualization server |
38
+ | Workspace init | Investigation workspace scaffold and runtime schema notes |
39
39
 
40
40
  ## Data Flow
41
41
 
@@ -65,15 +65,15 @@ endpoints are operator configuration, not hardcoded package defaults.
65
65
 
66
66
  Supported config keys:
67
67
 
68
- | Key | Purpose |
69
- | --- | --- |
70
- | `graphMcpEndpoint` | Chain Insights Graph endpoint used by CLI and proxy |
68
+ | Key | Purpose |
69
+ | ------------------- | ------------------------------------------------------------------------------ |
70
+ | `graphMcpEndpoint` | Chain Insights Graph endpoint used by CLI and proxy |
71
71
  | `graphMcpAuthToken` | Chain Insights Graph bearer credential for test access keys or local debug UAT |
72
- | `graphMcpMode` | Endpoint access mode: `paid` (default) or `debug` |
73
- | `walletAddress` | Optional wallet metadata |
74
- | `serverPort` | Local visualization and graph report server port |
75
- | `dataDir` | Local Chain Insights data directory |
76
- | `version` | Config schema version |
72
+ | `graphMcpMode` | Endpoint access mode: `paid` (default) or `debug` |
73
+ | `walletAddress` | Optional wallet metadata |
74
+ | `serverPort` | Local visualization and graph report server port |
75
+ | `dataDir` | Local Chain Insights data directory |
76
+ | `version` | Config schema version |
77
77
 
78
78
  Wallet private keys are intercepted before config write and stored encrypted in
79
79
  `~/.chain-insights/wallet.json`.
package/docs/debugging.md CHANGED
@@ -19,46 +19,6 @@ with no error and no hint that the build is the cause — including symptoms tha
19
19
  look exactly like bad data or a broken endpoint. Rule out the build before
20
20
  investigating the graph.
21
21
 
22
- ## Monitoring Runs
23
-
24
- `cia monitor run` signals a pass through its exit code, so read the code before
25
- reading the logs:
26
-
27
- ```bash
28
- cia monitor run; echo "exit=$?"
29
- ```
30
-
31
- - `0` — clean pass; every open case rendered.
32
- - `2` — **isolated case failure**: the pass completed, at least one case did
33
- not. The failing cases are printed as `[monitor] <case_id> FAILED: …`;
34
- every other case's dossier still rendered. This is a partial success.
35
- - `1` — the run could not start (unreadable workspace, invalid monitor config).
36
- Nothing ran.
37
-
38
- Under pm2, exit `2` shows the process as `errored` in `pm2 list`. That is the
39
- intended visibility for a partial pass, not a broken deployment.
40
-
41
- An unchanged case is also not a bug: rendering is content-keyed, so a case
42
- whose document did not change since the last pass is skipped
43
- (`skipped_reason: 'unchanged'`) rather than re-rendered. See
44
- [Continuous monitoring](monitoring.md).
45
-
46
- ## Bittensor Devkit Backend
47
-
48
- Use the bundled devkit when you need a deterministic local Chain Insights Graph
49
- backend for Chain Insights workflows:
50
-
51
- ```bash
52
- docker compose -f devkit/docker-compose.yml down -v --remove-orphans
53
- docker compose -f devkit/docker-compose.yml up -d --build
54
- export CHAIN_INSIGHTS_GRAPH_MCP_ENDPOINT=http://127.0.0.1:18012/mcp
55
- npm run devkit:smoke
56
- npm run devkit:smoke:parity
57
- ```
58
-
59
- The devkit backend exposes graph primitives only. It does not need a debug
60
- token, wallet, x402 payment, quota state, or hosted tester access key.
61
-
62
22
  ## Local Chain Insights Graph Debug
63
23
 
64
24
  Start your local Chain Insights Graph development endpoint with debug bearer
@@ -101,8 +61,8 @@ npx @modelcontextprotocol/inspector \
101
61
 
102
62
  ## Environment Variables
103
63
 
104
- | Variable | Purpose |
105
- | --- | --- |
64
+ | Variable | Purpose |
65
+ | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
106
66
  | `CIA_ACTION_LOG` | Optional path to an append-only JSONL audit log of every MCP tool invocation (tool name, arguments, outcome, duration, and any `warnings`/`search_limits` surfaced by the result). Unset by default — no file is written. Intended for unattended runs where an operator or a later reviewing agent needs to see what ran and why a result looked the way it did. Never causes a tool call to fail: a write error (including an unwritable path) is swallowed silently. |
107
67
 
108
68
  ## Smoke Checks
@@ -66,32 +66,6 @@ Focused docs and workspace tests:
66
66
  npm test -- tests/skills-contract.test.ts tests/cli.test.ts
67
67
  ```
68
68
 
69
- ## Bittensor Devkit
70
-
71
- The devkit runs a local Chain Insights Graph backend with deterministic Bittensor
72
- fixture data. Use it when changing graph workflows, AML recipes, MCP proxy
73
- behavior, or developer documentation that depends on a working local backend.
74
-
75
- Start from a clean state:
76
-
77
- ```bash
78
- docker compose -f devkit/docker-compose.yml down -v --remove-orphans
79
- docker compose -f devkit/docker-compose.yml up -d --build
80
- ```
81
-
82
- Run the devkit smoke checks:
83
-
84
- ```bash
85
- npm run devkit:smoke
86
- npm run devkit:smoke:parity
87
- ```
88
-
89
- For manual CLI work, point Chain Insights at the devkit endpoint:
90
-
91
- ```bash
92
- export CHAIN_INSIGHTS_GRAPH_MCP_ENDPOINT=http://127.0.0.1:18012/mcp
93
- ```
94
-
95
69
  ## Global Install From Checkout
96
70
 
97
71
  ```bash
@@ -104,6 +78,5 @@ cia --version
104
78
 
105
79
  - Contributor workflow: `docs/contributing.md`
106
80
  - Debugging and UAT: `docs/debugging.md`
107
- - Bittensor devkit: `devkit/README.md`
108
81
  - Graph tool contracts: `docs/graph-tools.md`
109
82
  - Investigation workspace layout: `docs/investigation-workspaces.md`
@@ -4,10 +4,10 @@ Chain Insights Graph accepts Cypher through `graph_query` and
4
4
  `graph_query_batch`. A query is routed by its leading `USE <graph>` clause to
5
5
  one of two backends, each with its own accepted surface:
6
6
 
7
- | Graph | Backend | Query surface |
8
- | --- | --- | --- |
7
+ | Graph | Backend | Query surface |
8
+ | ---------- | ---------------------------- | --------------------------------------------------------- |
9
9
  | `topology` | Memgraph, directly over Bolt | **Native Memgraph Cypher**, bounded (see topology bounds) |
10
- | `facts` | StarRocks warehouse | Corpus-scoped Cypher subset, compiled to SQL |
10
+ | `facts` | StarRocks warehouse | Corpus-scoped Cypher subset, compiled to SQL |
11
11
 
12
12
  Two consequences drive everything below:
13
13
 
@@ -18,10 +18,10 @@ Two consequences drive everything below:
18
18
  `*KSHORTEST`, `*ALLSHORTEST`) are first-class — subject to traversal bounds
19
19
  enforced before execution. There is no separate query dialect and no
20
20
  federation parser in front of it.
21
- 2. **`facts` is a compiled Cypher *subset*.** A corpus-scoped translator
21
+ 2. **`facts` is a compiled Cypher _subset_.** A corpus-scoped translator
22
22
  (`internal/cyphersql`) compiles a defined shape of `MATCH` / `WHERE` /
23
23
  projection / aggregate / `ORDER BY` / `LIMIT` to StarRocks SQL. Shapes outside
24
- that grammar are rejected with a typed contract error *before* any SQL runs —
24
+ that grammar are rejected with a typed contract error _before_ any SQL runs —
25
25
  they do not reach the warehouse.
26
26
 
27
27
  > **History.** Chain Insights Graph previously split topology into a fast
@@ -67,7 +67,7 @@ closed on an H160 address screened under the chain's primary network name.
67
67
 
68
68
  ### `USE facts` is the opposite case
69
69
 
70
- `facts` is the one place each network *does* get its own backing database —
70
+ `facts` is the one place each network _does_ get its own backing database —
71
71
  the routing metadata on a result reports it as
72
72
  `facts.routing.starrocks_database`. Because the database already scopes the
73
73
  network, the facts `Address` label has **no mapped `network` property at all**:
@@ -105,14 +105,14 @@ chain-evidence-derived, not registry labels.
105
105
 
106
106
  ### Traversal (the expanded surface)
107
107
 
108
- | Form | Syntax | Supported |
109
- | --- | --- | --- |
110
- | Bounded variable-length | `-[:FLOWS_TO*1..5]->` | ✅ upper bound ≤ 5 |
111
- | BFS to depth | `-[:FLOWS_TO *BFS 1..5]->` | ✅ upper bound ≤ 5 |
112
- | Weighted shortest path | `-[:FLOWS_TO *WSHORTEST 5 (r,n \| coalesce(r.amount_usd_sum,1)) w]->` | ✅ hop bound ≤ 5, weight lambda supported |
113
- | All shortest paths | `-[:FLOWS_TO *ALLSHORTEST 5 (r,n \| 1) w]->` | ✅ hop bound ≤ 5 |
114
- | K shortest paths | `-[:FLOWS_TO *KSHORTEST\|3]->` | ✅ path count k ≤ 16 |
115
- | Traversal filter lambda | `-[:FLOWS_TO *1..5 (r,n \| n.is_exchange IS NULL)]->` | ✅ |
108
+ | Form | Syntax | Supported |
109
+ | ----------------------- | --------------------------------------------------------------------- | ----------------------------------------- |
110
+ | Bounded variable-length | `-[:FLOWS_TO*1..5]->` | ✅ upper bound ≤ 5 |
111
+ | BFS to depth | `-[:FLOWS_TO *BFS 1..5]->` | ✅ upper bound ≤ 5 |
112
+ | Weighted shortest path | `-[:FLOWS_TO *WSHORTEST 5 (r,n \| coalesce(r.amount_usd_sum,1)) w]->` | ✅ hop bound ≤ 5, weight lambda supported |
113
+ | All shortest paths | `-[:FLOWS_TO *ALLSHORTEST 5 (r,n \| 1) w]->` | ✅ hop bound ≤ 5 |
114
+ | K shortest paths | `-[:FLOWS_TO *KSHORTEST\|3]->` | ✅ path count k ≤ 16 |
115
+ | Traversal filter lambda | `-[:FLOWS_TO *1..5 (r,n \| n.is_exchange IS NULL)]->` | ✅ |
116
116
 
117
117
  ### Topology admission + bounds gate
118
118
 
@@ -120,12 +120,12 @@ Admission mirrors the production graph MCP exactly (read-only, byte size ≤ 327
120
120
  single statement, must start with a read clause). On top of that, traversal is
121
121
  bounded so an admitted query cannot become an unbounded graph walk:
122
122
 
123
- | Bound | Limit | Rejected example |
124
- | --- | --- | --- |
125
- | Traversal depth (upper hop bound) | ≤ 5 | `-[:FLOWS_TO*1..9]->` → *traversal depth 9 exceeds the maximum of 5* |
126
- | Unbounded traversal | forbidden | `-[:FLOWS_TO*]->`, `-[:FLOWS_TO *BFS]->`, `-[:FLOWS_TO*3..]->` → *unbounded traversal … add an explicit upper hop bound* |
127
- | KSHORTEST path count `k` | ≤ 16 | `*KSHORTEST\|50` → *KSHORTEST k=50 exceeds the maximum of 16* |
128
- | `UNWIND` literal list length | ≤ 1000 | `UNWIND [ …1001 items… ] AS x` → *UNWIND list of 1001 items exceeds the maximum of 1000* |
123
+ | Bound | Limit | Rejected example |
124
+ | --------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------ |
125
+ | Traversal depth (upper hop bound) | ≤ 5 | `-[:FLOWS_TO*1..9]->` → _traversal depth 9 exceeds the maximum of 5_ |
126
+ | Unbounded traversal | forbidden | `-[:FLOWS_TO*]->`, `-[:FLOWS_TO *BFS]->`, `-[:FLOWS_TO*3..]->` → _unbounded traversal … add an explicit upper hop bound_ |
127
+ | KSHORTEST path count `k` | ≤ 16 | `*KSHORTEST\|50` → _KSHORTEST k=50 exceeds the maximum of 16_ |
128
+ | `UNWIND` literal list length | ≤ 1000 | `UNWIND [ …1001 items… ] AS x` → _UNWIND list of 1001 items exceeds the maximum of 1000_ |
129
129
 
130
130
  Always add an explicit upper hop bound and a `LIMIT`. Writes/DDL (`CREATE`,
131
131
  `MERGE`, `SET`, `DELETE`, `DROP`, `CALL`, …) are always rejected — the surface is
@@ -139,59 +139,68 @@ rejected with a typed contract error before execution.
139
139
 
140
140
  ### Supported
141
141
 
142
- | Construct | Notes |
143
- | --- | --- |
144
- | `MATCH` on a mapped node / single relationship | `(from:Address)-[t:TRANSFER]->(to:Address)` (bounded individual transfer rows from `facts_transfers_view`). Lifetime address metrics are node properties on `USE topology` (the facts `AddressFeature` surface is retired). Never serves `FLOWS_TO` or `LINKED` — those are topology-only. Neuron identity, hotkey/coldkey pairing, and IP/axon-port observation live on the topology `:Neuron` node, not on `facts`. Labels and per-label risk live on the topology address node, not on `facts`. |
145
- | Chained fixed-hop patterns | up to 5 hops |
146
- | `WHERE` with an indexed predicate | `address` equality or `IN`; `tx_id` equality or `IN` (the `TRANSFER` edge's row-level key); date/height/timestamp range |
147
- | Inline property maps | `MATCH (a:Address {address:"…"})` |
148
- | Property projections with aliases | `RETURN a.address AS address, f.tx_out_count AS tx_out_count` |
149
- | Aggregates **with** an indexed predicate | `count`, `sum` |
150
- | `ORDER BY`, `LIMIT` (≤ 1000), `OFFSET`-free paging | `LIMIT` required unless an indexed predicate is present — except `TRANSFER`, where an indexed predicate is always required (see below) |
142
+ | Construct | Notes |
143
+ | -------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
144
+ | `MATCH` on a mapped node / single relationship | `(from:Address)-[t:TRANSFER]->(to:Address)` (bounded individual transfer rows from `facts_transfers_view`). Lifetime address metrics are node properties on `USE topology` (the facts `AddressFeature` surface is retired). Never serves `FLOWS_TO` or `LINKED` — those are topology-only. Neuron identity, hotkey/coldkey pairing, and IP/axon-port observation live on the topology `:Neuron` node, not on `facts`. Labels and per-label risk live on the topology address node, not on `facts`. |
145
+ | Chained fixed-hop patterns | up to 5 hops |
146
+ | Bare `block_date` bound | `t.block_date >= ?` / `<`, `=`, `BETWEEN`, `IN` — the caller's own day range, passed through. The bound must be bare (no function around the column) and conjunctive (not inside an `OR` arm). An explicit full-range bound (`>= '1970-01-01'`) stays lifetime. |
147
+ | `tx_id` equality / `IN` | `t.tx_id = "…"` — a point lookup on the `TRANSFER` edge's row-level key. Lifetime semantics. |
148
+ | Address equality / `IN` | `{address:"…"}` map or `a.address = "…"` / `IN` — **a recency window is auto-applied** (bare `block_date >= now − 90 days`; the window is `FACTS_RECENCY_WINDOW_DAYS`, default 90). Address-only queries return the last 90 days. |
149
+ | Inline property maps | `MATCH (a:Address {address:"…"})` |
150
+ | Property projections with aliases | `RETURN a.address AS address, t.amount_usd AS amount_usd` |
151
+ | Aggregates **with** a partition-bounding predicate | `count`, `sum` |
152
+ | `ORDER BY`, `LIMIT` (≤ 1000), `OFFSET`-free paging | `LIMIT` required unless a partition-bounding predicate is present — except `TRANSFER`, where a partition-bounding predicate is always required (see below) |
151
153
 
152
154
  ### Cost-shape gate
153
155
 
154
156
  `facts` rejects full-scan shapes so a mapped-graph read cannot turn into an
155
- unbounded warehouse scan:
156
-
157
- | Rejected shape | Contract error |
158
- | --- | --- |
159
- | Predicate-less global aggregate | `count(i)` with no indexed predicate → *StarRocks-backed aggregate graph queries require an indexed predicate* |
160
- | No `LIMIT` and no indexed predicate | → *StarRocks-backed graph queries require an explicit LIMIT or indexed predicate* |
161
- | `TRANSFER` row-select or aggregate with no indexed predicate, even with `LIMIT` | `facts_transfers_view` is a full transfer-history table — a bare `LIMIT` does not bound the scan → *StarRocks-backed TRANSFER graph queries require an indexed predicate (address equality on either endpoint, or tx_id)* |
162
- | `LIMIT` above the ceiling | `LIMIT 5000` → *StarRocks-backed graph query LIMIT exceeds maximum 1000* |
157
+ unbounded warehouse scan. `core_transfers` is split into one partition per
158
+ day, keyed on `block_date` — a query without a bare `block_date` bound, a
159
+ `tx_id` point lookup, or an address filter (window auto-applied) touches
160
+ every partition and is refused before any SQL runs. The refusal names the
161
+ remedy: _add a bare `block_date` bound, or query by `tx_id`, or filter by
162
+ address (a recency window is auto-applied)_.
163
+
164
+ | Rejected shape | Contract error |
165
+ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
166
+ | Predicate-less global aggregate | `count(i)` with no partition-bounding predicate → _StarRocks-backed aggregate graph queries require a partition-bounding predicate: add a bare `block_date` bound, or query by `tx_id`, or filter by address (a recency window is auto-applied)_ |
167
+ | No `LIMIT` and no partition-bounding predicate | → _StarRocks-backed graph queries require an explicit LIMIT or partition-bounding predicate: add a bare `block_date` bound, or query by `tx_id`, or filter by address (a recency window is auto-applied)_ |
168
+ | `TRANSFER` row-select or aggregate with no partition-bounding predicate, even with `LIMIT` | `facts_transfers_view` is a full transfer-history table — a bare `LIMIT` does not bound the scan → _StarRocks-backed TRANSFER graph queries require a partition-bounding predicate: add a bare `block_date` bound, or query by `tx_id`, or filter by address (a recency window is auto-applied)_ |
169
+ | `block_height` / `block_timestamp` range only | `t.block_height >= ?` bounds the sort key, not the day partitions → rejected with the remedy error |
170
+ | Wrapped `block_date` | `DATE(t.block_date) >= ?` wraps the partition column → rejected with the remedy error |
171
+ | `block_date` bound inside an `OR` arm | `t.block_height >= 0 OR t.block_date >= ?` — the optimizer cannot prune the unbounded arm → rejected with the remedy error |
172
+ | `LIMIT` above the ceiling | `LIMIT 5000` → _StarRocks-backed graph query LIMIT exceeds maximum 1000_ |
163
173
 
164
174
  ### Not in the facts grammar (contract error)
165
175
 
166
176
  These compile-reject (`ErrUnsupportedShape` / related) — they never reach
167
177
  StarRocks. Use the topology graph, or restructure:
168
178
 
169
- | Construct | Instead |
170
- | --- | --- |
171
- | `FLOWS_TO` / money-flow traversal | The topology graph — facts never serves money flow |
172
- | Native traversal (`*1..3`, `*BFS`, `*WSHORTEST`, …) | The topology graph, or a single fixed-hop `LINKED` pattern |
173
- | `WITH` pipelines | The topology graph |
174
- | `CASE … END` | The topology graph, or post-process client-side |
175
- | Grouped aggregates (`GROUP BY`-shaped) | The topology graph, or per-key `graph_query_batch` |
176
- | `collect()` and other warehouse-dialect-gap aggregates | The topology graph |
177
- | Self-joins / node-to-node comparison `WHERE a <> b` | Compare key properties: `a.address <> b.address` |
178
- | Untyped relationship `-[r]->` | Name the relationship type |
179
- | Metadata functions `keys(n)`, `labels(n)`, `type(r)` | Project known properties explicitly |
180
-
181
- The facts result baselines and the exact supported/rejected shape set are pinned
182
- by `devkit/chain-insights-graph-devkit/internal/cyphersql`
183
- (`corpus_test.go`, `conformance_starrocks_test.go`).
179
+ | Construct | Instead |
180
+ | ------------------------------------------------------ | ---------------------------------------------------------- |
181
+ | `FLOWS_TO` / money-flow traversal | The topology graph — facts never serves money flow |
182
+ | Native traversal (`*1..3`, `*BFS`, `*WSHORTEST`, …) | The topology graph, or a single fixed-hop `LINKED` pattern |
183
+ | `WITH` pipelines | The topology graph |
184
+ | `CASE … END` | The topology graph, or post-process client-side |
185
+ | Grouped aggregates (`GROUP BY`-shaped) | The topology graph, or per-key `graph_query_batch` |
186
+ | `collect()` and other warehouse-dialect-gap aggregates | The topology graph |
187
+ | Self-joins / node-to-node comparison `WHERE a <> b` | Compare key properties: `a.address <> b.address` |
188
+ | Untyped relationship `-[r]->` | Name the relationship type |
189
+ | Metadata functions `keys(n)`, `labels(n)`, `type(r)` | Project known properties explicitly |
190
+
191
+ There is no longer a local pinned conformance suite; verify supported and
192
+ rejected shapes against a live Chain Insights Graph endpoint.
184
193
 
185
194
  ## Taxonomy labels (topology graph)
186
195
 
187
196
  Secondary node labels (exchange / scam classification labels maintained on
188
197
  addresses) are queryable on `topology`:
189
198
 
190
- | Form | Result |
191
- | --- | --- |
192
- | `MATCH (n:Exchange)` — bare secondary label | ✅ |
193
- | `MATCH (n:Address:Exchange)` — colon-stacked labels | ✅ (native Cypher) |
194
- | `RETURN labels(n)` | project known properties instead |
199
+ | Form | Result |
200
+ | --------------------------------------------------- | -------------------------------- |
201
+ | `MATCH (n:Exchange)` — bare secondary label | ✅ |
202
+ | `MATCH (n:Address:Exchange)` — colon-stacked labels | ✅ (native Cypher) |
203
+ | `RETURN labels(n)` | project known properties instead |
195
204
 
196
205
  Caveats: taxonomy labels are sticky (never removed once assigned — presence means
197
206
  "was ever classified", not "currently active"); facts carries only its mapped
@@ -11,11 +11,11 @@ local review and `published/` only for rendered HTML or handoff-ready outputs.
11
11
 
12
12
  The Chain Insights Graph surface is intentionally small:
13
13
 
14
- | Tool | Purpose |
15
- | --- | --- |
14
+ | Tool | Purpose |
15
+ | ---------------------- | --------------------------------------------------------------------------------------- |
16
16
  | `network_capabilities` | Return supported networks and graph layers when the backend exposes capability metadata |
17
- | `graph_query` | Run one read-only GQL/Cypher query through the universal graph endpoint |
18
- | `graph_query_batch` | Run related read-only graph-language queries as one MCP call |
17
+ | `graph_query` | Run one read-only GQL/Cypher query through the universal graph endpoint |
18
+ | `graph_query_batch` | Run related read-only graph-language queries as one MCP call |
19
19
 
20
20
  Chain Insights tools such as `aml_address_risk` are recipes built over
21
21
  `graph_query_batch`. They are not assumed to exist on the
@@ -24,8 +24,8 @@ Chain Insights Graph endpoint.
24
24
  The Chain Insights MCP proxy adds product-facing local metadata tools such as
25
25
  `meta_network_capabilities`, `meta_usage_status`, and `meta_help`. On hosted
26
26
  backends, `meta_usage_status` can reflect remote quota telemetry. On
27
- primitive-only local backends such as the Bittensor devkit, Chain Insights
28
- returns a local unmetered primitive-backend status instead.
27
+ backends without a quota tool, Chain Insights returns a local unmetered
28
+ primitive-backend status instead.
29
29
 
30
30
  ## Query Rules
31
31
 
@@ -37,41 +37,6 @@ templates/ Reusable workspace templates
37
37
  No investigation output belongs under `~/.chain-insights`. That directory is for
38
38
  local Chain Insights config, wallet, and schema cache state.
39
39
 
40
- ## Monitor Workspaces
41
-
42
- A monitor workspace is not a different kind of workspace. `cia monitor` runs
43
- inside an ordinary initialized workspace and adds directories alongside the
44
- investigation ones:
45
-
46
- ```text
47
- cases/<case-id>/case.json Case definition (seeds, seed events)
48
- .chain-insights/monitor/config.json Monitor configuration (render)
49
- .chain-insights/monitor/render-state.json Per-case render keys
50
- .chain-insights/monitor/logs/ Append-only run log (monitor-runs.jsonl)
51
- published/cases/<case-id>/ Rendered case dossiers, per-address notes, timelines
52
- ```
53
-
54
- The same rules apply: run every command from the workspace root, and no monitor
55
- output belongs under `~/.chain-insights`.
56
-
57
- Whether to share one workspace or keep two is a question of lifetime, not
58
- capability:
59
-
60
- - **One workspace** when monitoring exists to feed investigation — a tracked
61
- theft whose case dossiers you then read alongside your `reports/` analysis.
62
- The rendered case output and your analysis sit next to each other and
63
- reference each other by path.
64
- - **A dedicated monitoring workspace** when the watch is long-running and
65
- general (a standing case-tracking schedule). It accumulates run documents
66
- and rendered cases indefinitely; an investigation workspace is a bounded
67
- piece of work you eventually publish and close. Mixing them buries a
68
- finished investigation under months of run documents.
69
-
70
- Do not point two schedules at the same workspace. Passes are idempotent, but
71
- overlapping schedules double the work for no extra coverage.
72
-
73
- See [Continuous monitoring](monitoring.md) for the command surface.
74
-
75
40
  ## Imports
76
41
 
77
42
  `imports/` is for user-provided or third-party inputs before they become
package/docs/mcp-proxy.md CHANGED
@@ -84,12 +84,12 @@ The proxy:
84
84
 
85
85
  ## Local Tools
86
86
 
87
- | Tool | Purpose |
88
- | --- | --- |
89
- | `meta_network_capabilities` | Show the current Chain Insights network/tool support matrix |
90
- | `meta_usage_status` | Check the caller's daily free-tier graph query allowance |
91
- | `meta_help` | Show Chain Insights tool and workflow guidance |
92
- | `wallet_balance` | Show the local payment wallet address, payment network, token, and amount |
87
+ | Tool | Purpose |
88
+ | --------------------------- | ------------------------------------------------------------------------- |
89
+ | `meta_network_capabilities` | Show the current Chain Insights network/tool support matrix |
90
+ | `meta_usage_status` | Check the caller's daily free-tier graph query allowance |
91
+ | `meta_help` | Show Chain Insights tool and workflow guidance |
92
+ | `wallet_balance` | Show the local payment wallet address, payment network, token, and amount |
93
93
 
94
94
  For normal local review, inspect local workspace files directly and keep your
95
95
  preferred editor or agent tooling open to the same workspace while you work.
@@ -104,9 +104,8 @@ Chain Insights presents this as local, prefixed metadata through
104
104
  `meta_network_capabilities`.
105
105
 
106
106
  `meta_usage_status` is a Chain Insights proxy tool. On hosted Chain Insights Graph
107
- backends it can reflect remote quota telemetry. On primitive-only local
108
- backends such as the Bittensor devkit, it returns a local unmetered
109
- primitive-backend status.
107
+ backends it can reflect remote quota telemetry. On backends without a quota
108
+ tool, it returns a local unmetered primitive-backend status.
110
109
 
111
110
  Chain Insights adds the high-level local graph recipe `aml_address_risk`
112
111
  when the remote endpoint only exposes primitives.
@@ -20,9 +20,9 @@ Highest wins:
20
20
 
21
21
  ## Knobs
22
22
 
23
- | Key | Bounds | Default | Ceiling | Per-call argument |
24
- | --- | --- | --- | --- | --- |
25
- | `viz_max_nodes` | nodes rendered before truncation | 100 | 2000 | `maxNodes` |
23
+ | Key | Bounds | Default | Ceiling | Per-call argument |
24
+ | --------------- | -------------------------------- | ------- | ------- | ----------------- |
25
+ | `viz_max_nodes` | nodes rendered before truncation | 100 | 2000 | `maxNodes` |
26
26
 
27
27
  Defaults are exactly the values that used to be hardcoded, so an existing call
28
28
  that passes no override behaves identically.
@@ -66,8 +66,8 @@ that had no effect.
66
66
 
67
67
  These are protocol or safety limits, not budget choices:
68
68
 
69
- | Bound | Why it stays fixed |
70
- | --- | --- |
71
- | Max query text size (32 KiB) | A hard backend limit. Exceeding it fails the query; it is not a cost trade-off. |
72
- | Queries per `graph_query_batch` (20) | The backend's protocol maximum. A larger batch is rejected server-side. |
73
- | Per-query and per-request timeouts | Transport-level, not search breadth. |
69
+ | Bound | Why it stays fixed |
70
+ | ------------------------------------ | ------------------------------------------------------------------------------- |
71
+ | Max query text size (32 KiB) | A hard backend limit. Exceeding it fails the query; it is not a cost trade-off. |
72
+ | Queries per `graph_query_batch` (20) | The backend's protocol maximum. A larger batch is rejected server-side. |
73
+ | Per-query and per-request timeouts | Transport-level, not search breadth. |