chain-insights 0.74.1 → 0.76.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/README.md +3 -2
- package/dist/{action-log-D49Par9P.mjs → action-log-Byv9Ln_6.mjs} +4 -10
- package/dist/{action-log-D49Par9P.mjs.map → action-log-Byv9Ln_6.mjs.map} +1 -1
- package/dist/{action-log-HniMMF7f.cjs → action-log-WMW6xFMx.cjs} +3 -9
- package/dist/{active-Dkf8AB1R.mjs → active-D2aabYRF.mjs} +3 -4
- package/dist/{active-Dkf8AB1R.mjs.map → active-D2aabYRF.mjs.map} +1 -1
- package/dist/{active-Bc13hJIm.cjs → active-q3yViZhc.cjs} +2 -3
- package/dist/answer-hint-BlYEBq_Y.cjs +57 -0
- package/dist/answer-hint-vOE1O6Lf.mjs +48 -0
- package/dist/answer-hint-vOE1O6Lf.mjs.map +1 -0
- package/dist/{buy-_mpdRieG.mjs → buy-B2luUbWF.mjs} +5 -6
- package/dist/{buy-_mpdRieG.mjs.map → buy-B2luUbWF.mjs.map} +1 -1
- package/dist/{buy-97M6dtEu.cjs → buy-DEoGITbT.cjs} +4 -5
- package/dist/{cache-location-CBVzUIxq.cjs → cache-location-C09AE55j.cjs} +2 -3
- package/dist/{cache-location-BO2XkfgI.mjs → cache-location-DxTTqBwk.mjs} +2 -3
- package/dist/{cache-location-BO2XkfgI.mjs.map → cache-location-DxTTqBwk.mjs.map} +1 -1
- package/dist/{call-args-B0oMK1-J.mjs → call-args-CBqbYfOE.mjs} +15 -4
- package/dist/{call-args-B0oMK1-J.mjs.map → call-args-CBqbYfOE.mjs.map} +1 -1
- package/dist/{call-args-C8Gp5gco.cjs → call-args-DXEmPeE-.cjs} +14 -2
- package/dist/{capabilities-DxojbX4D.mjs → capabilities-BRNHcabF.mjs} +5 -11
- package/dist/{capabilities-DxojbX4D.mjs.map → capabilities-BRNHcabF.mjs.map} +1 -1
- package/dist/{capabilities-Ds3320iS.cjs → capabilities-DalimVY2.cjs} +4 -10
- package/dist/{claude-desktop-Jmm4PlBZ.cjs → claude-desktop-3OksQZVE.cjs} +2 -3
- package/dist/{claude-desktop-6jwX0Lux.mjs → claude-desktop-C1SDYAP2.mjs} +2 -3
- package/dist/{claude-desktop-6jwX0Lux.mjs.map → claude-desktop-C1SDYAP2.mjs.map} +1 -1
- package/dist/cli.cjs +95 -76
- package/dist/cli.mjs +94 -75
- package/dist/cli.mjs.map +1 -1
- package/dist/{client-7qOfAdpH.mjs → client-BaHAIidE.mjs} +10 -21
- package/dist/{client-7qOfAdpH.mjs.map → client-BaHAIidE.mjs.map} +1 -1
- package/dist/{client-C9uwHnBS.cjs → client-Ddk4X9Ko.cjs} +9 -20
- package/dist/{config-BxtMoo9c.cjs → config-BdE8LcF-.cjs} +3 -5
- package/dist/{config-9MabJh5R.mjs → config-BkLIqOYq.mjs} +4 -6
- package/dist/{config-9MabJh5R.mjs.map → config-BkLIqOYq.mjs.map} +1 -1
- package/dist/{create-CpfZq2fx.mjs → create-CluDZkuF.mjs} +3 -4
- package/dist/{create-CpfZq2fx.mjs.map → create-CluDZkuF.mjs.map} +1 -1
- package/dist/{create-DdggkF04.cjs → create-DvBumvHn.cjs} +2 -3
- package/dist/{dex-registry-Chs79Ukc.cjs → dex-registry-CZQB2YhU.cjs} +4 -26
- package/dist/{dex-registry-rziydXYq.mjs → dex-registry-D6Xxi_vr.mjs} +5 -27
- package/dist/{dex-registry-rziydXYq.mjs.map → dex-registry-D6Xxi_vr.mjs.map} +1 -1
- package/dist/{dex-tool-DsaAIa-a.mjs → dex-tool-BoAYqhZO.mjs} +13 -67
- package/dist/dex-tool-BoAYqhZO.mjs.map +1 -0
- package/dist/{dex-tool-DLWnff1n.cjs → dex-tool-DsM-pSku.cjs} +17 -77
- package/dist/{format-CSesEBvS.mjs → format-CsnW5M4D.mjs} +2 -3
- package/dist/{format-CSesEBvS.mjs.map → format-CsnW5M4D.mjs.map} +1 -1
- package/dist/{format-DfhRQq4L.cjs → format-DUzmoeaE.cjs} +1 -2
- package/dist/{graph-schema-BGbJumCY.cjs → graph-schema-C8Pi6r7c.cjs} +12 -29
- package/dist/{graph-schema-ClqjzgrM.mjs → graph-schema-D4LAefGf.mjs} +13 -30
- package/dist/graph-schema-D4LAefGf.mjs.map +1 -0
- package/dist/index.cjs +7 -7
- package/dist/index.d.cts +0 -16
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +0 -16
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +7 -7
- package/dist/{known-keys-B87ZqOgE.mjs → known-keys-BbuzCZOW.mjs} +4 -7
- package/dist/{known-keys-B87ZqOgE.mjs.map → known-keys-BbuzCZOW.mjs.map} +1 -1
- package/dist/{known-keys-PKZF5GYd.cjs → known-keys-Cy8lKDOA.cjs} +3 -6
- package/dist/mcp-proxy.cjs +83 -57
- package/dist/mcp-proxy.d.cts +2 -2
- package/dist/mcp-proxy.d.cts.map +1 -1
- package/dist/mcp-proxy.d.mts +2 -2
- package/dist/mcp-proxy.d.mts.map +1 -1
- package/dist/mcp-proxy.mjs +81 -56
- package/dist/mcp-proxy.mjs.map +1 -1
- package/dist/{print-result-Cyqrlx8P.cjs → print-result-BYppJlUi.cjs} +20 -20
- package/dist/{print-result-C3YazZBw.mjs → print-result-IFARsMnL.mjs} +10 -22
- package/dist/print-result-IFARsMnL.mjs.map +1 -0
- package/dist/{public-tools-Bl_l_rKK.cjs → public-tools-Cfc1OPNS.cjs} +16 -21
- package/dist/{public-tools-CQjGt7_q.mjs → public-tools-DXlZcanX.mjs} +16 -21
- package/dist/public-tools-DXlZcanX.mjs.map +1 -0
- package/dist/{quote-DfTut0cx.mjs → quote-41CbMc37.mjs} +2 -3
- package/dist/{quote-DfTut0cx.mjs.map → quote-41CbMc37.mjs.map} +1 -1
- package/dist/{quote-B9sYNOiv.cjs → quote-pFKcSvMv.cjs} +1 -2
- package/dist/{request-timeout-CYmQF8N7.cjs → request-timeout-DxwNijQD.cjs} +1 -2
- package/dist/{request-timeout-lBBe0mGf.mjs → request-timeout-K3ljP0pa.mjs} +2 -3
- package/dist/{request-timeout-lBBe0mGf.mjs.map → request-timeout-K3ljP0pa.mjs.map} +1 -1
- package/dist/{robinhood-CCTMagwM.mjs → robinhood-0NZsA6ZW.mjs} +2 -3
- package/dist/robinhood-0NZsA6ZW.mjs.map +1 -0
- package/dist/{robinhood-ChiT69sc.cjs → robinhood-DumTxvlA.cjs} +1 -2
- package/dist/{rolldown-runtime-8H4AJuhK.mjs → rolldown-runtime-BJohB4LM.mjs} +1 -2
- package/dist/{rolldown-runtime-C0BPl7ul.cjs → rolldown-runtime-BW-eSwOZ.cjs} +1 -2
- package/dist/{rules-BWdbOtHi.mjs → rules-B3w9pCeQ.mjs} +2 -3
- package/dist/{rules-BWdbOtHi.mjs.map → rules-B3w9pCeQ.mjs.map} +1 -1
- package/dist/{rules-BD-cNHMX.cjs → rules-BKwfmNsJ.cjs} +1 -2
- package/dist/{schema-KjZqCHbu.mjs → schema-CKnQsdw9.mjs} +6 -13
- package/dist/{schema-KjZqCHbu.mjs.map → schema-CKnQsdw9.mjs.map} +1 -1
- package/dist/{schema-tX0U0-VI.cjs → schema-CSESfCvA.cjs} +5 -12
- package/dist/{schema-cache-DRObKUvS.mjs → schema-cache-BfKHodDY.mjs} +3 -4
- package/dist/{schema-cache-DRObKUvS.mjs.map → schema-cache-BfKHodDY.mjs.map} +1 -1
- package/dist/{schema-cache-C7v9ml6S.cjs → schema-cache-NLgJmh4X.cjs} +3 -4
- package/dist/{skill-refresh-xYWZ_hua.mjs → skill-refresh-BchIsODN.mjs} +2 -3
- package/dist/{skill-refresh-xYWZ_hua.mjs.map → skill-refresh-BchIsODN.mjs.map} +1 -1
- package/dist/{skill-refresh-Be2D5FrX.cjs → skill-refresh-DaCTxhhy.cjs} +2 -3
- package/dist/{subscription-status-DIuH84fM.mjs → subscription-status-5WfPhSep.mjs} +3 -4
- package/dist/{subscription-status-DIuH84fM.mjs.map → subscription-status-5WfPhSep.mjs.map} +1 -1
- package/dist/{subscription-status-9tMfD90J.cjs → subscription-status-w4zI2KCK.cjs} +2 -3
- package/dist/token-lookup-BJ00JO9A.cjs +342 -0
- package/dist/token-lookup-XnyisLQW.mjs +303 -0
- package/dist/token-lookup-XnyisLQW.mjs.map +1 -0
- package/dist/{tool-visibility-BNwvcuVx.cjs → tool-visibility-DIpgPULN.cjs} +5 -10
- package/dist/{tool-visibility-B6983rxo.mjs → tool-visibility-Dy3psowS.mjs} +6 -11
- package/dist/tool-visibility-Dy3psowS.mjs.map +1 -0
- package/dist/{tools-D9ep9E7Q.mjs → tools-6pZo4h_p.mjs} +6 -21
- package/dist/{tools-D9ep9E7Q.mjs.map → tools-6pZo4h_p.mjs.map} +1 -1
- package/dist/{tools-Cmnq7yip.cjs → tools-DZLizem9.cjs} +5 -20
- package/dist/{topup-B6gZbTmv.mjs → topup--7JTo4UQ.mjs} +6 -7
- package/dist/{topup-B6gZbTmv.mjs.map → topup--7JTo4UQ.mjs.map} +1 -1
- package/dist/{topup-DVTCU2le.cjs → topup-BgI9OcUd.cjs} +5 -6
- package/dist/{topup-server-ShuYSyBY.cjs → topup-server-D9Uk1Th3.cjs} +7 -24
- package/dist/{topup-server-KQDviFXG.mjs → topup-server-DR0HaUcR.mjs} +8 -25
- package/dist/{topup-server-KQDviFXG.mjs.map → topup-server-DR0HaUcR.mjs.map} +1 -1
- package/dist/{topup-server-BcT7DIpd.mjs → topup-server-DlwzFEF1.mjs} +5 -12
- package/dist/{topup-server-BcT7DIpd.mjs.map → topup-server-DlwzFEF1.mjs.map} +1 -1
- package/dist/{topup-server-f4Gx0vji.cjs → topup-server-H1M_7PJK.cjs} +4 -11
- package/dist/{transport-error-D4hmpkqL.mjs → transport-error-68G35VPH.mjs} +3 -4
- package/dist/{transport-error-D4hmpkqL.mjs.map → transport-error-68G35VPH.mjs.map} +1 -1
- package/dist/{transport-error-CgISST8l.cjs → transport-error-DXy1iTpS.cjs} +2 -3
- package/dist/{update-CZDHSi_u.mjs → update-BH8F4cQ2.mjs} +3 -4
- package/dist/{update-CZDHSi_u.mjs.map → update-BH8F4cQ2.mjs.map} +1 -1
- package/dist/{update-DGyRlm3J.cjs → update-DUDdQSEU.cjs} +2 -3
- package/dist/{usage-status-Frot6fPG.mjs → usage-status-BUZgRl4r.mjs} +3 -5
- package/dist/{usage-status-Frot6fPG.mjs.map → usage-status-BUZgRl4r.mjs.map} +1 -1
- package/dist/{usage-status-DonwoLR3.cjs → usage-status-DnV3I3gX.cjs} +2 -4
- package/dist/{wallet-QTo5YCFR.mjs → wallet-B1M0HdQh.mjs} +4 -8
- package/dist/{wallet-QTo5YCFR.mjs.map → wallet-B1M0HdQh.mjs.map} +1 -1
- package/dist/{wallet-CgIAfdxL.cjs → wallet-BubGd_sG.cjs} +3 -7
- package/docs/graph-query-compatibility.md +13 -13
- package/docs/graph-tools.md +22 -22
- package/docs/mcp-proxy.md +35 -1
- package/docs/stability.md +3 -2
- package/package.json +1 -1
- package/skills/chain-insights-cypher/SKILL.md +30 -27
- package/skills/chain-insights-dex/SKILL.md +2 -2
- package/skills/chain-insights-dex/reference.md +1 -1
- package/skills/chain-insights-dex-gauge/SKILL.md +4 -4
- package/skills/chain-insights-dex-launchpad/SKILL.md +2 -2
- package/skills/chain-insights-virtuals/reference.md +5 -5
- package/dist/dex-tool-DsaAIa-a.mjs.map +0 -1
- package/dist/graph-schema-ClqjzgrM.mjs.map +0 -1
- package/dist/print-result-C3YazZBw.mjs.map +0 -1
- package/dist/public-tools-CQjGt7_q.mjs.map +0 -1
- package/dist/robinhood-CCTMagwM.mjs.map +0 -1
- package/dist/tool-visibility-B6983rxo.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"graph-schema-ClqjzgrM.mjs","names":["errorResult","isRecord"],"sources":["../src/mcp/flows.ts","../src/mcp/graph-schema-cache.ts","../src/mcp/graph-schema.ts"],"sourcesContent":["/**\n * graph_expand, the one dedicated tool of the local proxy, called by the Chain\n * Insights view (ui://chain-insights/view) when the investigator clicks. Its\n * _meta says visibility [\"app\"], so a host keeps it away from the model: the\n * model writes its own graph_query, and the view draws the rows by their column\n * names.\n *\n * Two forms, told apart by the arguments:\n *\n * - node, {network, address, in_offset?, out_offset?}: one address with up to\n * 250 newest senders and 250 newest receivers, a text summary and\n * chain-insights.flows.v1 in structuredContent. Composed from at most five\n * anchored graph_query reads on the topology graph: the node, then its\n * outgoing and its incoming FLOWS_TO, newest first, two reads a side because\n * a reply holds at most 200 rows.\n * - link, {network, from, to, day}: the transfers between two known addresses\n * on one UTC day, newest first, at most 50, a short text summary and\n * chain-insights.transfers.v1 in structuredContent. One anchored USE facts\n * graph_query read.\n * - link page, {network, from, to, day, limit, skip?, first_day?}: a page of\n * `limit` transfers (1 to 50) newest first, read from `day` back one UTC day\n * at a time, at most TRANSFERS_MAX_DAYS (a week of) reads a call, never before\n * first_day. The answer carries `next` ({day, skip}, or null when every\n * transfer back to first_day is listed) which the next call sends back as\n * day and skip. The view's \"More transfers\".\n * - details, {network, address, details: true}: the lifetime totals, counts,\n * role and labels of one address, chain-insights.address.v1, one anchored\n * topology read. The view fills its panel with it when the rows of a query\n * carried no totals.\n *\n * Every read goes through the proxy's remote client, the same path and payment\n * wrapping a graph_query call takes, and is billed as a graph_query. Every\n * argument is checked before the first read, so a refused call reaches no graph\n * endpoint and costs nothing.\n */\n\nexport const FLOWS_SCHEMA = 'chain-insights.flows.v1'\nexport const GRAPH_EXPAND_TOOL = 'graph_expand'\nexport const FLOWS_NETWORK = 'robinhood'\n\n/** How many senders and how many receivers one page shows, at most. */\nexport const FLOWS_PER_SIDE = 250\n/** The view data of one answer: at most this many addresses, the centre included... */\nexport const FLOWS_MAX_NODES = 500\n/**\n * ...and under this many characters of JSON. Hosts drop an app tool result\n * over about 150,000 characters.\n */\nexport const FLOWS_MAX_CHARS = 140_000\n/**\n * The graph endpoint cuts a reply at 200 rows, whatever the LIMIT, so one side\n * of a page is read in reads of at most this many rows.\n */\nexport const FLOWS_READ_ROWS = 200\n/** The text of a node answer holds at most this many lines. */\nexport const FLOWS_SUMMARY_MAX_LINES = 20\n/** Where a graph_expand page may start on each side, at most. */\nexport const FLOWS_MAX_OFFSET = 10_000\n\nexport const TRANSFERS_SCHEMA = 'chain-insights.transfers.v1'\n/** A link answer lists at most this many transfers... */\nexport const TRANSFERS_MAX = 50\n/**\n * ...from the rows one read brings back. A facts read takes no ORDER BY and\n * the server cuts a reply at 200 rows, so the read asks for the whole cap and\n * the newest rows are picked here.\n */\nexport const TRANSFERS_READ_ROWS = 200\n/** The text of a link answer names at most this many transfers. */\nexport const TRANSFERS_SUMMARY_ROWS = 5\n/** A paged link answer reads at most this many days (a week) in one call: a sparse link costs at most this many reads a page, and a week of it comes back at once. */\nexport const TRANSFERS_MAX_DAYS = 7\n/** Where a paged link answer stops reading back when the caller names no first_day. */\nexport const TRANSFERS_FLOOR_DAY = '2015-01-01'\n\nexport const ADDRESS_SCHEMA = 'chain-insights.address.v1'\n\nexport type FlowNode = {\n address: string\n role: string\n labels: string[]\n total_in_usd: number\n total_out_usd: number\n degree_in: number\n degree_out: number\n}\n\nexport type FlowEdge = {\n from: string\n to: string\n usd: number\n tx_count: number\n first_seen_ms: number\n last_seen_ms: number\n}\n\nexport type FlowCursor = { in_offset: number; out_offset: number }\n\n/** The links of the centre not loaded yet, past the cursor, on each side. */\nexport type FlowRemaining = { senders: number; receivers: number }\n\nexport type FlowView = {\n schema: typeof FLOWS_SCHEMA\n network: string\n center: string\n nodes: FlowNode[]\n edges: FlowEdge[]\n cursor: FlowCursor\n truncated: boolean\n /** Set on every node page. A view that does not know it ignores it. */\n remaining?: FlowRemaining\n}\n\ntype Row = Record<string, unknown>\n\nexport type FlowsPage = {\n center: Row\n senders: Row[]\n receivers: Row[]\n inOffset: number\n outOffset: number\n}\n\n/** One graph_query answer as the remote client returns it. */\nexport type GraphQueryAnswer = {\n content?: Array<{ type: string; text?: string }>\n structuredContent?: Record<string, unknown>\n isError?: boolean\n}\n\nexport type FlowsToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n isError: boolean\n}\n\nexport type FlowsDependencies = {\n /** One graph_query call through the proxy's remote client. */\n graphQuery: (args: { network: string; query: string }) => Promise<GraphQueryAnswer>\n /**\n * The whole refusal of a failed read, text and structured facts\n * (chain-insights.refusal.v1: the free tier spent, a wallet that cannot\n * pay). When given it replaces describeFailure, so the view can say why in\n * the viewer's own words and time.\n */\n refusal?: (err: unknown) => Promise<FlowsToolResult>\n /** The text of a call that threw (payment required, transport failure). */\n describeFailure: (err: unknown) => string\n /** Why no read can run (the graph endpoint is not connected), checked after the arguments. */\n unavailable?: () => string | undefined\n now?: () => Date\n}\n\nexport const INVALID_ADDRESS_TEXT =\n 'invalid_address: a full 0x address of 40 hexadecimal characters is needed, for example 0x04911a118f11c75667e4d0dfb8e640af5a353550'\nexport const OFFSET_TOO_LARGE_TEXT = `invalid_offset: in_offset and out_offset must each be at most ${FLOWS_MAX_OFFSET}`\nexport const OFFSET_NEGATIVE_TEXT =\n 'invalid_offset: in_offset and out_offset must each be a whole number, 0 or more'\n\nexport const INVALID_DAY_TEXT =\n 'invalid_day: day must be a calendar date written YYYY-MM-DD (UTC), for example 2026-07-10'\nexport const BOTH_FORMS_TEXT =\n 'invalid_arguments: pass address (with in_offset and out_offset) to expand a node, or from, to and day to list the transfers of a link, not both'\nexport const INVALID_LIMIT_TEXT = 'invalid_limit: limit must be a whole number from 1 to 50'\nexport const INVALID_SKIP_TEXT = 'invalid_skip: skip must be a whole number of 0 or more'\nexport const INVALID_FIRST_DAY_TEXT =\n 'invalid_first_day: first_day must be a calendar date written YYYY-MM-DD (UTC), not after day'\nexport const DETAILS_FORM_TEXT =\n 'invalid_arguments: details takes address alone; pass no from, to, day or offsets with it'\n\nconst ADDRESS_PATTERN = /^0x[0-9a-f]{40}$/\nconst DAY_PATTERN = /^\\d{4}-\\d{2}-\\d{2}$/\nconst CODE_PREFIX = /^([a-z][a-z0-9_]*):\\s*/\n\n/**\n * The address lower-cased, or null when it is not 0x and 40 hexadecimal\n * characters. Only an address that passes is ever written into a read, so the\n * reads can carry it as a literal.\n */\nexport function normalizeFlowsAddress(raw: unknown): string | null {\n if (typeof raw !== 'string') return null\n const address = raw.trim().toLowerCase()\n return ADDRESS_PATTERN.test(address) ? address : null\n}\n\n/**\n * The day as YYYY-MM-DD when it is a real calendar date, or null. Only a day\n * that passes is ever written into a read.\n */\nexport function normalizeFlowsDay(raw: unknown): string | null {\n if (typeof raw !== 'string') return null\n const day = raw.trim()\n if (!DAY_PATTERN.test(day)) return null\n const time = Date.parse(`${day}T00:00:00Z`)\n if (Number.isNaN(time) || new Date(time).toISOString().slice(0, 10) !== day) return null\n return day\n}\n\n/**\n * The one facts read of a link: the transfers from one address to another on\n * one day. A facts read names the pair with one day, takes no ORDER BY and\n * holds at most 200 rows, so the read asks for the whole cap and the order is\n * made in buildTransfersView. Both addresses and the day have passed their\n * checks, so they are written into the read as literals.\n */\nexport function transfersReadFor(from: string, to: string, day: string): string {\n return (\n `USE facts MATCH (a:Address {address: \"${from}\"})-[t:TRANSFER]->(b:Address {address: \"${to}\"}) ` +\n `WHERE t.block_date = \"${day}\" ` +\n 'RETURN t.tx_id AS tx_id, t.block_timestamp AS block_timestamp, t.amount AS amount, ' +\n `t.asset_symbol AS asset_symbol, t.amount_usd AS amount_usd LIMIT ${TRANSFERS_READ_ROWS}`\n )\n}\n\n/** The UTC day before a YYYY-MM-DD day. */\nexport function dayBefore(day: string): string {\n return new Date(Date.parse(`${day}T00:00:00Z`) - 86_400_000).toISOString().slice(0, 10)\n}\n\n/**\n * The one topology read of a details call: the address alone, with its\n * lifetime rollups and activity span. The address has passed its check, so it\n * is written into the read as a literal.\n */\nexport function detailsReadFor(address: string): string {\n return (\n `USE topology MATCH (b:Address {address: \"${address}\"}) RETURN ${NODE_FIELDS}, ` +\n 'b.first_activity_timestamp AS first_activity_timestamp, b.last_activity_timestamp AS last_activity_timestamp LIMIT 1'\n )\n}\n\nexport type AddressView = FlowNode & {\n schema: typeof ADDRESS_SCHEMA\n network: string\n is_exchange: boolean\n is_sanctioned: boolean\n is_scam: boolean\n is_victim: boolean\n pool: boolean\n first_activity_timestamp: number | null\n last_activity_timestamp: number | null\n}\n\n/** chain-insights.address.v1 from the one row of a details read. */\nexport function buildAddressView(network: string, address: string, row: Row): AddressView {\n const node = flowsNodeOf({ ...row, address })\n return {\n schema: ADDRESS_SCHEMA,\n network,\n ...node,\n is_exchange: row.is_exchange === true,\n is_sanctioned: row.is_sanctioned === true,\n is_scam: row.is_scam === true,\n is_victim: row.is_victim === true,\n pool: row.pool === true,\n first_activity_timestamp: flowsNumberOrNull(row.first_activity_timestamp),\n last_activity_timestamp: flowsNumberOrNull(row.last_activity_timestamp),\n }\n}\n\n/** The one line of a details answer. */\nexport function addressSummary(view: AddressView): string {\n return (\n `${view.address} on ${view.network}: ${roleWord(view.role)}; lifetime ${formatFlowsUsd(view.total_in_usd)} in, ` +\n `${formatFlowsUsd(view.total_out_usd)} out; ${view.degree_in} senders and ${view.degree_out} receivers in the topology graph` +\n (view.labels.length ? `; labels ${view.labels.join(', ')}` : '') +\n '.'\n )\n}\n\nconst NODE_FIELDS =\n 'b.address AS address, b.labels AS labels, b.is_exchange AS is_exchange, ' +\n 'b.is_sanctioned AS is_sanctioned, b.is_scam AS is_scam, b.is_victim AS is_victim, b:Pool AS pool, ' +\n 'b.total_in_usd AS total_in_usd, b.total_out_usd AS total_out_usd, b.degree_in AS degree_in, b.degree_out AS degree_out'\nconst PARTY_FIELDS =\n NODE_FIELDS +\n ', f.amount_usd_sum AS usd, f.tx_count AS tx_count, ' +\n 'f.first_seen_timestamp AS first_seen, f.last_seen_timestamp AS last_seen'\n// Newest link first, the address breaking a tie, so a page and the next one\n// never share or skip a link.\nconst PAGE_ORDER = ' ORDER BY f.last_seen_timestamp DESC, b.address'\n\n/** One anchored read of a page, with the SKIP and LIMIT it carries. */\nexport type FlowsRead = { id: 'node' | 'out' | 'in'; query: string; skip: number; limit: number }\n\n/**\n * The anchored reads of one page: the node, then the receivers, then the\n * senders. Each side asks for one row more than it shows: the extra row says\n * another page exists. A reply holds at most FLOWS_READ_ROWS rows, so a side\n * is read in chunks on the same order, each starting where the last one ends.\n */\nexport function flowsReadsFor(address: string, inOffset: number, outOffset: number): FlowsRead[] {\n const side = (id: 'out' | 'in', offset: number, match: string): FlowsRead[] => {\n const reads: FlowsRead[] = []\n for (let done = 0; done < FLOWS_PER_SIDE + 1; done += FLOWS_READ_ROWS) {\n const skip = offset + done\n const limit = Math.min(FLOWS_READ_ROWS, FLOWS_PER_SIDE + 1 - done)\n reads.push({\n id,\n query: `USE topology MATCH ${match} RETURN ${PARTY_FIELDS}${PAGE_ORDER}${skip > 0 ? ` SKIP ${skip}` : ''} LIMIT ${limit}`,\n skip,\n limit,\n })\n }\n return reads\n }\n return [\n {\n id: 'node',\n query: `USE topology MATCH (b:Address {address: '${address}'}) RETURN ${NODE_FIELDS} LIMIT 1`,\n skip: 0,\n limit: 1,\n },\n ...side('out', outOffset, `(a:Address {address: '${address}'})-[f:FLOWS_TO]->(b:Address)`),\n ...side('in', inOffset, `(b:Address)-[f:FLOWS_TO]->(a:Address {address: '${address}'})`),\n ]\n}\n\n/** The role word of an address, first match wins. */\nexport function flowsRole(row: Row): string {\n if (row.is_exchange === true) return 'exchange'\n if (row.is_sanctioned === true) return 'sanctioned'\n if (row.is_scam === true) return 'scam'\n if (row.is_victim === true) return 'victim'\n if (row.pool === true) return 'pool'\n if (Array.isArray(row.labels) && row.labels.includes('SelfTrader')) return 'self_trader'\n return 'other'\n}\n\n/** The role as the text answers write it: a role code becomes words. */\nfunction roleWord(role: string): string {\n return role === 'self_trader' ? 'self-trading contract' : role\n}\n\nfunction flowsFloat(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0\n}\n\nfunction flowsInt(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : 0\n}\n\nfunction flowsNodeOf(row: Row): FlowNode {\n const labels = Array.isArray(row.labels)\n ? row.labels.filter((label): label is string => typeof label === 'string')\n : []\n return {\n address: typeof row.address === 'string' ? row.address : '',\n role: flowsRole(row),\n labels,\n total_in_usd: flowsFloat(row.total_in_usd),\n total_out_usd: flowsFloat(row.total_out_usd),\n degree_in: flowsInt(row.degree_in),\n degree_out: flowsInt(row.degree_out),\n }\n}\n\nfunction assembleFlowView(\n network: string,\n page: FlowsPage,\n senders: Row[],\n receivers: Row[],\n truncated: boolean\n): FlowView {\n const center = flowsNodeOf(page.center)\n const cursor = {\n in_offset: page.inOffset + senders.length,\n out_offset: page.outOffset + receivers.length,\n }\n const view: FlowView = {\n schema: FLOWS_SCHEMA,\n network,\n center: center.address,\n nodes: [center],\n edges: [],\n cursor,\n truncated,\n remaining: {\n senders: Math.max(0, center.degree_in - cursor.in_offset),\n receivers: Math.max(0, center.degree_out - cursor.out_offset),\n },\n }\n const seen = new Set([center.address])\n const add = (row: Row, incoming: boolean) => {\n const node = flowsNodeOf(row)\n if (!seen.has(node.address)) {\n seen.add(node.address)\n view.nodes.push(node)\n }\n view.edges.push({\n from: incoming ? node.address : center.address,\n to: incoming ? center.address : node.address,\n usd: flowsFloat(row.usd),\n tx_count: flowsInt(row.tx_count),\n first_seen_ms: flowsInt(row.first_seen),\n last_seen_ms: flowsInt(row.last_seen),\n })\n }\n for (const row of senders) add(row, true)\n for (const row of receivers) add(row, false)\n return view\n}\n\nfunction fitsFlowBudget(view: FlowView): boolean {\n return view.nodes.length <= FLOWS_MAX_NODES && JSON.stringify(view).length < FLOWS_MAX_CHARS\n}\n\n/**\n * How many senders and receivers stay after `drops` of the oldest links go,\n * one at a time from the longer side, the senders first on a tie.\n */\nfunction keptAfterDrops(senders: number, receivers: number, drops: number): [number, number] {\n let s = senders\n let r = receivers\n for (let left = Math.min(drops, s + r); left > 0; left -= 1) {\n if (s >= r) s -= 1\n else r -= 1\n }\n return [s, r]\n}\n\n/**\n * flows.v1 from one page: the centre first, then the senders and the\n * receivers, each newest first, at most FLOWS_PER_SIDE a side. When the view\n * data would hold more than FLOWS_MAX_NODES addresses or reach FLOWS_MAX_CHARS\n * characters, the oldest links go first, the view is marked truncated, and the\n * cursor still says where the next page starts.\n *\n * Each dropped link only makes the view smaller, so the fewest drops that fit\n * are found by halving: about ten views are measured for a full page, not one\n * per dropped link.\n */\nexport function buildFlowView(network: string, page: FlowsPage): FlowView {\n const overflow = page.senders.length > FLOWS_PER_SIDE || page.receivers.length > FLOWS_PER_SIDE\n const senders = page.senders.slice(0, FLOWS_PER_SIDE)\n const receivers = page.receivers.slice(0, FLOWS_PER_SIDE)\n const viewAfter = (drops: number) => {\n const [s, r] = keptAfterDrops(senders.length, receivers.length, drops)\n return assembleFlowView(\n network,\n page,\n senders.slice(0, s),\n receivers.slice(0, r),\n overflow || drops > 0\n )\n }\n // Dropping every link is the floor: that view is answered even when it does\n // not fit.\n let low = 0\n let high = senders.length + receivers.length\n while (low < high) {\n const mid = (low + high) >> 1\n if (fitsFlowBudget(viewAfter(mid))) high = mid\n else low = mid + 1\n }\n return viewAfter(low)\n}\n\nexport function formatFlowsUsd(value: number): string {\n if (!(value > 0)) return '$0'\n if (value < 0.01) return 'under $0.01'\n const whole = Math.floor(value)\n const cents = Math.round((value - whole) * 100)\n if (cents === 100) return formatFlowsUsd(whole + 1)\n const grouped = whole.toFixed(0).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')\n return `$${grouped}.${String(cents).padStart(2, '0')}`\n}\n\nfunction formatFlowsAge(lastSeenMs: number, now: Date): string {\n if (lastSeenMs <= 0) return 'at an unknown time'\n const date = new Date(lastSeenMs).toISOString().slice(0, 10)\n const days = Math.trunc((now.getTime() - lastSeenMs) / 86_400_000)\n if (days < 1) return `${date} (less than a day ago)`\n if (days === 1) return `${date} (1 day ago)`\n return `${date} (${days} days ago)`\n}\n\n/** The role word, with up to three address labels beside it. */\nfunction roleText(node: FlowNode | undefined): string {\n if (!node) return 'other'\n const word = roleWord(node.role)\n if (node.labels.length === 0) return word\n return `${word} (${node.labels.slice(0, 3).join(', ')})`\n}\n\nfunction sideLines(title: string, parties: string[]): string[] {\n if (parties.length === 0) return [`${title}, newest first: none.`]\n const lines = [`${title}, newest first (${parties.length}):`]\n // A side with more than six counterparties lists two on a line, so a full\n // page stays within the line budget.\n const perLine = parties.length > 6 ? 2 : 1\n for (let start = 0; start < parties.length; start += perLine) {\n lines.push(`- ${parties.slice(start, start + perLine).join('; ')}`)\n }\n return lines\n}\n\n/**\n * The text of a node answer: the centre, its role and lifetime totals, then\n * every counterparty of the view with its USD, transaction count and last-seen\n * date and age. At most FLOWS_SUMMARY_MAX_LINES lines.\n */\nexport function flowsSummary(view: FlowView, now: Date): string {\n const nodes = new Map(view.nodes.map((node) => [node.address, node]))\n const center = nodes.get(view.center)\n const party = (address: string, edge: FlowEdge) =>\n `${address} ${roleText(nodes.get(address))}, ${formatFlowsUsd(edge.usd)} in ${edge.tx_count} tx, last seen ${formatFlowsAge(edge.last_seen_ms, now)}`\n const senders: string[] = []\n const receivers: string[] = []\n for (const edge of view.edges) {\n if (edge.to === view.center) senders.push(party(edge.from, edge))\n else receivers.push(party(edge.to, edge))\n }\n const lines = [\n `Money flows of ${view.center} on ${view.network}: ${roleText(center)}; lifetime ${formatFlowsUsd(center?.total_in_usd ?? 0)} in, ${formatFlowsUsd(center?.total_out_usd ?? 0)} out; ${center?.degree_in ?? 0} senders and ${center?.degree_out ?? 0} receivers in the topology graph.`,\n ...sideLines('Recent senders', senders),\n ...sideLines('Recent receivers', receivers),\n ]\n const body = lines.slice(0, FLOWS_SUMMARY_MAX_LINES - 2)\n const footer = pagingLines(view, senders.length, receivers.length, center)\n return [...body, ...footer].join('\\n')\n}\n\n/** Where this page sits, and that the picture loads the rest when an address is clicked. */\nfunction pagingLines(\n view: FlowView,\n shownSenders: number,\n shownReceivers: number,\n center: FlowNode | undefined\n): string[] {\n const totalIn = center?.degree_in ?? 0\n const totalOut = center?.degree_out ?? 0\n const { in_offset: nextIn, out_offset: nextOut } = view.cursor\n const range = (shown: number, next: number, total: number) =>\n shown === 0 ? `none of ${total}` : `${next - shown + 1} to ${next} of ${total}`\n const where = `Showing senders ${range(shownSenders, nextIn, totalIn)} and receivers ${range(shownReceivers, nextOut, totalOut)}, newest first.`\n if (!view.truncated && nextIn >= totalIn && nextOut >= totalOut) return [where]\n return [\n where,\n 'More senders and receivers load when an address in the picture is double-clicked.',\n ]\n}\n\nexport type TransferRow = {\n tx_id: string\n block_timestamp: number | null\n amount: number | string | null\n asset_symbol: string | null\n amount_usd: number | null\n}\n\nexport type TransfersCursor = { day: string; skip: number }\n\nexport type TransfersView = {\n schema: typeof TRANSFERS_SCHEMA\n network: string\n from: string\n to: string\n day: string\n transfers: TransferRow[]\n truncated: boolean\n /** Paged answers only: the earliest day read, how many days the call read, and where the next page starts (null: every transfer back to first_day is listed). */\n through_day?: string\n days_read?: number\n next?: TransfersCursor | null\n}\n\nexport type TransfersPageRequest = { skip: number; firstDay: string | null; limit: number }\n\n/** A finite number, or a decimal string read as one, or null. */\nfunction flowsNumberOrNull(value: unknown): number | null {\n if (typeof value === 'number') return Number.isFinite(value) ? value : null\n if (typeof value === 'string' && value.trim() !== '') {\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : null\n }\n return null\n}\n\nfunction transferOf(row: Row): TransferRow {\n const amount =\n typeof row.amount === 'number' && Number.isFinite(row.amount)\n ? row.amount\n : typeof row.amount === 'string' && row.amount.trim() !== ''\n ? row.amount\n : null\n return {\n tx_id: typeof row.tx_id === 'string' ? row.tx_id : '',\n block_timestamp: flowsNumberOrNull(row.block_timestamp),\n amount,\n asset_symbol:\n typeof row.asset_symbol === 'string' && row.asset_symbol !== '' ? row.asset_symbol : null,\n amount_usd: flowsNumberOrNull(row.amount_usd),\n }\n}\n\n/**\n * chain-insights.transfers.v1 from the rows of one facts read: newest first,\n * at most TRANSFERS_MAX, truncated when more rows than that came back. The\n * facts layer takes no ORDER BY, so the order is made here.\n */\nexport function buildTransfersView(\n network: string,\n from: string,\n to: string,\n day: string,\n rows: Row[]\n): TransfersView {\n const newestFirst = rows\n .map(transferOf)\n .sort((a, b) => (b.block_timestamp ?? -Infinity) - (a.block_timestamp ?? -Infinity))\n return {\n schema: TRANSFERS_SCHEMA,\n network,\n from,\n to,\n day,\n transfers: newestFirst.slice(0, TRANSFERS_MAX),\n truncated: newestFirst.length > TRANSFERS_MAX,\n }\n}\n\nfunction transferLine(transfer: TransferRow): string {\n const time =\n transfer.block_timestamp === null\n ? 'at an unknown time'\n : `${new Date(transfer.block_timestamp).toISOString().slice(0, 19).replace('T', ' ')} UTC`\n const amount = transfer.amount === null ? 'an unknown amount' : String(transfer.amount)\n const asset = transfer.asset_symbol ? ` ${transfer.asset_symbol}` : ''\n const usd = transfer.amount_usd === null ? 'no USD price' : formatFlowsUsd(transfer.amount_usd)\n return `- ${time}, ${amount}${asset}, ${usd}, tx ${transfer.tx_id}`\n}\n\n/** The short text of a link answer: the pair, the day, the count and the newest few transfers. */\nexport function transfersSummary(view: TransfersView): string {\n const paged = view.through_day !== undefined\n const span = paged && view.through_day !== view.day ? `${view.through_day} to ${view.day}` : view.day\n const head = `Transfers from ${view.from} to ${view.to} on ${span} (UTC) on ${view.network}`\n if (view.transfers.length === 0) {\n return paged && view.next ? `${head}: none; earlier days remain before ${view.next.day}.` : `${head}: none.`\n }\n const count = view.truncated\n ? paged\n ? `${view.transfers.length}, and a day holds more than one read lists`\n : `the newest ${view.transfers.length}, and the day holds more`\n : `${view.transfers.length}`\n const lines = [\n `${head}: ${count}, newest first.`,\n ...view.transfers.slice(0, TRANSFERS_SUMMARY_ROWS).map(transferLine),\n ]\n const rest = view.transfers.length - TRANSFERS_SUMMARY_ROWS\n if (rest > 0) lines.push(`- and ${rest} more in the picture.`)\n if (paged && view.next) lines.push(`- earlier transfers remain, from ${view.next.day} back.`)\n return lines.join('\\n')\n}\n\nfunction errorResult(text: string): FlowsToolResult {\n return { content: [{ type: 'text', text }], isError: true }\n}\n\n/** The result of a failed read: the structured refusal when the proxy builds one, else the text. */\nasync function failedRead(deps: FlowsDependencies, err: unknown): Promise<FlowsToolResult> {\n if (deps.refusal) {\n try {\n return await deps.refusal(err)\n } catch {\n // The refusal builder itself failed: the plain text still names the cause.\n }\n }\n return errorResult(deps.describeFailure(err))\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction answerText(answer: GraphQueryAnswer): string {\n return (answer.content ?? [])\n .map((block) => (block.type === 'text' && typeof block.text === 'string' ? block.text : ''))\n .filter(Boolean)\n .join('\\n')\n .trim()\n}\n\n/**\n * The refusal of a read that did not answer, naming its code first:\n * error_detail.code when the graph endpoint sent its typed refusal, the code\n * its text starts with otherwise, and graph_query_failed when it names none.\n * The view marks the address it was expanding.\n */\nexport function refusalText(answer: GraphQueryAnswer): string {\n const text = answerText(answer)\n const detail = isRecord(answer.structuredContent)\n ? answer.structuredContent.error_detail\n : undefined\n const detailCode = isRecord(detail) && typeof detail.code === 'string' ? detail.code : ''\n const textCode = CODE_PREFIX.exec(text)?.[1] ?? ''\n const code = detailCode || textCode || 'graph_query_failed'\n const rest = textCode === code ? text.replace(CODE_PREFIX, '') : text\n return rest ? `${code}: ${rest}` : `${code}: the graph endpoint refused the read`\n}\n\n/** The endpoint says it cut the reply short (facts.query.truncated). */\nfunction cutByEndpoint(answer: GraphQueryAnswer): boolean {\n const facts = isRecord(answer.structuredContent) ? answer.structuredContent.facts : undefined\n const query = isRecord(facts) ? facts.query : undefined\n return isRecord(query) && query.truncated === true\n}\n\nfunction rowsOf(answer: GraphQueryAnswer): Row[] | null {\n const facts = isRecord(answer.structuredContent) ? answer.structuredContent.facts : undefined\n const query = isRecord(facts) ? facts.query : undefined\n const results = isRecord(query) ? query.results : undefined\n return Array.isArray(results) ? results.filter(isRecord) : null\n}\n\ntype Checked<T> = T | { error: string }\n\nfunction checkNetwork(args: Record<string, unknown>): Checked<string> {\n const rawNetwork = typeof args.network === 'string' ? args.network.trim().toLowerCase() : ''\n if (!rawNetwork) return { error: 'invalid_network: network is required; pass robinhood' }\n if (rawNetwork !== FLOWS_NETWORK) {\n return {\n error: `invalid_network: graph_expand reads the robinhood graph only; got \"${String(args.network).trim()}\"`,\n }\n }\n return FLOWS_NETWORK\n}\n\n/** The address of a node or of one end of a link; `name` says which end in a link refusal. */\nfunction checkAddress(raw: unknown, name?: string): Checked<string> {\n const address = normalizeFlowsAddress(raw)\n if (address) return address\n return {\n error: name\n ? INVALID_ADDRESS_TEXT.replace('invalid_address:', `invalid_address (${name}):`)\n : INVALID_ADDRESS_TEXT,\n }\n}\n\nfunction checkDay(raw: unknown): Checked<string> {\n const day = normalizeFlowsDay(raw)\n return day ?? { error: INVALID_DAY_TEXT }\n}\n\nfunction checkLimit(value: unknown): Checked<number> {\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value > TRANSFERS_MAX) {\n return { error: INVALID_LIMIT_TEXT }\n }\n return value\n}\n\nfunction checkSkip(value: unknown): Checked<number> {\n if (value === undefined || value === null) return 0\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) return { error: INVALID_SKIP_TEXT }\n return value\n}\n\nfunction checkFirstDay(value: unknown, day: string): Checked<string | null> {\n if (value === undefined || value === null) return null\n const first = normalizeFlowsDay(value)\n if (!first || first > day) return { error: INVALID_FIRST_DAY_TEXT }\n return first\n}\n\nfunction checkOffset(value: unknown): Checked<number> {\n if (value === undefined || value === null) return 0\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {\n return { error: OFFSET_NEGATIVE_TEXT }\n }\n if (value > FLOWS_MAX_OFFSET) return { error: OFFSET_TOO_LARGE_TEXT }\n return value\n}\n\n/**\n * Read and answer one node page. The reads run one after another: the node\n * first, so an address the graph does not hold costs one read; then the\n * receivers and the senders, the chunks of a side joined in order. A chunk that\n * comes back short, and not cut by the endpoint, ends its side, so the next\n * chunk of that side is not read or billed. The first read that does not\n * answer ends the call.\n */\nasync function runNode(\n deps: FlowsDependencies,\n network: string,\n address: string,\n inOffset: number,\n outOffset: number\n): Promise<FlowsToolResult> {\n const unavailable = deps.unavailable?.()\n if (unavailable) return errorResult(unavailable)\n const rows: Record<FlowsRead['id'], Row[]> = { node: [], out: [], in: [] }\n const ended = new Set<FlowsRead['id']>()\n for (const read of flowsReadsFor(address, inOffset, outOffset)) {\n if (ended.has(read.id)) continue\n let answer: GraphQueryAnswer\n try {\n answer = await deps.graphQuery({ network, query: read.query })\n } catch (err) {\n return failedRead(deps, err)\n }\n if (answer.isError === true) return errorResult(refusalText(answer))\n const found = rowsOf(answer)\n if (!found) {\n return errorResult(\n 'graph_query_failed: the graph endpoint answered without chain-insights.result.v1 rows'\n )\n }\n rows[read.id].push(...found)\n if (read.id === 'node' && found.length === 0) {\n return errorResult(`${address} is not in the ${network} topology graph`)\n }\n if (found.length < read.limit && !cutByEndpoint(answer)) ended.add(read.id)\n }\n const view = buildFlowView(network, {\n center: rows.node[0] ?? {},\n senders: rows.in,\n receivers: rows.out,\n inOffset,\n outOffset,\n })\n const now = deps.now ? deps.now() : new Date()\n return {\n content: [{ type: 'text', text: flowsSummary(view, now) }],\n structuredContent: view as unknown as Record<string, unknown>,\n isError: false,\n }\n}\n\n/** Read and answer the transfers of one link on one day: a single facts read. */\nasync function runLink(\n deps: FlowsDependencies,\n network: string,\n from: string,\n to: string,\n day: string\n): Promise<FlowsToolResult> {\n const unavailable = deps.unavailable?.()\n if (unavailable) return errorResult(unavailable)\n let answer: GraphQueryAnswer\n try {\n answer = await deps.graphQuery({ network, query: transfersReadFor(from, to, day) })\n } catch (err) {\n return failedRead(deps, err)\n }\n if (answer.isError === true) return errorResult(refusalText(answer))\n const rows = rowsOf(answer)\n if (!rows) {\n return errorResult(\n 'graph_query_failed: the graph endpoint answered without chain-insights.result.v1 rows'\n )\n }\n const view = buildTransfersView(network, from, to, day, rows)\n return {\n content: [{ type: 'text', text: transfersSummary(view) }],\n structuredContent: view as unknown as Record<string, unknown>,\n isError: false,\n }\n}\n\n/** One facts read of a day, as the paged walk needs it: the rows newest first, or the error that ends the call. */\nasync function readDay(\n deps: FlowsDependencies,\n network: string,\n from: string,\n to: string,\n day: string\n): Promise<{ rows: TransferRow[]; cut: boolean } | { error: string }> {\n let answer: GraphQueryAnswer\n try {\n answer = await deps.graphQuery({ network, query: transfersReadFor(from, to, day) })\n } catch (err) {\n return { error: deps.describeFailure(err) }\n }\n if (answer.isError === true) return { error: refusalText(answer) }\n const rows = rowsOf(answer)\n if (!rows) {\n return { error: 'graph_query_failed: the graph endpoint answered without chain-insights.result.v1 rows' }\n }\n const newestFirst = rows\n .map(transferOf)\n .sort((a, b) => (b.block_timestamp ?? -Infinity) - (a.block_timestamp ?? -Infinity))\n return { rows: newestFirst, cut: rows.length >= TRANSFERS_READ_ROWS }\n}\n\n/**\n * Read and answer one page of a link's transfers: from `day` back, one day a\n * read, until the page holds `limit` transfers, TRANSFERS_MAX_DAYS days were\n * read, or the day before first_day is reached. `skip` passes over the\n * transfers of `day` an earlier page listed. The first read that does not\n * answer ends the call.\n */\nasync function runLinkPage(\n deps: FlowsDependencies,\n network: string,\n from: string,\n to: string,\n day: string,\n page: TransfersPageRequest\n): Promise<FlowsToolResult> {\n const unavailable = deps.unavailable?.()\n if (unavailable) return errorResult(unavailable)\n const floor = page.firstDay ?? TRANSFERS_FLOOR_DAY\n const transfers: TransferRow[] = []\n let current = day\n let skip = page.skip\n let daysRead = 0\n let through = day\n let truncated = false\n let next: TransfersCursor | null = null\n for (;;) {\n if (current < floor) break\n if (daysRead >= TRANSFERS_MAX_DAYS) {\n next = { day: current, skip }\n break\n }\n const read = await readDay(deps, network, from, to, current)\n if ('error' in read) return errorResult(read.error)\n daysRead += 1\n through = current\n if (read.cut) truncated = true\n const rest = read.rows.slice(skip)\n const room = page.limit - transfers.length\n if (rest.length > room) {\n transfers.push(...rest.slice(0, room))\n next = { day: current, skip: skip + room }\n break\n }\n transfers.push(...rest)\n const earlier = dayBefore(current)\n if (transfers.length >= page.limit) {\n next = earlier < floor ? null : { day: earlier, skip: 0 }\n break\n }\n current = earlier\n skip = 0\n }\n const view: TransfersView = {\n schema: TRANSFERS_SCHEMA,\n network,\n from,\n to,\n day,\n transfers,\n truncated,\n through_day: through,\n days_read: daysRead,\n next,\n }\n return {\n content: [{ type: 'text', text: transfersSummary(view) }],\n structuredContent: view as unknown as Record<string, unknown>,\n isError: false,\n }\n}\n\n/** Read and answer the details of one address: a single anchored topology read. */\nasync function runDetails(\n deps: FlowsDependencies,\n network: string,\n address: string\n): Promise<FlowsToolResult> {\n const unavailable = deps.unavailable?.()\n if (unavailable) return errorResult(unavailable)\n let answer: GraphQueryAnswer\n try {\n answer = await deps.graphQuery({ network, query: detailsReadFor(address) })\n } catch (err) {\n return failedRead(deps, err)\n }\n if (answer.isError === true) return errorResult(refusalText(answer))\n const rows = rowsOf(answer)\n if (!rows) {\n return errorResult(\n 'graph_query_failed: the graph endpoint answered without chain-insights.result.v1 rows'\n )\n }\n if (rows.length === 0) return errorResult(`${address} is not in the ${network} topology graph`)\n const view = buildAddressView(network, address, rows[0]!)\n return {\n content: [{ type: 'text', text: addressSummary(view) }],\n structuredContent: view as unknown as Record<string, unknown>,\n isError: false,\n }\n}\n\nfunction given(record: Record<string, unknown>, keys: string[]): boolean {\n return keys.some((key) => record[key] !== undefined && record[key] !== null)\n}\n\n/**\n * graph_expand, the node form {network, address, in_offset?, out_offset?} or the\n * link form {network, from, to, day}. Every argument is checked before the\n * first read.\n */\nexport async function handleGraphExpand(\n args: unknown,\n deps: FlowsDependencies\n): Promise<FlowsToolResult> {\n const record = isRecord(args) ? args : {}\n const network = checkNetwork(record)\n if (typeof network !== 'string') return errorResult(network.error)\n\n const isLink = given(record, ['from', 'to', 'day'])\n if (isLink && given(record, ['address', 'in_offset', 'out_offset', 'details']))\n return errorResult(BOTH_FORMS_TEXT)\n\n if (isLink) {\n const from = checkAddress(record.from, 'from')\n if (typeof from !== 'string') return errorResult(from.error)\n const to = checkAddress(record.to, 'to')\n if (typeof to !== 'string') return errorResult(to.error)\n const day = checkDay(record.day)\n if (typeof day !== 'string') return errorResult(day.error)\n // A limit, a skip or a first_day asks for a page across days; without them the call is the one-day read.\n if (given(record, ['limit', 'skip', 'first_day'])) {\n const limit = checkLimit(record.limit)\n if (typeof limit !== 'number') return errorResult(limit.error)\n const skip = checkSkip(record.skip)\n if (typeof skip !== 'number') return errorResult(skip.error)\n const firstDay = checkFirstDay(record.first_day, day)\n if (firstDay !== null && typeof firstDay !== 'string') return errorResult(firstDay.error)\n return runLinkPage(deps, network, from, to, day, { skip, firstDay, limit })\n }\n return runLink(deps, network, from, to, day)\n }\n\n if (record.details !== undefined && record.details !== null) {\n if (record.details !== true) return errorResult(DETAILS_FORM_TEXT)\n if (given(record, ['in_offset', 'out_offset'])) return errorResult(DETAILS_FORM_TEXT)\n const address = checkAddress(record.address)\n if (typeof address !== 'string') return errorResult(address.error)\n return runDetails(deps, network, address)\n }\n\n const address = checkAddress(record.address)\n if (typeof address !== 'string') return errorResult(address.error)\n const inOffset = checkOffset(record.in_offset)\n if (typeof inOffset !== 'number') return errorResult(inOffset.error)\n const outOffset = checkOffset(record.out_offset)\n if (typeof outOffset !== 'number') return errorResult(outOffset.error)\n return runNode(deps, network, address, inOffset, outOffset)\n}\n\nexport const GRAPH_EXPAND_TITLE = 'Expand a node or a link in the picture'\n\nexport const GRAPH_EXPAND_DESCRIPTION =\n 'Expand an open Chain Insights picture. Called by the view when the investigator clicks, never by the model. ' +\n 'A node, {network, address, in_offset?, out_offset?}, loads the newest senders and receivers of one address ' +\n '(up to 250 a side, from the offsets); billed as at most five graph_query topology reads. A link, {network, from, to, day}, ' +\n 'lists the transfers between two addresses on one UTC day (YYYY-MM-DD), newest first, at most 50; billed as ' +\n 'one graph_query facts read. A link page, {network, from, to, day, limit, skip?, first_day?}, lists `limit` (1-50) ' +\n 'transfers from `day` back across days, newest first, and answers a `next` cursor ({day, skip}) while older ones ' +\n 'remain; billed as at most seven facts reads (a week). Details, {network, address, details: true}, answer the lifetime totals, ' +\n 'counts, role and labels of one address; billed as one topology read. Read-only; an argument refused before a read costs nothing.'\n","import { createHash } from 'node:crypto'\nimport { mkdir, readFile, rename, writeFile } from 'node:fs/promises'\nimport path from 'node:path'\nimport { CACHE_TTL_MS, chainInsightsHome } from './cache-location.js'\nimport type { GraphSchemaDocument } from './graph-schema.js'\n\n// The graph schema of one network on one endpoint, kept on disk beside the tool\n// list cache (src/mcp/schema-cache.ts) with the same home and the same 24 hour\n// lifetime: ~/.chain-insights/cache/schema-<network>-<endpoint hash>.json.\n//\n// A schema built while a read failed is kept for a short time only. Kept for\n// 24 hours, one refused or rate-limited read would hide a section of the schema\n// for a whole day.\n\n/** How long a schema with a failed read stays fresh. */\nexport const PARTIAL_SCHEMA_TTL_MS = 10 * 60 * 1000\n\ninterface GraphSchemaCacheFile {\n cached_at: number\n complete: boolean\n endpoint: string\n document: GraphSchemaDocument\n}\n\nfunction endpointHash(endpoint: string): string {\n return createHash('sha256').update(endpoint).digest('hex').slice(0, 12)\n}\n\n/** The cache file of a network on an endpoint. The network is an identifier already checked by the caller. */\nexport function graphSchemaCachePath(network: string, endpoint: string): string {\n return path.join(chainInsightsHome(), 'cache', `schema-${network}-${endpointHash(endpoint)}.json`)\n}\n\n/**\n * The cached schema, marked cached, or null when there is none, it is stale, or\n * the file cannot be read. A cache is derived data: a damaged file is a miss and\n * the next build replaces it.\n */\nexport async function loadGraphSchemaCache(\n network: string,\n endpoint: string,\n now: Date\n): Promise<GraphSchemaDocument | null> {\n let parsed: unknown\n try {\n parsed = JSON.parse(await readFile(graphSchemaCachePath(network, endpoint), 'utf8'))\n } catch {\n return null\n }\n const file = parsed as Partial<GraphSchemaCacheFile> | null\n if (\n !file ||\n typeof file.cached_at !== 'number' ||\n file.endpoint !== endpoint ||\n file.document?.schema !== 'chain-insights.graph-schema.v1'\n ) {\n return null\n }\n const lifetime = file.complete === true ? CACHE_TTL_MS : PARTIAL_SCHEMA_TTL_MS\n const age = now.getTime() - file.cached_at\n if (age < 0 || age > lifetime) return null\n return { ...file.document, cached: true }\n}\n\n/** `network` is the name the caller asked for, the same one a later load asks with. */\nexport async function saveGraphSchemaCache(\n network: string,\n document: GraphSchemaDocument,\n endpoint: string,\n complete: boolean,\n now: Date\n): Promise<void> {\n const target = graphSchemaCachePath(network, endpoint)\n const file: GraphSchemaCacheFile = {\n cached_at: now.getTime(),\n complete,\n endpoint,\n document: { ...document, cached: false },\n }\n await mkdir(path.dirname(target), { recursive: true })\n // Written beside the target and renamed, so a second proxy reading the file\n // never sees half of it.\n const scratch = `${target}.${process.pid}.tmp`\n await writeFile(scratch, JSON.stringify(file, null, 2) + '\\n', { mode: 0o600 })\n await rename(scratch, target)\n}\n","/**\n * meta_schema: the live graph schema of one network, read from the graph\n * endpoint and kept on disk for 24 hours.\n *\n * The graph serves four read-only catalog statements on `USE topology` through\n * the ordinary graph_query tool: `CALL db.labels()`, `CALL db.relationshipTypes()`,\n * `CALL db.propertyKeys()` and `SHOW INDEXES`. They name the labels, the link\n * types, every property key and the indexes. They do not say which keys belong to\n * which kind, so the main kinds are sampled with the two probe forms the server\n * admits (`keys(a)` on addresses, `keys(r)` on a link). The facts relationships\n * and the chain lookups come from the network's published capabilities.\n *\n * One build is one MCP session and runs its reads one after another: the public\n * endpoint allows about 30 requests a minute for each IP address, and opening a\n * session costs three of them. A read that fails leaves its section empty and\n * adds a note. It never fails the tool.\n */\n\nimport { findNetworkCapability, mirrorGraphNetworkCapabilities } from './capabilities.js'\nimport type { NetworkCapability } from './capabilities.js'\nimport { PaymentRequiredError } from './client.js'\nimport { refusalText, type GraphQueryAnswer } from './flows.js'\nimport { loadGraphSchemaCache, saveGraphSchemaCache } from './graph-schema-cache.js'\n\nexport const GRAPH_SCHEMA_ID = 'chain-insights.graph-schema.v1' as const\nexport const GRAPH_SCHEMA_SOURCE = 'live catalog' as const\nexport const META_SCHEMA_TITLE = 'Graph schema'\nexport const META_SCHEMA_DESCRIPTION =\n 'Return the live graph schema of one network: the labels, the link types, the field names of an address and of each main link, the indexes, the USE facts relationships with the TRANSFER columns, and the USE chain lookups. ' +\n 'Call it first when you need field names. It is cached for 24 hours; pass refresh=true to rebuild it.'\n\n/** Fields of an address come from this many sampled nodes, and of a link from this many sampled links. */\nexport const ADDRESS_SAMPLE_LIMIT = 20\nexport const LINK_SAMPLE_LIMIT = 5\n\n/** The link types an agent queries. Each is sampled only when the graph lists it. */\nexport const SAMPLED_LINK_TYPES = [\n 'FLOWS_TO',\n 'OPERATED_BY',\n 'LINKED',\n 'SWAPPED',\n 'BRIDGED',\n 'ADDED_LIQUIDITY',\n 'REMOVED_LIQUIDITY',\n] as const\n\n// The TRANSFER columns the cypher skill lists, in its order. tests/graph-schema.test.ts\n// holds this list to the skill and to the columns the graph server maps on TRANSFER\n// (tests/fixtures/facts-columns.json).\nexport const FACTS_TRANSFER_COLUMNS = [\n 'tx_id',\n 'block_date',\n 'block_height',\n 'block_timestamp',\n 'event_index',\n 'edge_index',\n 'kind',\n 'asset_contract',\n 'asset_symbol',\n 'amount',\n 'amount_usd',\n 'price_usd',\n 'price_missing',\n 'token_id',\n 'token_standard',\n 'operator_address',\n 'raw_amount',\n 'decimals',\n] as const\n\n// `CALL db.schema.visualization()` is not read. It bills about 427 units where\n// the four statements below bill 13 to 133 each, and it adds only which labels a\n// link type joins, which the cypher skill and the served hints already say.\nconst CATALOG_READS = {\n labels: { label: 'labels', query: 'USE topology CALL db.labels()' },\n linkTypes: { label: 'link types', query: 'USE topology CALL db.relationshipTypes()' },\n propertyKeys: { label: 'property keys', query: 'USE topology CALL db.propertyKeys()' },\n indexes: { label: 'indexes', query: 'USE topology SHOW INDEXES' },\n} as const\n\nexport function addressSampleQuery(): string {\n return `USE topology MATCH (a:Address) RETURN keys(a) AS keys LIMIT ${ADDRESS_SAMPLE_LIMIT}`\n}\n\nexport function linkSampleQuery(linkType: string): string {\n return `USE topology MATCH ()-[r:${linkType}]->() RETURN keys(r) AS keys LIMIT ${LINK_SAMPLE_LIMIT}`\n}\n\nexport interface GraphSchemaIndex {\n name: string\n entity: 'node' | 'link'\n /** The labels of a node index, the link types of a link index. */\n types: string[]\n properties: string[]\n state: string\n}\n\nexport interface GraphSchemaDocument {\n schema: typeof GRAPH_SCHEMA_ID\n network: string\n built_at: string\n source: typeof GRAPH_SCHEMA_SOURCE\n cached: boolean\n /** Units the reads of the build billed, summed from the replies. A cached document keeps the units of its build. */\n billed_units: number\n layers: {\n topology: {\n labels: string[]\n link_types: string[]\n property_keys: string[]\n indexes: GraphSchemaIndex[]\n samples: Record<string, string[]>\n }\n facts: { relationships: string[]; transfer_columns: string[] }\n chain: { lookups: string[] }\n }\n notes: string[]\n}\n\n/** A refusal with its own words for the caller: a bad argument, an unserved network, an endpoint that is down. */\nexport class GraphSchemaError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'GraphSchemaError'\n }\n}\n\nexport interface GraphSchemaClient {\n callTool(request: { name: string; arguments: Record<string, unknown> }): Promise<unknown>\n}\n\ntype Row = Record<string, unknown>\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction sortedUnique(values: Iterable<string>): string[] {\n return [...new Set(values)].sort()\n}\n\nfunction stringList(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((entry): entry is string => typeof entry === 'string' && entry !== '')\n : []\n}\n\nconst NETWORK_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/\n\n/**\n * The network as a lower-case identifier. It becomes part of a file name and of\n * every query, so only an identifier passes.\n */\nexport function normalizeSchemaNetwork(raw: unknown): string {\n const network = typeof raw === 'string' ? raw.trim().toLowerCase() : ''\n if (!network) {\n throw new GraphSchemaError(\n 'invalid_network: network is required. Pass the identifier of a served network, for example robinhood.'\n )\n }\n if (!NETWORK_PATTERN.test(network)) {\n throw new GraphSchemaError(\n `invalid_network: \"${String(raw).trim()}\" is not a network identifier. Pass the identifier of a served network, for example robinhood.`\n )\n }\n return network\n}\n\n// ─── Reading ──────────────────────────────────────────────────────────────────\n\nfunction queryBlock(structured: unknown): Row | null {\n const facts = isRecord(structured) ? structured.facts : undefined\n const query = isRecord(facts) ? facts.query : undefined\n return isRecord(query) ? query : null\n}\n\n/** The `facts.query` block of one graph_query reply, from structuredContent or from the JSON text. */\nfunction answerQuery(answer: GraphQueryAnswer): Row | null {\n const fromStructured = queryBlock(answer.structuredContent)\n if (fromStructured) return fromStructured\n for (const block of answer.content ?? []) {\n if (block.type !== 'text' || typeof block.text !== 'string') continue\n try {\n const parsed = queryBlock(JSON.parse(block.text))\n if (parsed) return parsed\n } catch {\n /* not JSON: try the next block */\n }\n }\n return null\n}\n\n// A failure after which every later read would fail the same way: the endpoint\n// limits requests, or it asks for payment. The build stops sending reads.\ntype Halt = 'rate_limit' | 'payment'\n\nfunction haltOfError(err: unknown): Halt | undefined {\n if (err instanceof PaymentRequiredError) return 'payment'\n const code = isRecord(err) ? err.code : undefined\n const message = err instanceof Error ? err.message : String(err)\n if (code === 429 || /\\b429\\b|too many requests|rate.?limit/i.test(message)) return 'rate_limit'\n if (/\\b402\\b|payment required/i.test(message)) return 'payment'\n return undefined\n}\n\nfunction haltOfAnswer(answer: GraphQueryAnswer): Halt | undefined {\n const detail = isRecord(answer.structuredContent)\n ? answer.structuredContent.error_detail\n : undefined\n return isRecord(detail) && detail.class === 'capacity' ? 'rate_limit' : undefined\n}\n\nexport interface BuildOptions {\n client: GraphSchemaClient\n /** A normalized network identifier. */\n network: string\n now?: () => Date\n /** A wait between two reads, in milliseconds. One build needs none: it stays under the rate limit. */\n pauseMs?: number\n sleep?: (ms: number) => Promise<void>\n}\n\nexport interface BuildResult {\n document: GraphSchemaDocument\n /** False when a read failed: the document has a section missing. */\n complete: boolean\n}\n\nfunction describeIndex(row: Row): GraphSchemaIndex | null {\n const name = typeof row.name === 'string' ? row.name : ''\n const entity =\n row.entityType === 'NODE' ? 'node' : row.entityType === 'RELATIONSHIP' ? 'link' : null\n const properties = stringList(row.properties)\n // A lookup index names no label and no property: it tells an agent nothing.\n if (!name || !entity || properties.length === 0) return null\n return {\n name,\n entity,\n types: stringList(row.labelsOrTypes),\n properties,\n state: typeof row.state === 'string' && row.state ? row.state : 'unknown',\n }\n}\n\nexport async function buildGraphSchema(options: BuildOptions): Promise<BuildResult> {\n const { client } = options\n const now = options.now ?? (() => new Date())\n const pauseMs = options.pauseMs ?? 0\n const sleep = options.sleep ?? ((ms: number) => new Promise<void>((done) => setTimeout(done, ms)))\n\n const problems: string[] = []\n const remarks: string[] = []\n let billed = 0\n let calls = 0\n let halted = false\n\n async function pace(): Promise<void> {\n if (calls > 0 && pauseMs > 0) await sleep(pauseMs)\n calls += 1\n }\n\n function fail(label: string, reason: string, halt?: Halt): null {\n problems.push(`${label} could not be read: ${reason}`)\n if (halt && !halted) {\n halted = true\n if (halt === 'payment') {\n problems.push(\n 'The endpoint asks for payment, so the reads after it were not sent. Fix the payment setup, then call again with refresh=true.'\n )\n } else {\n // The endpoint says how long to wait: \"retry after 23 seconds\".\n const wait = /retry after (\\d+) seconds?/i.exec(reason)?.[1]\n problems.push(\n `The endpoint is limiting requests, so the reads after it were not sent. Call again after ${wait ? `${wait} seconds` : 'a minute'} with refresh=true.`\n )\n }\n }\n return null\n }\n\n async function graphRead(network: string, label: string, query: string): Promise<Row[] | null> {\n if (halted) return null\n await pace()\n let answer: GraphQueryAnswer\n try {\n answer = (await client.callTool({\n name: 'graph_query',\n arguments: { network, query },\n })) as GraphQueryAnswer\n } catch (err) {\n return fail(label, err instanceof Error ? err.message : String(err), haltOfError(err))\n }\n const block = answerQuery(answer ?? {})\n if (block && typeof block.billable_units === 'number') billed += block.billable_units\n if (answer?.isError === true) {\n return fail(label, refusalText(answer), haltOfAnswer(answer))\n }\n if (!block || !Array.isArray(block.results)) {\n return fail(label, 'the reply holds no rows')\n }\n return block.results.filter(isRecord)\n }\n\n // ── The network: capabilities first, so an unserved name costs no graph read.\n let network = options.network\n let capability: NetworkCapability | undefined\n await pace()\n try {\n const answer = (await client.callTool({\n name: 'network_capabilities',\n arguments: {},\n })) as GraphQueryAnswer\n if (answer?.isError === true) {\n fail('network capabilities', refusalText(answer), haltOfAnswer(answer))\n } else {\n const facts = isRecord(answer?.structuredContent) ? answer.structuredContent.facts : undefined\n const capabilities = isRecord(facts) ? facts.capabilities : undefined\n const networks =\n isRecord(capabilities) && Array.isArray(capabilities.networks)\n ? capabilities.networks\n : null\n if (!networks) {\n fail('network capabilities', 'the reply lists no networks')\n } else {\n const document = mirrorGraphNetworkCapabilities({ networks })\n capability = findNetworkCapability(document, options.network)\n if (!capability) {\n const served = document.networks.map((entry) => entry.network).join(', ')\n throw new GraphSchemaError(\n `network_not_served: \"${options.network}\" is not a network this endpoint serves. Served networks: ${served || 'none'}.`\n )\n }\n network = capability.network\n }\n }\n } catch (err) {\n if (err instanceof GraphSchemaError) throw err\n fail('network capabilities', err instanceof Error ? err.message : String(err), haltOfError(err))\n }\n\n // ── Topology: the catalog, then a sample of the main kinds.\n const topology: GraphSchemaDocument['layers']['topology'] = {\n labels: [],\n link_types: [],\n property_keys: [],\n indexes: [],\n samples: {},\n }\n const topologyOff = capability?.layers?.topology?.enabled === false\n if (topologyOff) {\n remarks.push('The topology layer is off on this network.')\n } else {\n const labels = await graphRead(network, CATALOG_READS.labels.label, CATALOG_READS.labels.query)\n if (labels) topology.labels = sortedUnique(labels.flatMap((row) => stringList([row.label])))\n\n const linkTypes = await graphRead(\n network,\n CATALOG_READS.linkTypes.label,\n CATALOG_READS.linkTypes.query\n )\n if (linkTypes) {\n topology.link_types = sortedUnique(\n linkTypes.flatMap((row) => stringList([row.relationshipType]))\n )\n }\n\n const keys = await graphRead(\n network,\n CATALOG_READS.propertyKeys.label,\n CATALOG_READS.propertyKeys.query\n )\n if (keys) {\n topology.property_keys = sortedUnique(keys.flatMap((row) => stringList([row.propertyKey])))\n }\n\n const indexes = await graphRead(\n network,\n CATALOG_READS.indexes.label,\n CATALOG_READS.indexes.query\n )\n if (indexes) {\n topology.indexes = indexes\n .map(describeIndex)\n .filter((index): index is GraphSchemaIndex => index !== null)\n .sort((a, b) => a.name.localeCompare(b.name))\n }\n\n // An address is sampled unless the label list was read and has no Address.\n const labelsRead = labels !== null\n if (!labelsRead || topology.labels.includes('Address')) {\n const rows = await graphRead(network, 'the Address sample', addressSampleQuery())\n if (rows) topology.samples['Address'] = unionOfKeys(rows)\n }\n\n const sampled = SAMPLED_LINK_TYPES.filter((type) => topology.link_types.includes(type))\n if (linkTypes === null && !halted) {\n problems.push('The link samples were skipped: the link types are unknown.')\n }\n for (const type of sampled) {\n const rows = await graphRead(network, `the ${type} sample`, linkSampleQuery(type))\n if (rows) topology.samples[type] = unionOfKeys(rows)\n }\n\n const unsampled = topology.link_types.filter(\n (type) => !(SAMPLED_LINK_TYPES as readonly string[]).includes(type)\n )\n if (unsampled.length > 0) {\n remarks.push(\n `Link types with no sample: ${unsampled.join(', ')}. Read the keys of one with USE topology MATCH ()-[r:<TYPE>]->() RETURN keys(r) AS keys LIMIT ${LINK_SAMPLE_LIMIT}.`\n )\n }\n }\n\n // ── Facts and chain: what the network publishes.\n const facts: GraphSchemaDocument['layers']['facts'] = { relationships: [], transfer_columns: [] }\n const chain: GraphSchemaDocument['layers']['chain'] = { lookups: [] }\n if (capability) {\n if (capability.layers?.facts?.enabled === false) {\n remarks.push('The facts layer is off on this network.')\n } else {\n facts.relationships = stringList(capability.layers?.facts?.relationships)\n if (facts.relationships.includes('TRANSFER')) {\n facts.transfer_columns = [...FACTS_TRANSFER_COLUMNS]\n }\n }\n const admission = capability.chain_admission\n if (admission?.enabled === false) {\n remarks.push(`The chain layer is off (status ${admission.status ?? 'unknown'}).`)\n } else {\n chain.lookups = stringList(admission?.lookups)\n }\n }\n\n const words = [...topology.property_keys, ...Object.values(topology.samples).flat()]\n if (words.includes('synced_through_height') || words.includes('pair_key')) {\n remarks.push(\n 'synced_through_height and pair_key are sync bookkeeping: never filter or sort on them.'\n )\n }\n remarks.push('Fields come from a sample of the live graph. A rare field may be missing.')\n\n return {\n complete: problems.length === 0,\n document: {\n schema: GRAPH_SCHEMA_ID,\n network,\n built_at: now().toISOString(),\n source: GRAPH_SCHEMA_SOURCE,\n cached: false,\n billed_units: billed,\n layers: { topology, facts, chain },\n notes: [...problems, ...remarks],\n },\n }\n}\n\nfunction unionOfKeys(rows: Row[]): string[] {\n return sortedUnique(rows.flatMap((row) => stringList(row.keys)))\n}\n\n// ─── Reading from the cache, or building ──────────────────────────────────────\n\nexport interface GetGraphSchemaOptions {\n /** As the caller wrote it: normalized here. */\n network: unknown\n refresh?: boolean\n endpoint: string\n /**\n * Runs `fn` with one connected client. It is called once for a build and not at\n * all when the cache answers, so a cache hit opens no session.\n */\n withClient: <T>(fn: (client: GraphSchemaClient) => Promise<T>) => Promise<T>\n now?: () => Date\n pauseMs?: number\n sleep?: (ms: number) => Promise<void>\n}\n\n// Builds in flight, by endpoint and network: two callers that ask for one\n// schema at once share one build and pay for it once.\nconst building = new Map<string, Promise<GraphSchemaDocument>>()\n\nexport async function getGraphSchema(options: GetGraphSchemaOptions): Promise<GraphSchemaDocument> {\n const network = normalizeSchemaNetwork(options.network)\n const now = options.now ?? (() => new Date())\n if (options.refresh !== true) {\n const cached = await loadGraphSchemaCache(network, options.endpoint, now())\n if (cached) return cached\n }\n const key = `${options.endpoint}\\n${network}`\n const running = building.get(key)\n if (running) return running\n const build = (async () => {\n const { document, complete } = await options.withClient((client) =>\n buildGraphSchema({\n client,\n network,\n now,\n ...(options.pauseMs === undefined ? {} : { pauseMs: options.pauseMs }),\n ...(options.sleep ? { sleep: options.sleep } : {}),\n })\n )\n try {\n await saveGraphSchemaCache(network, document, options.endpoint, complete, now())\n } catch (err) {\n document.notes.push(\n `The schema could not be saved to the cache: ${err instanceof Error ? err.message : String(err)}`\n )\n }\n return document\n })()\n building.set(key, build)\n try {\n return await build\n } finally {\n building.delete(key)\n }\n}\n\n// ─── Text ─────────────────────────────────────────────────────────────────────\n\nfunction listLine(title: string, values: string[], empty = 'none read'): string {\n return `${title}: ${values.length > 0 ? values.join(', ') : empty}`\n}\n\n/** The schema as the model and the terminal read it. */\nexport function formatGraphSchemaText(document: GraphSchemaDocument): string {\n const { topology, facts, chain } = document.layers\n const origin = document.cached\n ? 'from the cache, kept 24 hours; refresh=true rebuilds it'\n : `read now for ${document.billed_units} billed units and cached for 24 hours`\n const lines = [\n `Graph schema, network ${document.network}`,\n `Source: ${document.source}, built ${document.built_at} (${origin})`,\n '',\n 'USE topology',\n listLine('Labels', topology.labels),\n listLine('Link types', topology.link_types),\n listLine(`Property keys (${topology.property_keys.length})`, topology.property_keys),\n ]\n lines.push(topology.indexes.length > 0 ? 'Indexes:' : 'Indexes: none read')\n for (const index of topology.indexes) {\n lines.push(\n `- ${index.entity} ${index.types.join('|')}(${index.properties.join(', ')}) ${index.state}`\n )\n }\n const sampled = Object.entries(topology.samples)\n lines.push(sampled.length > 0 ? 'Fields, from a sample:' : 'Fields, from a sample: none read')\n for (const [kind, fields] of sampled) lines.push(`- ${kind}: ${fields.join(', ')}`)\n lines.push(\n '',\n 'USE facts',\n listLine('Relationships', facts.relationships),\n listLine('TRANSFER columns', facts.transfer_columns),\n '',\n 'USE chain',\n listLine('Lookups', chain.lookups)\n )\n if (document.notes.length > 0) {\n lines.push('', 'Notes:', ...document.notes.map((note) => `- ${note}`))\n }\n return lines.join('\\n')\n}\n\n// ─── The MCP tool ─────────────────────────────────────────────────────────────\n\nexport interface GraphSchemaDependencies {\n endpoint: string\n withClient: GetGraphSchemaOptions['withClient']\n /** The text of a failure that is not a GraphSchemaError: payment required, transport. */\n describeFailure: (err: unknown) => string\n now?: () => Date\n pauseMs?: number\n sleep?: (ms: number) => Promise<void>\n}\n\nexport type MetaSchemaResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n isError: boolean\n}\n\nfunction errorResult(text: string): MetaSchemaResult {\n return { content: [{ type: 'text', text }], isError: true }\n}\n\n/** meta_schema, {network, refresh?}. Every argument is checked before the first read. */\nexport async function handleMetaSchema(\n args: unknown,\n deps: GraphSchemaDependencies\n): Promise<MetaSchemaResult> {\n const record = isRecord(args) ? args : {}\n const refresh = record.refresh\n if (refresh !== undefined && refresh !== null && typeof refresh !== 'boolean') {\n return errorResult('invalid_refresh: refresh must be true or false')\n }\n try {\n const document = await getGraphSchema({\n network: record.network,\n refresh: refresh === true,\n endpoint: deps.endpoint,\n withClient: deps.withClient,\n ...(deps.now ? { now: deps.now } : {}),\n ...(deps.pauseMs === undefined ? {} : { pauseMs: deps.pauseMs }),\n ...(deps.sleep ? { sleep: deps.sleep } : {}),\n })\n return {\n content: [{ type: 'text', text: formatGraphSchemaText(document) }],\n structuredContent: document as unknown as Record<string, unknown>,\n isError: false,\n }\n } catch (err) {\n return errorResult(err instanceof GraphSchemaError ? err.message : deps.describeFailure(err))\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,eAAe;AAC5B,MAAa,oBAAoB;AACjC,MAAa,gBAAgB;;AAG7B,MAAa,iBAAiB;;AAE9B,MAAa,kBAAkB;;;;;AAK/B,MAAa,kBAAkB;;;;;AAK/B,MAAa,kBAAkB;;AAI/B,MAAa,mBAAmB;AAEhC,MAAa,mBAAmB;;AAEhC,MAAa,gBAAgB;;;;;;AAM7B,MAAa,sBAAsB;;AAEnC,MAAa,yBAAyB;;AAEtC,MAAa,qBAAqB;;AAElC,MAAa,sBAAsB;AAEnC,MAAa,iBAAiB;AA8E9B,MAAa,uBACX;AACF,MAAa,wBAAwB,iEAAiE;AACtG,MAAa,uBACX;AAEF,MAAa,mBACX;AACF,MAAa,kBACX;AACF,MAAa,qBAAqB;AAClC,MAAa,oBAAoB;AACjC,MAAa,yBACX;AACF,MAAa,oBACX;AAEF,MAAM,kBAAkB;AACxB,MAAM,cAAc;AACpB,MAAM,cAAc;;;;;;AAOpB,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KAAK,SAAS,KAAK,MAAM,CAAC;CAEvE,OAAO,MAAM,KAAK,IAAI;AACxB;AAoBA,SAAS,YAAY,MAAgC;CACnD,OAAO;EAAE,SAAS,CAAC;GAAE,MAAM;GAAQ;EAAK,CAAC;EAAG,SAAS;CAAK;AAC5D;;AAGA,eAAsB,iBACpB,MACA,MAC2B;CAC3B,MAAM,SAAS,SAAS,IAAI,IAAI,OAAO,CAAC;CACxC,MAAM,UAAU,OAAO;CACvB,IAAI,YAAY,KAAA,KAAa,YAAY,QAAQ,OAAO,YAAY,WAClE,OAAO,YAAY,gDAAgD;CAErE,IAAI;EACF,MAAM,WAAW,MAAM,eAAe;GACpC,SAAS,OAAO;GAChB,SAAS,YAAY;GACrB,UAAU,KAAK;GACf,YAAY,KAAK;GACjB,GAAI,KAAK,MAAM,EAAE,KAAK,KAAK,IAAI,IAAI,CAAC;GACpC,GAAI,KAAK,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,KAAK,QAAQ;GAC9D,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;EAC5C,CAAC;EACD,OAAO;GACL,SAAS,CAAC;IAAE,MAAM;IAAQ,MAAM,sBAAsB,QAAQ;GAAE,CAAC;GACjE,mBAAmB;GACnB,SAAS;EACX;CACF,SAAS,KAAK;EACZ,OAAO,YAAY,eAAe,mBAAmB,IAAI,UAAU,KAAK,gBAAgB,GAAG,CAAC;CAC9F;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"print-result-C3YazZBw.mjs","names":["isRecord"],"sources":["../src/version.ts","../src/mcp/balance-text.ts","../src/mcp/label-case.ts","../src/mcp/timestamp-text.ts","../src/mcp/print-result.ts"],"sourcesContent":["import { readFileSync } from 'node:fs'\n\nexport const PACKAGE_INFO = JSON.parse(\n readFileSync(new URL('../package.json', import.meta.url), 'utf8')\n) as { name: string; version: string }\n\nexport const PACKAGE_VERSION = PACKAGE_INFO.version\n","/**\n * An ETH text twin beside every native balance column of a chain answer.\n *\n * `USE chain` serves `balance` as wei in decimal text, exact and 16 to 22\n * digits long. A host without a shell (Claude Desktop, 2026-10-21) printed\n * `10003752747799400` to the user as the balance. A model that divides by\n * 10^18 by head misplaces the point, so the proxy writes `<column>_eth`\n * next to each one, the same way `<column>_utc` sits beside a timestamp.\n */\n\nconst BALANCE_KEY = /(^|_)balance$/\nconst WEI_TEXT = /^[0-9]{1,78}$/\nconst WEI_PER_ETH = 10n ** 18n\n\n/** `0.0100037527477994` for `10003752747799400` wei: exact, no exponent, no trailing zeros. */\nexport function ethText(wei: string): string {\n const value = BigInt(wei)\n const whole = value / WEI_PER_ETH\n const frac = (value % WEI_PER_ETH).toString().padStart(18, '0').replace(/0+$/, '')\n return frac === '' ? whole.toString() : `${whole}.${frac}`\n}\n\nfunction isWeiText(value: unknown): value is string {\n return typeof value === 'string' && WEI_TEXT.test(value)\n}\n\n/**\n * One row with a `<key>_eth` string after every wei balance column that has\n * no twin yet. A column the model itself named `*_eth` (an alias such as\n * `a.balance_eth AS held_eth`, see stripEthProperties) arrives as wei and is\n * rendered as ETH text in place: the model gets the column it asked for.\n */\nexport function addBalanceText(row: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(row)) {\n out[key] = key.endsWith('_eth') && isWeiText(value) ? ethText(value) : value\n if (BALANCE_KEY.test(key) && isWeiText(value) && !(`${key}_eth` in row)) out[`${key}_eth`] = ethText(value)\n }\n return out\n}\n\n/**\n * The `_eth` twin is added by the proxy; it is no chain property. A query\n * that names `a.balance_eth` is rewritten to `a.balance`, so the row comes\n * back and the twin is written beside it. An alias after AS stays as written.\n */\nexport function stripEthProperties(query: string): string {\n return query.replace(/\\.((?:[A-Za-z_][A-Za-z0-9_]*_)?balance)_eth\\b/g, '.$1')\n}\n","/**\n * A node label or link type written in the wrong case is spelled the graph's way.\n *\n * Labels and link types are case sensitive. `(a:address {address: \"0x…\"})`\n * matches nothing and the read answers zero rows with no error, so the model\n * tells the user the address has no activity. Claude Desktop did exactly that\n * for the basket router on 2026-10-21 (skill loop, basket round 8): its links\n * were there under `:Address`.\n *\n * Only a name that is a known label or link type, in another case, after the\n * `:` (or `|`) of a node or link pattern is rewritten. Text inside quotes and a\n * map value such as `{address: address}` stay as written.\n */\n\nconst NAMES = [\n // topology node labels\n 'Account', 'Address', 'Bridge', 'Bundler', 'Chain', 'Contract', 'EntryPoint', 'Exchange', 'IssuerFrozen', 'Launchpad',\n 'Mixer', 'NFT', 'OnMoneyTrail', 'Paymaster', 'Poisoned', 'Pool', 'Protocol', 'Sanctioned', 'Scam', 'SmartAccount',\n 'Targeted', 'Token', 'Victim',\n // chain lookups\n 'Transaction', 'Block', 'Head',\n // topology link types\n 'ADDED_LIQUIDITY', 'APPROVED', 'BRIDGED', 'BUNDLED', 'DEPLOYED_CONTRACT', 'FLOWS_TO', 'LINKED', 'OPERATED_BY',\n 'REMOVED_LIQUIDITY', 'SIGNED_AUTHORIZATION', 'SIGNED_FOR', 'SPONSORED', 'SWAPPED', 'TRANSFERRED',\n // facts link types\n 'TRANSFER', 'BRIDGE_CROSSING', 'SWAP', 'LIQUIDITY_ADD', 'LIQUIDITY_REMOVE',\n]\n\nconst CANONICAL = new Map(NAMES.map((name) => [name.toLowerCase(), name]))\nconst IDENT = /[A-Za-z0-9_]/\n\nfunction prevNonSpace(text: string, from: number): number {\n let i = from\n while (i >= 0 && /\\s/.test(text[i])) i--\n return i\n}\n\n/** True when the `:` or `|` at `at` opens a label or link type, not a map value. */\nfunction opensLabel(text: string, at: number): boolean {\n let i = prevNonSpace(text, at - 1)\n if (i < 0) return false\n // `[:TRANSFER|swap]`: a `|` counts only after a link type of its own.\n if (text[at] !== '|' && (text[i] === '(' || text[i] === '[')) return true\n if (!IDENT.test(text[i])) return false\n while (i >= 0 && IDENT.test(text[i])) i--\n const before = prevNonSpace(text, i)\n // `(a:Address:contract)`: the name before this `:` is itself a label.\n if (before >= 0 && (text[before] === ':' || text[before] === '|')) return opensLabel(text, before)\n return text[at] === ':' && before >= 0 && (text[before] === '(' || text[before] === '[')\n}\n\nfunction fixSegment(segment: string): string {\n return segment.replace(/([:|])(\\s*)([A-Za-z_][A-Za-z0-9_]*)/g, (whole, mark: string, space: string, name: string, at: number) => {\n const canonical = CANONICAL.get(name.toLowerCase())\n if (!canonical || canonical === name || !opensLabel(segment, at)) return whole\n return `${mark}${space}${canonical}`\n })\n}\n\n/** The query with every known label and link type in the graph's case; quoted text is untouched. */\nexport function fixLabelCase(query: string): string {\n return query\n .split(/(\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*'|`[^`]*`)/)\n .map((part, index) => (index % 2 === 1 ? part : fixSegment(part)))\n .join('')\n}\n","/**\n * A UTC text twin beside every timestamp column of a graph answer.\n *\n * The graph serves integer milliseconds. A model that converts them by head\n * gets the time of day wrong about one time in three (loop 3, 2026-10-10:\n * four of twelve answers about one block named 00:15, 09:35, 06:35 or 09:15\n * for 23:55:43 UTC). Hosts without a shell (Claude Desktop) have no other\n * way to convert, so the proxy writes `<column>_utc` next to each one.\n */\n\nimport { addBalanceText, stripEthProperties } from './balance-text.js'\nimport { fixLabelCase } from './label-case.js'\n\nconst TIMESTAMP_KEY = /(_timestamp|_time|_at|_seen|_active)$/\nconst MIN_MS = 1_000_000_000_000 // 2001-09-09\nconst MAX_MS = 4_000_000_000_000 // 2096-10-02\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** `2026-08-05 23:55:43 UTC` for epoch milliseconds. */\nexport function utcText(ms: number): string {\n return `${new Date(ms).toISOString().slice(0, 19).replace('T', ' ')} UTC`\n}\n\nfunction isEpochMs(value: unknown): value is number {\n return typeof value === 'number' && Number.isInteger(value) && value >= MIN_MS && value <= MAX_MS\n}\n\n/**\n * One row with a `<key>_utc` string after every epoch-millisecond timestamp\n * column. A column the model itself named `*_utc` (its query asked for the\n * twin as a property, see stripUtcProperties) arrives as milliseconds and is\n * rendered as UTC text in place: the model gets the column it asked for.\n */\nexport function addTimestampText(row: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(row)) {\n out[key] = key.endsWith('_utc') && isEpochMs(value) ? utcText(value) : value\n if (TIMESTAMP_KEY.test(key) && isEpochMs(value) && !(`${key}_utc` in row)) out[`${key}_utc`] = utcText(value)\n }\n return out\n}\n\n/**\n * The `_utc` twin is added to a reply by the proxy; it is no graph property.\n * Thirteen of 48 loop-5 rounds wrote `f.first_seen_timestamp_utc` into a\n * query anyway: topology answers null, a SWAP read is refused. The property\n * reference is rewritten to its millisecond column, `x.<column>_utc` to\n * `x.<column>`; an alias after AS is not a property and stays as written, so\n * `f.first_seen_timestamp_utc AS first_seen_utc` yields a `first_seen_utc`\n * column that addTimestampText renders as text. A label or link type in the\n * wrong case is spelled the graph's way (label-case.ts).\n */\nexport function stripUtcProperties(query: string): string {\n return fixLabelCase(stripEthProperties(query.replace(/\\.([A-Za-z_][A-Za-z0-9_]*?)_utc\\b/g, '.$1')))\n}\n\n/** graph_query and graph_query_batch arguments with stripUtcProperties applied to every query. */\nexport function withoutUtcProperties(toolName: string, args: Record<string, unknown>): Record<string, unknown> {\n if (toolName === 'graph_query' && typeof args.query === 'string') return { ...args, query: stripUtcProperties(args.query) }\n if (toolName === 'graph_query_batch' && Array.isArray(args.queries)) {\n return {\n ...args,\n queries: args.queries.map((entry) =>\n isRecord(entry) && typeof entry.query === 'string' ? { ...entry, query: stripUtcProperties(entry.query) } : entry\n ),\n }\n }\n return args\n}\n\nfunction mapResults(holder: unknown): unknown {\n if (!isRecord(holder) || !Array.isArray(holder.results)) return holder\n return {\n ...holder,\n results: holder.results.map((row) => (isRecord(row) ? addBalanceText(addTimestampText(row)) : row)),\n }\n}\n\n/**\n * The structured content of graph_query (facts.query.results) or\n * graph_query_batch (facts.queries[].results) with the UTC twins and the\n * ETH twins (balance-text.ts) added.\n * Anything else comes back as it was.\n */\nexport function withTimestampText(structuredContent: unknown): unknown {\n if (!isRecord(structuredContent) || !isRecord(structuredContent.facts)) return structuredContent\n const facts = structuredContent.facts\n if (!isRecord(facts.query) && !Array.isArray(facts.queries)) return structuredContent\n const next: Record<string, unknown> = { ...facts }\n if (isRecord(facts.query)) next.query = mapResults(facts.query)\n if (Array.isArray(facts.queries)) next.queries = facts.queries.map(mapResults)\n return { ...structuredContent, facts: next }\n}\n\ntype TextBlock = { type: string; text?: string }\n\n/**\n * A tool result whose structured content and single JSON text block both carry\n * the UTC twins. A text block that is not the JSON of the structured content\n * is left alone.\n */\nexport function withTimestampTextResult<T extends { content?: TextBlock[]; structuredContent?: unknown }>(result: T): T {\n const structured = withTimestampText(result.structuredContent)\n if (structured === result.structuredContent) return result\n const content = result.content ?? []\n const only = content.length === 1 && content[0]?.type === 'text' ? content[0] : null\n let parsed: unknown = undefined\n try {\n parsed = only?.text ? JSON.parse(only.text) : undefined\n } catch {\n parsed = undefined\n }\n const textIsStructured =\n parsed !== undefined && JSON.stringify(parsed) === JSON.stringify(result.structuredContent)\n return {\n ...result,\n structuredContent: structured,\n content: textIsStructured ? [{ ...only, text: JSON.stringify(structured) }] : content,\n }\n}\n","import { withTimestampTextResult } from './timestamp-text.js'\n\nexport interface McpTextResult {\n content?: Array<{ type: string; text?: string }>\n structuredContent?: unknown\n isError?: boolean\n}\n\n/**\n * The refusal envelope of the graph server, as the reply carries it in\n * `structuredContent.error_detail`. `class` is one of `refused`, `killed`,\n * `capacity` or `failed`, and it decides the caller's next move.\n */\nexport interface McpErrorDetail {\n code?: string\n rule?: string\n class?: string\n fix?: string\n example?: string\n}\n\nconst ERROR_DETAIL_FIELDS = ['code', 'rule', 'class', 'fix', 'example'] as const\n\n/**\n * A tool reply flagged `isError`: the server answered, and its answer is an\n * error. It is never a failure of the connection, so no caller may report it\n * as an unreachable endpoint. `message` is the server's own text and\n * `errorDetail` is the envelope of the reply, absent when the reply has none.\n */\nexport class McpToolError extends Error {\n readonly errorDetail?: McpErrorDetail\n\n constructor(message: string, errorDetail?: McpErrorDetail) {\n super(message)\n this.name = 'McpToolError'\n if (errorDetail) this.errorDetail = errorDetail\n }\n}\n\nexport interface McpPrintOptions {\n tool?: string\n json?: boolean\n}\n\n// What a switched-off or lagging chain layer means for the caller, in the line\n// under the server's text. The endpoint answered, so the endpoint is up, and\n// the other two layers do not depend on the chain node.\nconst CHAIN_UNAVAILABLE_MEANING =\n 'the chain layer is off or behind. The endpoint is up. USE topology and USE facts still work.'\n\n/**\n * How `cia mcp call` shows an McpToolError: the server's own text, then one\n * line built from its error_detail, `code <code> · class <class> · <fix>`. A\n * reply with no error_detail is the server text alone. For `chain_unavailable`\n * the line also says what the code means for the caller.\n */\nexport function formatMcpToolError(err: McpToolError): string {\n const detail = err.errorDetail\n if (!detail) return err.message\n const parts: string[] = []\n if (detail.code) parts.push(`code ${detail.code}`)\n if (detail.class) parts.push(`class ${detail.class}`)\n if (detail.fix) parts.push(detail.fix)\n if (detail.code === 'chain_unavailable') parts.push(CHAIN_UNAVAILABLE_MEANING)\n if (parts.length === 0) return err.message\n return `${err.message}\\n ${parts.join(' · ')}`\n}\n\ntype JsonRecord = Record<string, unknown>\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\n/** The text fields of `structuredContent.error_detail`, or undefined when it has none. */\nfunction errorDetailOf(structuredContent: unknown): McpErrorDetail | undefined {\n if (!isRecord(structuredContent) || !isRecord(structuredContent.error_detail)) return undefined\n const detail: McpErrorDetail = {}\n for (const field of ERROR_DETAIL_FIELDS) {\n const value = structuredContent.error_detail[field]\n if (typeof value === 'string') detail[field] = value\n }\n return Object.keys(detail).length > 0 ? detail : undefined\n}\n\nfunction displayValue(value: unknown): string {\n if (value === null || value === undefined) return ''\n if (typeof value === 'string') return value\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n try {\n return JSON.stringify(value)\n } catch {\n return String(value)\n }\n}\n\nfunction formatTable(rows: Array<JsonRecord>): string[] {\n if (rows.length === 0) return []\n const columns = [...new Set(rows.flatMap((row) => Object.keys(row)))]\n const values = rows.map((row) => columns.map((column) => displayValue(row[column])))\n const widths = columns.map((column, index) =>\n Math.max(column.length, ...values.map((row) => row[index]?.length ?? 0))\n )\n const line = (row: string[]): string =>\n row\n .map((value, index) => (index === row.length - 1 ? value : value.padEnd(widths[index] ?? 0)))\n .join(' | ')\n return [line(columns), widths.map((width) => '-'.repeat(width)).join('-+-'), ...values.map(line)]\n}\n\nfunction formatGraphResult(value: JsonRecord, fallbackTool?: string): string | null {\n const facts = isRecord(value.facts) ? value.facts : undefined\n const query = facts && isRecord(facts.query) ? facts.query : undefined\n const queries = facts && Array.isArray(facts.queries) ? facts.queries : undefined\n if (!query && !queries) return null\n\n const lines = [`Tool: ${displayValue(value.tool) || fallbackTool || 'MCP result'}`]\n const subject = isRecord(value.subject)\n ? value.subject\n : facts && isRecord(facts.subject)\n ? facts.subject\n : undefined\n if (subject?.network !== undefined) lines.push(`Network: ${displayValue(subject.network)}`)\n\n if (query) {\n const results = Array.isArray(query.results) ? query.results.filter(isRecord) : []\n if (query.count !== undefined) lines.push(`Rows: ${displayValue(query.count)}`)\n else lines.push(`Rows: ${results.length}`)\n if (query.billable_units !== undefined) {\n lines.push(`Billed units: ${displayValue(query.billable_units)}`)\n }\n if (query.elapsed_ms !== undefined) lines.push(`Elapsed: ${displayValue(query.elapsed_ms)} ms`)\n if (query.truncated !== undefined) lines.push(`Truncated: ${displayValue(query.truncated)}`)\n if (query.error !== undefined) lines.push(`Error: ${displayValue(query.error)}`)\n if (results.length > 0) lines.push('', 'Results:', ...formatTable(results))\n else lines.push('', 'Results: none')\n }\n\n if (queries) {\n lines.push(`Queries: ${queries.length}`)\n for (const entry of queries) {\n if (!isRecord(entry)) continue\n const id = displayValue(entry.id) || 'query'\n const results = Array.isArray(entry.results) ? entry.results.filter(isRecord) : []\n lines.push('', `[${id}]`)\n if (entry.error !== undefined) lines.push(`Error: ${displayValue(entry.error)}`)\n lines.push(`Rows: ${displayValue(entry.count ?? results.length)}`)\n if (results.length > 0) lines.push(...formatTable(results))\n else lines.push('Results: none')\n }\n }\n\n return lines.join('\\n')\n}\n\n/**\n * Formats one MCP text block for terminal output. JSON is indented when the\n * caller requests `--json`; graph query envelopes are rendered as a compact\n * result summary and table by default.\n */\nexport function formatMcpTextContent(\n text: string,\n tool?: string,\n options: Pick<McpPrintOptions, 'json'> = {}\n): string {\n let parsed: unknown\n try {\n parsed = JSON.parse(text) as unknown\n } catch {\n return text\n }\n\n if (options.json) {\n try {\n return JSON.stringify(parsed, null, 2)\n } catch {\n return text\n }\n }\n\n if (isRecord(parsed)) {\n return formatGraphResult(parsed, tool) ?? JSON.stringify(parsed, null, 2)\n }\n return displayValue(parsed)\n}\n\n/**\n * Prints the text blocks of an MCP tool result to stdout. When the result is\n * flagged `isError`, throws an McpToolError with the tool's error text instead\n * — MCP `callTool` returns tool errors as ordinary results (it does not\n * reject), so callers must surface them as failures (non-zero exit) rather than\n * printing to stdout and exiting 0. The error keeps the `error_detail` of the\n * reply, so a caller can tell a refused query from a dead endpoint.\n */\n/** The tools whose rows carry the `_utc` and `_eth` twins, the same two the proxy adds (src/mcp/proxy.ts). */\nfunction isGraphReadTool(tool?: string): boolean {\n return tool === 'graph_query' || tool === 'graph_query_batch'\n}\n\n/**\n * A graph reply with the twins the proxy writes for a host: `<column>_utc`\n * beside every timestamp and `<column>_eth` beside every wei balance. The\n * shell path printed the server row as it arrived (chain-insights #509), so a\n * person reading `cia mcp call` got the raw milliseconds and the raw wei.\n * The text block the server sends is the JSON of its structured content, so\n * both are rewritten together; a result with no structured content is read\n * from its text block first.\n */\nexport function withGraphTwins(result: McpTextResult, tool?: string): McpTextResult {\n if (!isGraphReadTool(tool) || result.isError) return result\n const only = (result.content ?? []).length === 1 && result.content?.[0]?.type === 'text' ? result.content[0] : null\n let structured = result.structuredContent\n if (structured === undefined && only?.text) {\n try {\n structured = JSON.parse(only.text) as unknown\n } catch {\n return result\n }\n }\n const twinned = withTimestampTextResult({ ...result, structuredContent: structured })\n return twinned.structuredContent === structured && result.structuredContent !== undefined ? result : twinned\n}\n\nexport function printMcpTextContent(result: McpTextResult, options: McpPrintOptions = {}): void {\n result = withGraphTwins(result, options.tool)\n const texts = (result.content ?? [])\n .filter((item) => item.type === 'text')\n .map((item) => item.text ?? '')\n\n if (result.isError) {\n throw new McpToolError(\n texts.join('\\n').trim() || 'MCP tool returned an error',\n errorDetailOf(result.structuredContent)\n )\n }\n\n for (const text of texts) console.log(formatMcpTextContent(text, options.tool, options))\n}\n"],"mappings":";;;AAEA,MAAa,eAAe,KAAK,MAC/B,aAAa,IAAI,IAAI,mBAAmB,YAAY,GAAG,GAAG,MAAM,CAClE;AAEA,MAAa,kBAAkB,aAAa;;;;;;;;;;;;ACI5C,MAAM,cAAc;AACpB,MAAM,WAAW;AACjB,MAAM,cAAc,OAAO;;AAG3B,SAAgB,QAAQ,KAAqB;CAC3C,MAAM,QAAQ,OAAO,GAAG;CACxB,MAAM,QAAQ,QAAQ;CACtB,MAAM,QAAQ,QAAQ,YAAA,CAAa,SAAS,CAAC,CAAC,SAAS,IAAI,GAAG,CAAC,CAAC,QAAQ,OAAO,EAAE;CACjF,OAAO,SAAS,KAAK,MAAM,SAAS,IAAI,GAAG,MAAM,GAAG;AACtD;AAEA,SAAS,UAAU,OAAiC;CAClD,OAAO,OAAO,UAAU,YAAY,SAAS,KAAK,KAAK;AACzD;;;;;;;AAQA,SAAgB,eAAe,KAAuD;CACpF,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,GAAG,GAAG;EAC9C,IAAI,OAAO,IAAI,SAAS,MAAM,KAAK,UAAU,KAAK,IAAI,QAAQ,KAAK,IAAI;EACvE,IAAI,YAAY,KAAK,GAAG,KAAK,UAAU,KAAK,KAAK,EAAE,GAAG,IAAI,SAAS,MAAM,IAAI,GAAG,IA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AC/G,IAAI,aAAa,OAAO;CACxB,IAAI,eAAe,KAAA,KAAa,MAAM,MACpC,IAAI;EACF,aAAa,KAAK,MAAM,KAAK,IAAI;CACnC,QAAQ;EACN,OAAO;CACT;CAEF,MAAM,UAAU,wBAAwB;EAAE,GAAG;EAAQ,mBAAmB;CAAW,CAAC;CACpF,OAAO,QAAQ,sBAAsB,cAAc,OAAO,sBAAsB,KAAA,IAAY,SAAS;AACvG;AAEA,SAAgB,oBAAoB,QAAuB,UAA2B,CAAC,GAAS;CAC9F,SAAS,eAAe,QAAQ,QAAQ,IAAI;CAC5C,MAAM,SAAS,OAAO,WAAW,CAAC,EAAA,CAC/B,QAAQ,SAAS,KAAK,SAAS,MAAM,CAAC,CACtC,KAAK,SAAS,KAAK,QAAQ,EAAE;CAEhC,IAAI,OAAO,SACT,MAAM,IAAI,aACR,MAAM,KAAK,IAAI,CAAC,CAAC,KAAK,KAAK,8BAC3B,cAAc,OAAO,iBAAiB,CACxC;CAGF,KAAK,MAAM,QAAQ,OAAO,QAAQ,IAAI,qBAAqB,MAAM,QAAQ,MAAM,OAAO,CAAC;AACzF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"public-tools-CQjGt7_q.mjs","names":["isRecord","numberValue"],"sources":["../src/investigation/graph-normalizer.ts","../src/investigation/risk-level.ts","../src/workspace/output-root.ts","../src/lib/usage-accumulator.ts","../src/investigation/public-tools.ts"],"sourcesContent":["const GRAPH_TYPE_LABELS = new Set([\n 'Address',\n 'Exchange',\n 'Miner',\n 'Validator',\n 'Hotkey',\n 'Subnet',\n 'IPAddress',\n])\nconst FLOW_EDGE_TYPES = new Set(['flows_to', 'transfer', 'transfer_to', 'transfers_to'])\n\ntype GraphRecord = Record<string, unknown>\n\nexport type NormalizedGraphPayload = {\n schema: 'chain-insights.graph.v1'\n nodes: GraphRecord[]\n edges: GraphRecord[]\n flows: unknown[]\n edge_anchors: unknown[]\n [key: string]: unknown\n}\n\nfunction isRecord(value: unknown): value is GraphRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction stringArray(value: unknown): string[] {\n return Array.isArray(value) ? value.map(String).filter(Boolean) : []\n}\n\nfunction unique(values: string[]): string[] {\n return [...new Set(values)]\n}\n\nfunction lowerSnake(value: string): string {\n return value\n .trim()\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[^A-Za-z0-9]+/g, '_')\n .replace(/^_+|_+$/g, '')\n .toLowerCase()\n}\n\nfunction isGraphTypeLabel(label: string): boolean {\n return GRAPH_TYPE_LABELS.has(label)\n}\n\nfunction displayLabels(node: GraphRecord): string[] {\n return unique(stringArray(node['labels'])).filter((label) => !isGraphTypeLabel(label))\n}\n\nfunction systemLabels(node: GraphRecord): string[] {\n return unique([\n ...stringArray(node['system_labels']),\n ...stringArray(node['graph_labels']),\n ...stringArray(node['raw_labels']),\n ...stringArray(node['labels']).filter(isGraphTypeLabel),\n ])\n}\n\nfunction normalizeRoles(node: GraphRecord): string[] {\n const roles = stringArray(node['roles'])\n const role = typeof node['role'] === 'string' ? node['role'] : ''\n if (role === 'source_exchange') roles.push('exchange')\n else if (role) roles.push(role)\n\n const display = stringArray(node['labels']).map(lowerSnake)\n if (\n systemLabels(node).some((label) => lowerSnake(label) === 'exchange') ||\n display.includes('exchange')\n ) {\n roles.push('exchange')\n }\n\n return unique(roles.map(lowerSnake).filter(Boolean))\n}\n\nfunction normalizeNodeType(node: GraphRecord): string {\n if (typeof node['node_type'] === 'string' && node['node_type'].trim()) {\n return lowerSnake(node['node_type'])\n }\n if (typeof node['address'] === 'string' || typeof node['id'] === 'string') return 'address'\n const labels = systemLabels(node)\n if (labels.length > 0) return lowerSnake(labels[0]!)\n return 'unknown'\n}\n\nfunction normalizeNode(node: unknown): GraphRecord {\n if (!isRecord(node)) return {}\n\n const normalized: GraphRecord = {}\n for (const [key, value] of Object.entries(node)) {\n if (\n [\n 'address_subtypes',\n 'entity_kind',\n 'graph_labels',\n 'labels',\n 'node_type',\n 'pattern_flags',\n 'raw_labels',\n 'role',\n 'roles',\n 'system_labels',\n 'type',\n ].includes(key)\n ) {\n continue\n }\n normalized[key] = value\n }\n\n const id =\n typeof node['id'] === 'string'\n ? node['id']\n : typeof node['address'] === 'string'\n ? node['address']\n : undefined\n if (id) normalized['id'] = id\n\n const address = typeof node['address'] === 'string' ? node['address'] : id\n if (address) normalized['address'] = address\n\n normalized['node_type'] = normalizeNodeType(node)\n normalized['labels'] = displayLabels(node)\n\n const addressSubtypes = unique(stringArray(node['address_subtypes']))\n if (addressSubtypes.length > 0) normalized['address_subtypes'] = addressSubtypes\n\n const roles = normalizeRoles(node)\n if (roles.length > 0) normalized['roles'] = roles\n\n if (\n !Array.isArray(node['flags']) &&\n Array.isArray(node['pattern_flags']) &&\n node['pattern_flags'].length > 0\n ) {\n normalized['flags'] = node['pattern_flags'].map(String)\n }\n\n return normalized\n}\n\nfunction normalizeEdgeType(edge: GraphRecord): string {\n const rawType =\n typeof edge['edge_type'] === 'string' && edge['edge_type'].trim()\n ? edge['edge_type']\n : typeof edge['type'] === 'string' && edge['type'].trim()\n ? edge['type']\n : typeof edge['relationship_type'] === 'string' && edge['relationship_type'].trim()\n ? edge['relationship_type']\n : 'related_to'\n const edgeType = lowerSnake(rawType)\n return FLOW_EDGE_TYPES.has(edgeType) ? 'flows_to' : edgeType\n}\n\nfunction normalizeEdge(edge: unknown): GraphRecord {\n if (!isRecord(edge)) return {}\n\n const normalized: GraphRecord = {}\n for (const [key, value] of Object.entries(edge)) {\n if (['edge_type', 'from_address', 'relationship_type', 'to_address', 'type'].includes(key))\n continue\n normalized[key] = value\n }\n\n if (typeof normalized['source'] !== 'string' && typeof edge['from_address'] === 'string') {\n normalized['source'] = edge['from_address']\n }\n if (typeof normalized['target'] !== 'string' && typeof edge['to_address'] === 'string') {\n normalized['target'] = edge['to_address']\n }\n normalized['edge_type'] = normalizeEdgeType(edge)\n\n return normalized\n}\n\nexport function normalizeGraphPayload(payload: unknown): NormalizedGraphPayload {\n if (!isRecord(payload) || payload['schema'] !== 'chain-insights.graph.v1') {\n throw new Error('Unsupported graph payload schema')\n }\n\n return {\n ...payload,\n schema: 'chain-insights.graph.v1',\n nodes: Array.isArray(payload['nodes']) ? payload['nodes'].map(normalizeNode) : [],\n edges: Array.isArray(payload['edges']) ? payload['edges'].map(normalizeEdge) : [],\n flows: Array.isArray(payload['flows']) ? payload['flows'] : [],\n edge_anchors: Array.isArray(payload['edge_anchors']) ? payload['edge_anchors'] : [],\n }\n}\n","/**\n * Risk-level normalization shared by the AML tools and graph payload builders.\n *\n * The Chain Insights Graph serves the ML verdict verbatim, which historically\n * mixed cases (HIGH vs high) and — since the calibrated-scoring release —\n * includes an explicit abstention band: risk_level = UNSCORED means the model\n * had too little labeled graph context to stand behind a band. UNSCORED is a\n * \"no stance\" state and must never be rendered or reasoned about as low risk.\n */\n\nexport const RISK_SEVERITIES = ['low', 'medium', 'high', 'critical'] as const\nexport const UNSCORED_RISK_LEVEL = 'unscored'\n\n/** Lowercased, trimmed risk level; undefined for empty/unrecognized values. */\nexport function normalizeRiskLevel(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const normalized = value.trim().toLowerCase()\n if (!normalized) return undefined\n if (normalized === UNSCORED_RISK_LEVEL) return UNSCORED_RISK_LEVEL\n if ((RISK_SEVERITIES as readonly string[]).includes(normalized)) return normalized\n return undefined\n}\n\n/** True when the ML verdict explicitly abstained (no stance, not low). */\nexport function isUnscoredRiskLevel(value: unknown): boolean {\n return normalizeRiskLevel(value) === UNSCORED_RISK_LEVEL\n}\n\n/**\n * Severity ordering for comparisons: low(0) < medium(1) < high(2) <\n * critical(3). Unknown/unscored values rank -1 — they never win a\n * severity comparison, they abstain from it.\n */\nexport function riskSeverityRank(value: unknown): number {\n const normalized = normalizeRiskLevel(value)\n if (!normalized || normalized === UNSCORED_RISK_LEVEL) return -1\n return (RISK_SEVERITIES as readonly string[]).indexOf(normalized)\n}\n","import path from 'node:path'\nimport { findActiveWorkspace } from './active.js'\n\nexport const NO_WORKSPACE_ERROR = 'No Chain Insights workspace found. Run: cia init .'\n\nexport interface WorkspaceOutputPaths {\n root: string\n metadataDir: string\n schemaDir: string\n runtimeDir: string\n artifactsRoot: string\n entitiesRoot: string\n sessionsRoot: string\n publishedRoot: string\n reportsRoot: string\n reportGraphsRoot: string\n reportTablesRoot: string\n logsRoot: string\n}\n\nexport function requireWorkspaceRoot(startDir = process.cwd()): string {\n const workspace = findActiveWorkspace(startDir)\n if (!workspace) throw new Error(NO_WORKSPACE_ERROR)\n return workspace.root\n}\n\nexport function workspaceOutputPaths(workspaceRoot = requireWorkspaceRoot()): WorkspaceOutputPaths {\n const root = path.resolve(workspaceRoot)\n return {\n root,\n metadataDir: path.join(root, '.chain-insights'),\n schemaDir: path.join(root, '.chain-insights', 'schema'),\n runtimeDir: path.join(root, '.chain-insights', 'runtime'),\n artifactsRoot: path.join(root, 'artifacts'),\n entitiesRoot: path.join(root, 'entities'),\n sessionsRoot: path.join(root, 'sessions'),\n publishedRoot: path.join(root, 'published'),\n reportsRoot: path.join(root, 'reports'),\n reportGraphsRoot: path.join(root, 'reports', 'graphs'),\n reportTablesRoot: path.join(root, 'reports', 'tables'),\n logsRoot: path.join(root, '.chain-insights', 'runtime', 'logs'),\n }\n}\n","/**\n * Per-workflow billable-units accounting for the aml_* tools (internal feature:\n * usage-units-propagation). The `aml_*` workflow tools make MANY internal\n * graph_query_batch round trips to answer one high-level question; this\n * module totals what those round trips billed so the workflow response can\n * report a single `usage` block instead of exposing nothing at all.\n *\n * Capture point: aml_address_risk (and internal graph_query_batch helper\n * calls feeding its enrichment) wraps its `remoteClient` once via\n * `wrapClientForUsageTracking` before making any internal calls, then reads\n * the shared `UsageTotals` back out when building its response. Every\n * internal helper (callGraphBatch, probeSeedAddresses, ...) keeps calling\n * `client.callTool(...)` exactly as before -- the wrapper observes\n * graph_query_batch/graph_query responses in transit and never changes their\n * return value.\n *\n * Defensive by design: a backend that does not yet emit billing fields (or\n * an unparsable response) contributes 0 units but the call still counts\n * toward `query_count` -- this must never throw and never block a workflow.\n */\n\ninterface CallToolLike {\n callTool(...args: unknown[]): Promise<unknown>\n}\n\nexport interface UsageTotals {\n billable_units: number\n query_count: number\n truncated_queries: number\n}\n\nexport function createUsageAccumulator(): UsageTotals {\n return { billable_units: 0, query_count: 0, truncated_queries: 0 }\n}\n\n// Snapshot as a plain object for embedding in a response -- callers should\n// not hand out the live mutable accumulator.\nexport function usageBlock(totals: UsageTotals): UsageTotals {\n return {\n billable_units: totals.billable_units,\n query_count: totals.query_count,\n truncated_queries: totals.truncated_queries,\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction numberValue(value: unknown): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string' && value.trim()) {\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : undefined\n }\n return undefined\n}\n\nfunction textOfToolResult(result: unknown): string {\n if (!isRecord(result)) return ''\n const content = result['content']\n if (!Array.isArray(content)) return ''\n return content\n .filter(\n (item): item is { type: 'text'; text: string } =>\n isRecord(item) && item['type'] === 'text' && typeof item['text'] === 'string'\n )\n .map((item) => item.text)\n .join('\\n')\n}\n\n// facts.query.* is the single-query shape (graph_query). facts.batch.* /\n// facts.queries[] is the batch shape (graph_query_batch). Both are read\n// defensively -- missing/malformed fields never throw, they just contribute\n// nothing to the total.\nfunction accumulateFacts(totals: UsageTotals, facts: unknown): void {\n if (!isRecord(facts)) return\n\n const query = facts['query']\n if (isRecord(query)) {\n const units = numberValue(query['billable_units'])\n if (units !== undefined) totals.billable_units += units\n if (query['truncated'] === true) totals.truncated_queries += 1\n }\n\n const batch = facts['batch']\n const batchUnits = isRecord(batch) ? numberValue(batch['billable_units']) : undefined\n const queries = Array.isArray(facts['queries'])\n ? (facts['queries'] as unknown[]).filter(isRecord)\n : undefined\n\n if (batchUnits !== undefined) {\n totals.billable_units += batchUnits\n } else if (queries) {\n // No batch-level total (older/mocked backend): fall back to summing\n // whatever per-query billable_units are present. Entries with no field\n // contribute 0, same as the single-query defensive path.\n for (const entry of queries) {\n const units = numberValue(entry['billable_units'])\n if (units !== undefined) totals.billable_units += units\n }\n }\n\n if (queries) {\n for (const entry of queries) {\n if (entry['truncated'] === true) totals.truncated_queries += 1\n }\n } else if (isRecord(batch) && batch['truncated'] === true) {\n totals.truncated_queries += 1\n }\n}\n\n// One graph_query_batch round trip is one query_count unit per Cypher\n// statement it carried (facts.queries.length) -- that is what \"one internal\n// graph query\" means for this tool. A round trip whose response could not be\n// attributed to individual statements (parse failure, missing facts.queries)\n// still represents one internal graph query having been issued, so it counts\n// as 1 rather than 0.\nfunction recordGraphQueryBatchResult(totals: UsageTotals, rawResult: unknown): void {\n let facts: unknown\n try {\n const text = textOfToolResult(rawResult).trim()\n if (text) facts = (JSON.parse(text) as { facts?: unknown }).facts\n else if (\n isRecord(rawResult) &&\n isRecord((rawResult as Record<string, unknown>)['structuredContent'])\n ) {\n facts = (\n (rawResult as Record<string, unknown>)['structuredContent'] as Record<string, unknown>\n )['facts']\n }\n } catch {\n facts = undefined\n }\n\n const queries =\n isRecord(facts) && Array.isArray(facts['queries']) ? (facts['queries'] as unknown[]) : undefined\n totals.query_count += queries ? queries.length : 1\n accumulateFacts(totals, facts)\n}\n\n// One graph_query round trip is exactly one internal graph query.\nfunction recordGraphQueryResult(totals: UsageTotals, rawResult: unknown): void {\n totals.query_count += 1\n let facts: unknown\n try {\n if (\n isRecord(rawResult) &&\n isRecord((rawResult as Record<string, unknown>)['structuredContent'])\n ) {\n facts = (\n (rawResult as Record<string, unknown>)['structuredContent'] as Record<string, unknown>\n )['facts']\n } else {\n const text = textOfToolResult(rawResult).trim()\n if (text) facts = (JSON.parse(text) as { facts?: unknown }).facts\n }\n } catch {\n facts = undefined\n }\n accumulateFacts(totals, facts)\n}\n\n// Wraps a Client-shaped object (real MCP SDK Client or a test double) so\n// every graph_query_batch/graph_query call it makes is observed and totaled\n// into `totals`, without changing what the call returns. Any other method\n// or property passes through untouched.\nexport function wrapClientForUsageTracking<T extends CallToolLike>(\n client: T,\n totals: UsageTotals\n): T {\n return new Proxy(client as object, {\n get(target, prop, receiver) {\n if (prop === 'callTool') {\n return async (...args: unknown[]) => {\n const result = await (target as CallToolLike).callTool(...args)\n const request = args[0]\n const toolName =\n isRecord(request) && typeof request['name'] === 'string' ? request['name'] : undefined\n if (toolName === 'graph_query_batch') {\n recordGraphQueryBatchResult(totals, result)\n } else if (toolName === 'graph_query') {\n recordGraphQueryResult(totals, result)\n }\n return result\n }\n }\n const value = Reflect.get(target, prop, target)\n return typeof value === 'function' ? value.bind(target) : value\n },\n }) as T\n}\n","import { mkdir, writeFile } from 'node:fs/promises'\nimport path from 'node:path'\nimport type { Client } from '@modelcontextprotocol/sdk/client/index.js'\nimport type { ContentBlock } from '@modelcontextprotocol/sdk/types.js'\nimport { normalizeGraphPayload } from './graph-normalizer.js'\nimport { isUnscoredRiskLevel, normalizeRiskLevel, riskSeverityRank } from './risk-level.js'\nimport { workspaceOutputPaths } from '../workspace/output-root.js'\nimport { GRAPH_TOOL_REQUEST_TIMEOUT_MS } from '../mcp/request-timeout.js'\nimport {\n createUsageAccumulator,\n usageBlock,\n wrapClientForUsageTracking,\n} from '../lib/usage-accumulator.js'\n\nexport { buildTruthProposal, resolveTruthIngressTlsPaths } from './truth-proposal.js'\nexport type { TruthProposalCommand } from './truth-proposal.js'\n\ntype RemoteToolResult = {\n content?: ContentBlock[]\n isError?: boolean\n}\n\ninterface ParsedGraphBatch {\n facts?: {\n queries?: Array<{\n id?: string\n ok?: boolean\n results?: Array<Record<string, unknown>>\n error?: string\n }>\n }\n}\n\ntype QueryFailure = {\n id: string\n error: string\n}\n\nexport interface AddressRiskOptions {\n address: string\n network: string\n compareAddress?: string\n writeArtifacts?: boolean\n}\n\nconst AML_ADDRESS_RISK_SUPPORTED_VERSIONS = ['v1'] as const\nexport type AmlAddressRiskVersion = (typeof AML_ADDRESS_RISK_SUPPORTED_VERSIONS)[number]\nexport const LATEST_AML_ADDRESS_RISK_VERSION: AmlAddressRiskVersion = 'v1'\n\nexport function resolveAmlAddressRiskVersion(requested?: string): AmlAddressRiskVersion {\n const normalized = requested?.trim().toLowerCase()\n if (!normalized) return LATEST_AML_ADDRESS_RISK_VERSION\n if (\n AML_ADDRESS_RISK_SUPPORTED_VERSIONS.includes(\n normalized as (typeof AML_ADDRESS_RISK_SUPPORTED_VERSIONS)[number]\n )\n ) {\n return normalized as AmlAddressRiskVersion\n }\n throw new Error(\n `Unsupported aml_address_risk version \"${requested?.trim() ?? ''}\". Supported versions: ${AML_ADDRESS_RISK_SUPPORTED_VERSIONS.join(', ')}.`\n )\n}\n\nfunction escapeCypherString(value: string): string {\n return value.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"')\n}\n\nfunction textFromToolResult(result: RemoteToolResult): string {\n return (result.content ?? [])\n .filter((item): item is Extract<ContentBlock, { type: 'text' }> => item.type === 'text')\n .map((item) => item.text)\n .join('\\n')\n}\n\nfunction parseGraphBatchResult(result: RemoteToolResult): ParsedGraphBatch {\n const text = textFromToolResult(result).trim()\n if (!text) throw new Error('graph_query_batch returned no text content')\n const parsed = JSON.parse(text) as ParsedGraphBatch\n if (!parsed.facts?.queries)\n throw new Error('graph_query_batch response did not include facts.queries')\n return parsed\n}\n\nfunction topologyGraphQuery(query: string): string {\n const trimmed = query.trim()\n if (/^USE\\s+/i.test(trimmed)) return trimmed\n return `USE topology ${trimmed}`\n}\n\nfunction collectQueryFailure(\n failures: QueryFailure[],\n id: string,\n error: string | undefined\n): void {\n failures.push({ id, error: error || 'unknown error' })\n}\n\nfunction optionalResultsFor(\n batch: ParsedGraphBatch,\n id: string,\n failures: QueryFailure[]\n): Array<Record<string, unknown>> {\n const query = batch.facts?.queries?.find((entry) => entry.id === id)\n if (!query) return []\n if (query.ok === false) {\n collectQueryFailure(failures, id, query.error)\n return []\n }\n return query.results ?? []\n}\n\nfunction optionalResultsWithPrefix(\n batch: ParsedGraphBatch,\n prefix: string,\n failures: QueryFailure[]\n): Array<Record<string, unknown>> {\n return (batch.facts?.queries ?? [])\n .filter((entry) => entry.id?.startsWith(prefix))\n .flatMap((entry) => {\n if (entry.ok === false) {\n collectQueryFailure(failures, entry.id ?? prefix, entry.error)\n return []\n }\n return entry.results ?? []\n })\n}\n\nasync function callGraphBatch(\n remoteClient: Client,\n network: string,\n queries: Array<{ id: string; query: string }>\n): Promise<ParsedGraphBatch> {\n const result = (await remoteClient.callTool(\n {\n name: 'graph_query_batch',\n arguments: {\n network,\n queries: queries.map((query) => ({\n ...query,\n query: topologyGraphQuery(query.query),\n })),\n },\n },\n undefined,\n {\n timeout: GRAPH_TOOL_REQUEST_TIMEOUT_MS,\n maxTotalTimeout: GRAPH_TOOL_REQUEST_TIMEOUT_MS,\n }\n )) as RemoteToolResult\n if (result.isError) throw new Error(textFromToolResult(result) || 'graph_query_batch failed')\n return parseGraphBatchResult(result)\n}\n\nfunction addressProfileQuery(address: string): { id: string; query: string } {\n // risk_score/risk_level are always projected: topology is now the only ML\n // risk source (the retired facts_risk_scores_view never had a risk_level\n // column, so UNSCORED abstention was invisible until this move).\n const riskFields = ', a.risk_score AS live_risk_score, a.risk_level AS live_risk_level'\n // Per-label risk is the overlay graphsync materializes on the node, one\n // entry per current label row. DozerDB properties cannot hold a list of\n // maps, so it is three parallel lists: label_risk_labels, label_risk_levels\n // and label_risk_updated_timestamps. deriveLabelRows zips them back.\n // Missing/empty is \"no label-risk signal,\" never an error.\n const labelRiskFields =\n ', a.label_risk_labels AS label_risk_labels, a.label_risk_levels AS label_risk_levels, a.label_risk_updated_timestamps AS label_risk_updated_timestamps'\n return {\n id: 'address_profile',\n query: [\n `MATCH (a:Address {address: \"${escapeCypherString(address)}\"})`,\n `RETURN a.address AS address, a.network AS network, a.labels AS display_labels, a.labels AS system_labels, a.is_exchange AS is_exchange${riskFields}${labelRiskFields}`,\n 'LIMIT 1',\n ].join(' '),\n }\n}\n\n// Lifetime address features are materialized on the one USE topology node.\nfunction addressFeatureQuery(address: string): { id: string; query: string } {\n return {\n id: 'address_feature',\n query: [\n 'USE topology',\n `MATCH (a:Address {address: \"${escapeCypherString(address)}\"})`,\n 'RETURN a.degree_in AS degree_in, a.degree_out AS degree_out, a.degree_total AS degree_total, a.tx_in_count AS tx_in_count, a.tx_out_count AS tx_out_count, a.tx_total_count AS tx_total_count, a.total_volume_usd AS total_volume_usd, a.total_in_usd AS total_in_usd, a.total_out_usd AS total_out_usd, a.net_flow_usd AS net_flow_usd, a.first_activity_timestamp AS first_activity_timestamp, a.last_activity_timestamp AS last_activity_timestamp, a.activity_span_days AS activity_span_days',\n 'LIMIT 1',\n ].join(' '),\n }\n}\n\nfunction flowEdgeMap(variableName: string): string {\n return `{amount_usd_sum: ${variableName}.amount_usd_sum, tx_count: ${variableName}.tx_count, first_seen_timestamp: ${variableName}.first_seen_timestamp, last_seen_timestamp: ${variableName}.last_seen_timestamp}`\n}\n\nfunction pathNodeMap(variableName: string): string {\n // risk_score/risk_level are always projected on topology nodes.\n const riskFields = `, risk_score: ${variableName}.risk_score, risk_level: ${variableName}.risk_level`\n return `{address: ${variableName}.address, network: ${variableName}.network, labels: ${variableName}.labels, system_labels: ${variableName}.labels, is_exchange: ${variableName}.is_exchange${riskFields}}`\n}\n\n// money-trail enrichment: incident MONEY_TRAIL edges on the subject address\n// (either direction), and the TRAIL_ENDS_AT fan-out of whichever seed\n// generated the trail -- both are optional-results reads, so a graph with no\n// money-trail layer (or a failed query) never fails aml_address_risk itself.\nexport function moneyTrailIncidentQuery(address: string): string {\n return [\n 'USE topology',\n `MATCH (a:Address {address: \"${escapeCypherString(address)}\"})-[r:MONEY_TRAIL]-()`,\n 'RETURN r.edge_class AS edge_class, r.value AS value, r.min_hop AS min_hop, r.seed_count AS seed_count, r.primary_seed AS primary_seed, r.generation AS generation, r.network AS network, r.first_ts AS first_ts, r.last_ts AS last_ts',\n 'LIMIT 200',\n ].join(' ')\n}\n\nexport function moneyTrailEndsQuery(seed: string): string {\n return [\n 'USE topology',\n `MATCH (s:Address {address: \"${escapeCypherString(seed)}\"})-[r:TRAIL_ENDS_AT]->(t:Address)`,\n 'RETURN t.address AS address, r.fact_type AS fact_type, r.direction AS direction, r.terminal_role AS terminal_role, r.hop AS hop, r.value AS value, r.generation AS generation',\n 'LIMIT 200',\n ].join(' ')\n}\n\n// Task 2 (trace fast path): a resolved trace target IS a money-trail seed\n// when it has outgoing TRAIL_ENDS_AT edges -- same shape as\n// moneyTrailEndsQuery, reused here under a probe-specific name so the\n// trace-tool call site reads as \"check whether this address is a seed\"\n// rather than \"fetch the ends fan of a known seed\" (they happen to be the\n// same read).\nexport function moneyTrailSeedProbeQuery(address: string): string {\n return moneyTrailEndsQuery(address)\n}\n\n// Precomputed MONEY_TRAIL corridor from a confirmed seed: bounded to 6 hops\n// (min_hop is a property baked onto the edge by the walk engine, not a\n// variable-length path depth) and excludes peripheral-only continuation --\n// peripheral is the \"touched funds\" floor (see MONEY_TRAIL_CLASS_RANK), not\n// a real trail hop, so it never extends the fast-path corridor.\nexport function moneyTrailCorridorQuery(seed: string): string {\n return [\n 'USE topology',\n `MATCH (s:Address {address: \"${escapeCypherString(seed)}\"})-[r:MONEY_TRAIL]->(t:Address)`,\n 'WHERE r.min_hop <= 6 AND r.edge_class <> \"peripheral\"',\n 'RETURN t.address AS address, r.edge_class AS edge_class, r.value AS value, r.min_hop AS min_hop, r.seed_count AS seed_count, r.primary_seed AS primary_seed, r.generation AS generation, r.network AS network',\n 'ORDER BY r.min_hop ASC',\n 'LIMIT 200',\n ].join(' ')\n}\n\nexport interface MoneyTrailBlock {\n on_trail: true\n class: string\n min_hop: number\n primary_seed: string\n generation: number\n nearest_trail_end?: { address: string; fact_type: string; value: string }\n}\n\nconst MONEY_TRAIL_CLASS_RANK: Record<string, number> = { transport: 3, holding: 2, peripheral: 1 }\n\nexport function buildMoneyTrailBlock(\n incidentRows: Array<Record<string, unknown>>,\n endRows: Array<Record<string, unknown>>\n): MoneyTrailBlock | undefined {\n if (incidentRows.length === 0) return undefined\n\n const winningClassRank = Math.max(\n ...incidentRows.map((row) => MONEY_TRAIL_CLASS_RANK[firstString(row['edge_class']) ?? ''] ?? 0)\n )\n const winningClass =\n Object.entries(MONEY_TRAIL_CLASS_RANK).find(([, rank]) => rank === winningClassRank)?.[0] ??\n firstString(incidentRows[0]?.['edge_class']) ??\n 'peripheral'\n const rowsOfWinningClass = incidentRows.filter(\n (row) => firstString(row['edge_class']) === winningClass\n )\n const bestRow = rowsOfWinningClass.reduce((best, row) => {\n const rowHop = numberValue(row['min_hop']) ?? Number.POSITIVE_INFINITY\n const bestHop = numberValue(best['min_hop']) ?? Number.POSITIVE_INFINITY\n return rowHop < bestHop ? row : best\n }, rowsOfWinningClass[0]!)\n\n const nearestEnd = endRows.reduce<Record<string, unknown> | undefined>((best, row) => {\n const rowValue = numberValue(row['value']) ?? Number.NEGATIVE_INFINITY\n const bestValue = best\n ? (numberValue(best['value']) ?? Number.NEGATIVE_INFINITY)\n : Number.NEGATIVE_INFINITY\n return !best || rowValue > bestValue ? row : best\n }, undefined)\n\n return {\n on_trail: true,\n class: winningClass,\n min_hop: numberValue(bestRow['min_hop']) ?? 0,\n primary_seed: firstString(bestRow['primary_seed']) ?? '',\n generation: numberValue(bestRow['generation']) ?? 0,\n ...(nearestEnd\n ? {\n nearest_trail_end: {\n address: firstString(nearestEnd['address']) ?? '',\n fact_type: firstString(nearestEnd['fact_type']) ?? '',\n value: String(nearestEnd['value'] ?? ''),\n },\n }\n : {}),\n }\n}\n\nexport function moneyTrailSummarySentence(block: MoneyTrailBlock): string {\n return block.class === 'peripheral'\n ? `This address touched money-trail funds (${block.class}, min hop ${block.min_hop}).`\n : `This address sits on a money trail (${block.class}, min hop ${block.min_hop}).`\n}\n\n// Pool guard (cypher skill, \"Pool trace rule\"): a FLOWS_TO walk never starts\n// at a :Pool and never passes through one, and each guard is its own AND term\n// (inside an OR it would guard nothing). Fixed-hop form of\n// skills/chain-insights-cypher: `WHERE NOT src:Pool AND NOT mid:Pool`.\nfunction poolGuardTerms(nodeVariables: string[]): string {\n return nodeVariables.map((nodeVariable) => `NOT ${nodeVariable}:Pool`).join(' AND ')\n}\n\n// System guard (cypher skill, \"Pool trace rule\"): a walk of two or more hops\n// also never starts at, and never passes through, a :Protocol contract (such\n// as a PoolManager) or a system address. Each links millions of unrelated\n// wallets, so a route through one connects nothing. One hop needs no guard:\n// the links of such an address are facts.\nexport const SYSTEM_ADDRESSES = [\n '0x0000000000000000000000000000000000000000',\n '0x000000000000000000000000000000000000dead',\n] as const\nconst SYSTEM_ADDRESS_LIST = `[${SYSTEM_ADDRESSES.map((address) => `\"${address}\"`).join(', ')}]`\n\nfunction systemGuardTerms(nodeVariables: string[]): string {\n return nodeVariables\n .map(\n (nodeVariable) =>\n `NOT ${nodeVariable}:Protocol AND NOT ${nodeVariable}:System AND NOT ${nodeVariable}.address IN ${SYSTEM_ADDRESS_LIST}`\n )\n .join(' AND ')\n}\n\n// The guard of every address a walk leaves: the pool guard, and on a walk of\n// two or more hops the system guard after it.\nfunction walkGuardTerms(nodeVariables: string[], hops: number): string {\n return hops > 1\n ? nodeVariables\n .map(\n (nodeVariable) =>\n `${poolGuardTerms([nodeVariable])} AND ${systemGuardTerms([nodeVariable])}`\n )\n .join(' AND ')\n : poolGuardTerms(nodeVariables)\n}\n\nfunction exchangeOutflowQueries(address: string): Array<{ id: string; query: string }> {\n return Array.from({ length: 3 }, (_, index) => exchangeOutflowQueryAtDepth(address, index + 1))\n}\n\nfunction exchangeOutflowQueryAtDepth(\n address: string,\n depth: number\n): { id: string; query: string } {\n const intermediateVariables = Array.from(\n { length: Math.max(depth - 1, 0) },\n (_, index) => `n${index + 1}`\n )\n const nodeVariables = ['a', ...intermediateVariables, 'exchange']\n const edgeVariables = Array.from({ length: depth }, (_, index) => `r${index + 1}`)\n const relationshipChain = edgeVariables\n .map((edgeVariable, index) => {\n const targetVariable =\n index === edgeVariables.length - 1 ? 'exchange' : intermediateVariables[index]!\n return `-[${edgeVariable}:FLOWS_TO]->(${targetVariable}:Address)`\n })\n .join('')\n const intermediatePredicates = intermediateVariables.map(\n (nodeVariable) => `${nodeVariable}.is_exchange IS NULL`\n )\n // Pool trace rule: the walk starts at the screened address and passes\n // through the intermediates, so none of them may be a :Pool, and on two or\n // more hops none a :Protocol or a system address. The exchange end is the\n // target, which may be one.\n const poolGuards = walkGuardTerms(['a', ...intermediateVariables], depth)\n const depositVariable = nodeVariables[nodeVariables.length - 2]!\n const terminalEdgeVariable = edgeVariables[edgeVariables.length - 1]!\n return {\n id: `exchange_outflows_${depth}`,\n query: [\n `MATCH (a:Address {address: \"${escapeCypherString(address)}\"})${relationshipChain}`,\n `WHERE a.address <> exchange.address AND exchange.is_exchange IS NOT NULL${intermediatePredicates.length > 0 ? ` AND ${intermediatePredicates.join(' AND ')}` : ''} AND ${poolGuards}`,\n `RETURN \"outflow\" AS direction, exchange.address AS exchange_address, exchange.labels AS exchange_display_labels, exchange.labels AS exchange_system_labels, ${depositVariable}.address AS deposit_address, ${depth} AS hops, ${terminalEdgeVariable}.amount_usd_sum AS amount_usd_sum, ${terminalEdgeVariable}.tx_count AS tx_count, ${terminalEdgeVariable}.first_seen_timestamp AS first_seen_timestamp, ${terminalEdgeVariable}.last_seen_timestamp AS last_seen_timestamp, [${nodeVariables.map((nodeVariable) => `${nodeVariable}.address`).join(', ')}] AS addresses, [${nodeVariables.map((nodeVariable) => pathNodeMap(nodeVariable)).join(', ')}] AS path_nodes, [${edgeVariables.map(flowEdgeMap).join(', ')}] AS edge_props`,\n 'ORDER BY hops ASC',\n 'LIMIT 200',\n ].join(' '),\n }\n}\n\nfunction exchangeInflowQueries(address: string): Array<{ id: string; query: string }> {\n return Array.from({ length: 3 }, (_, index) => exchangeInflowQueryAtDepth(address, index + 1))\n}\n\nfunction exchangeInflowQueryAtDepth(address: string, depth: number): { id: string; query: string } {\n const intermediateVariables = Array.from(\n { length: Math.max(depth - 1, 0) },\n (_, index) => `n${index + 1}`\n )\n const nodeVariables = ['exchange', ...intermediateVariables, 'a']\n const edgeVariables = Array.from({ length: depth }, (_, index) => `r${index + 1}`)\n const relationshipChain = edgeVariables\n .map((edgeVariable, index) => {\n const targetVariable =\n index === edgeVariables.length - 1 ? 'a' : intermediateVariables[index]!\n return `-[${edgeVariable}:FLOWS_TO]->(${targetVariable}:Address)`\n })\n .join('')\n const intermediatePredicates = intermediateVariables.map(\n (nodeVariable) => `${nodeVariable}.is_exchange IS NULL`\n )\n // Pool trace rule: the trace starts at the screened address `a` and walks\n // back through the intermediates, so none of them may be a :Pool, and on\n // two or more hops none a :Protocol or a system address. The exchange end\n // is the target, which may be one.\n const poolGuards = walkGuardTerms(['a', ...intermediateVariables], depth)\n const withdrawalVariable = nodeVariables[1]!\n const terminalEdgeVariable = edgeVariables[edgeVariables.length - 1]!\n return {\n id: `exchange_inflows_${depth}`,\n query: [\n `MATCH (exchange:Address)${relationshipChain}`,\n `WHERE a.address = \"${escapeCypherString(address)}\" AND a.address <> exchange.address AND exchange.is_exchange IS NOT NULL${intermediatePredicates.length > 0 ? ` AND ${intermediatePredicates.join(' AND ')}` : ''} AND ${poolGuards}`,\n `RETURN \"inflow\" AS direction, exchange.address AS exchange_address, exchange.labels AS exchange_display_labels, exchange.labels AS exchange_system_labels, ${withdrawalVariable}.address AS withdrawal_address, ${depth} AS hops, ${terminalEdgeVariable}.amount_usd_sum AS amount_usd_sum, ${terminalEdgeVariable}.tx_count AS tx_count, ${terminalEdgeVariable}.first_seen_timestamp AS first_seen_timestamp, ${terminalEdgeVariable}.last_seen_timestamp AS last_seen_timestamp, [${nodeVariables.map((nodeVariable) => `${nodeVariable}.address`).join(', ')}] AS addresses, [${nodeVariables.map((nodeVariable) => pathNodeMap(nodeVariable)).join(', ')}] AS path_nodes, [${edgeVariables.map(flowEdgeMap).join(', ')}] AS edge_props`,\n 'ORDER BY hops ASC',\n 'LIMIT 200',\n ].join(' '),\n }\n}\n\nfunction connectionProbeQuery(\n address: string,\n compareAddress: string\n): { id: string; query: string } {\n return {\n id: 'connection_probe',\n query: [\n `MATCH (a:Address {address: \"${escapeCypherString(address)}\"})-[r:FLOWS_TO]-(b:Address {address: \"${escapeCypherString(compareAddress)}\"})`,\n 'RETURN [a.address, b.address] AS addresses, 1 AS hops',\n 'LIMIT 5',\n ].join(' '),\n }\n}\n\n// Address-grain has no separate identity-resolution lookup: existence of the\n// compare_address is checked directly against :Address, distinct from the\n// primary address_profile query so both existence checks can run in one batch.\nfunction compareAddressExistsQuery(address: string): { id: string; query: string } {\n return {\n id: 'compare_address_exists',\n query: [\n `MATCH (a:Address {address: \"${escapeCypherString(address)}\"})`,\n 'RETURN a.address AS address',\n 'LIMIT 1',\n ].join(' '),\n }\n}\n\n// Pool trace rule: the via_linked read is a two-hop walk through `owned`, so\n// `a` and `owned` carry the pool and the system guard and the target `b` may\n// be a pool. The direct\n// read is a counterparty listing of one address, not a trace, and stays\n// unguarded (ruling: a pool's own counterparty list is a listing).\n// AC11: FLOWS_TO reachability UNIONed over one -[:LINKED]- hop, so an\n// investigator surveying an address's exposure also sees exposure carried by\n// an address that is only ownership-LINKED to it (LINKED is undirected).\nfunction linkedExposureQueries(address: string): Array<{ id: string; query: string }> {\n return [\n {\n id: 'linked_exposure_direct',\n query: [\n `MATCH (a:Address {address: \"${escapeCypherString(address)}\"})-[r:FLOWS_TO]-(b:Address)`,\n 'WHERE a.address <> b.address',\n `RETURN a.address AS subject_address, b.address AS counterparty_address, b.network AS counterparty_network, \"direct\" AS exposure_basis, r.amount_usd_sum AS amount_usd_sum, r.tx_count AS tx_count`,\n 'LIMIT 200',\n ].join(' '),\n },\n {\n id: 'linked_exposure_via_linked',\n query: [\n `MATCH (a:Address {address: \"${escapeCypherString(address)}\"})-[l:LINKED]-(owned:Address)-[r:FLOWS_TO]-(b:Address)`,\n `WHERE ${walkGuardTerms(['a', 'owned'], 2)} AND owned.address <> b.address AND a.address <> b.address`,\n `RETURN a.address AS subject_address, b.address AS counterparty_address, b.network AS counterparty_network, \"via_linked\" AS exposure_basis, owned.address AS linked_via_address, l.basis AS link_basis, l.confidence AS link_confidence, r.amount_usd_sum AS amount_usd_sum, r.tx_count AS tx_count`,\n 'LIMIT 200',\n ].join(' '),\n },\n ]\n}\n\n// AC5: LINKED ownership-overlay probe. On the single public robinhood graph,\n// `network` is the query's network on every node, never stored, so both ends of\n// a LINKED edge read the same value and never a second query network: LINKED is\n// the ownership edge within that one space, served on the topology graph only,\n// with no network switch.\nfunction crossSpaceLinkedQuery(address: string): { id: string; query: string } {\n return {\n id: 'cross_space_linked',\n query: [\n `MATCH (a:Address {address: \"${escapeCypherString(address)}\"})-[l:LINKED]-(b:Address)`,\n 'WHERE a.network <> b.network',\n 'RETURN a.address AS address, a.network AS network, b.address AS linked_address, b.network AS linked_network, l.basis AS basis, l.confidence AS confidence, l.source_event AS source_event, l.declared_owner AS declared_owner',\n 'LIMIT 50',\n ].join(' '),\n }\n}\n\n// ── Pairwise route evidence ──\n// Undirected shortest route between two KNOWN identity endpoints. The\n// topology graph speaks ISO GQL, so both routes use one shortest path.\n// Exchange intermediates on a returned route are DISCLOSED in the evidence,\n// never silently filtered out.\n//\n// Pool trace rule (cypher skill, \"Pool trace rule\"): a route never starts at\n// a :Pool and never passes through one, and it may end at one. It follows\n// FLOWS_TO and SWAPPED, so it crosses a swap from payer to recipient. The\n// guard sits inside the path pattern, so the search finds the shortest route\n// that avoids pools instead of dropping a shortest route that crosses one.\n//\n// The text is the guarded route contract (ruled 2026-09-28), served word for\n// word by skills/chain-insights-cypher, and graphrag-mcp rewrites exactly this\n// shape onto DozerDB's fast shortest-path search (data-pipeline\n// route_rewrite.go). Change the addresses and the RETURN only. The quantifier\n// bound covers the guarded middle; the last hop is the unguarded target end,\n// so a route is 1 to CONNECTION_ROUTE_DEPTH_BOUND + 1 hops. The `{0,...}`\n// lower bound keeps DozerDB off the slow undirected search.\n\nexport const CONNECTION_ROUTE_DEPTH_BOUND = 4\n// A route is the guarded middle plus the last hop to the target end.\nexport const CONNECTION_ROUTE_MAX_HOPS = CONNECTION_ROUTE_DEPTH_BOUND + 1\n\nexport function shouldIncludeRouteQueries(compareAddress: string | undefined): boolean {\n // GQL shortest-path traversal always fires when a compare address is given.\n return Boolean(compareAddress)\n}\n\nexport function connectionRouteQueries(\n address: string,\n compareAddress: string\n): Array<{ id: string; query: string }> {\n const routeQuery = (fromAddress: string, toAddress: string): string =>\n [\n `MATCH p = SHORTEST 1 (a:Address {address: \"${escapeCypherString(fromAddress)}\"} WHERE ${walkGuardTerms(['a'], 2)})`,\n ` (()-[:FLOWS_TO|SWAPPED]-(via:Address) WHERE ${walkGuardTerms(['via'], 2)}){0,${CONNECTION_ROUTE_DEPTH_BOUND}}`,\n ` ()-[:FLOWS_TO|SWAPPED]-(b:Address {address: \"${escapeCypherString(toAddress)}\"}) RETURN p LIMIT 1`,\n ].join('')\n return [\n { id: 'connection_route_outbound', query: routeQuery(address, compareAddress) },\n { id: 'connection_route_inbound', query: routeQuery(compareAddress, address) },\n ]\n}\n\nexport interface RouteEvidenceSide {\n hops: number\n identities: string[]\n exchange_intermediates: string[]\n amount_usd_sum_total: number\n}\n\nfunction collectOrdered(\n value: unknown,\n matches: (candidate: Record<string, unknown>) => boolean\n): Array<Record<string, unknown>> {\n const collected: Array<Record<string, unknown>> = []\n const walk = (node: unknown): void => {\n if (Array.isArray(node)) {\n for (const entry of node) walk(entry)\n return\n }\n if (node && typeof node === 'object') {\n const candidate = node as Record<string, unknown>\n if (matches(candidate)) collected.push(candidate)\n for (const nested of Object.values(candidate)) walk(nested)\n }\n }\n walk(value)\n return collected\n}\n\n// is_exchange on topology nodes is a MARKER, not a boolean: it usually\n// carries the exchange name (e.g. \"binance\"). Treat explicit falsy\n// encodings as not-exchange (a bare non-null check would falsely disclose\n// nodes serialized as false/\"false\"/0), and any other non-empty value as\n// exchange. isExchangeFlag() is NOT reused here — it is boolean-only and\n// would miss name-valued markers.\nexport function isExchangeMarker(value: unknown): boolean {\n if (value === null || value === undefined || value === false) return false\n if (typeof value === 'number') return value !== 0\n if (typeof value === 'string') {\n const normalized = value.trim().toLowerCase()\n return (\n normalized !== '' && normalized !== 'false' && normalized !== '0' && normalized !== 'null'\n )\n }\n return value === true\n}\n\n// Shape-tolerant hydrated-path reader: walks the returned path value for\n// ordered address nodes and FLOWS_TO edge amounts without pinning the\n// backend's exact path envelope.\nexport function routeFromPathValue(value: unknown): RouteEvidenceSide | null {\n if (!value || typeof value !== 'object') return null\n const nodes = collectOrdered(value, (candidate) => typeof candidate['address'] === 'string')\n if (nodes.length < 2) return null\n const edges = collectOrdered(\n value,\n (candidate) => typeof candidate['amount_usd_sum'] === 'number' && !('address' in candidate)\n )\n const identities = nodes.map((node) => String(node['address']))\n const exchangeIntermediates = nodes\n .slice(1, -1)\n .filter((node) => isExchangeMarker(node['is_exchange']))\n .map((node) => String(node['address']))\n return {\n // Hop count is a structural property of the node sequence — never\n // derived from edge-object detection, which keys on numeric\n // amount_usd_sum and would under-report on partially hydrated edges.\n hops: nodes.length - 1,\n identities,\n exchange_intermediates: exchangeIntermediates,\n amount_usd_sum_total: edges.reduce((total, edge) => total + Number(edge['amount_usd_sum']), 0),\n }\n}\n\nexport interface RouteEvidence {\n search_strategy: 'any_shortest'\n route_rank_basis: 'hop_count'\n depth_bound: number\n route_found: boolean\n outbound: RouteEvidenceSide | null\n inbound: RouteEvidenceSide | null\n}\n\nexport function buildRouteEvidence(\n outboundRows: Array<Record<string, unknown>>,\n inboundRows: Array<Record<string, unknown>>\n): RouteEvidence {\n const sideFrom = (rows: Array<Record<string, unknown>>): RouteEvidenceSide | null => {\n const first = rows[0]\n if (!first) return null\n const pathValue = 'p' in first ? first['p'] : Object.values(first)[0]\n return routeFromPathValue(pathValue)\n }\n const outbound = sideFrom(outboundRows)\n const inbound = sideFrom(inboundRows)\n return {\n search_strategy: 'any_shortest',\n route_rank_basis: 'hop_count',\n depth_bound: CONNECTION_ROUTE_MAX_HOPS,\n route_found: outbound !== null || inbound !== null,\n outbound,\n inbound,\n }\n}\n\nfunction formatExchangeRows(rows: Array<Record<string, unknown>>): string[] {\n return rows.map((row) => {\n const direction = String(row['direction'] ?? 'flow')\n const exchange = String(row['exchange_address'] ?? '')\n const amount = row['amount_usd_sum'] ?? ''\n const hops = row['hops'] ?? ''\n return `- ${direction}: ${exchange} (${hops} hop(s), amount_usd_sum ${amount})`\n })\n}\n\nfunction numberValue(value: unknown): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string' && value.trim()) {\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : undefined\n }\n return undefined\n}\n\nfunction firstNumber(...values: unknown[]): number | undefined {\n for (const value of values) {\n const parsed = numberValue(value)\n if (parsed !== undefined) return parsed\n }\n return undefined\n}\n\nfunction firstString(...values: unknown[]): string | undefined {\n for (const value of values) {\n if (typeof value === 'string' && value.trim()) return value.trim()\n }\n return undefined\n}\n\nfunction riskLevelFromScore(score: number): string {\n if (score >= 0.85) return 'critical'\n if (score >= 0.7) return 'high'\n if (score >= 0.4) return 'medium'\n return 'low'\n}\n\nfunction riskRecommendation(level: string): string {\n if (level === 'critical' || level === 'high') return 'Escalate for manual review.'\n if (level === 'medium') return 'Review exchange exposure and counterparties before clearing.'\n return 'No stored risk signal found; continue with normal monitoring.'\n}\n\nfunction riskDrivers(\n profile: Record<string, unknown>,\n labelRows: Array<Record<string, unknown>>,\n exchangeRows: Array<Record<string, unknown>>\n): string[] {\n const drivers: string[] = []\n\n const riskLabels = labelRows\n .map((row) => firstString(row['label']))\n .filter((label): label is string => Boolean(label))\n if (riskLabels.length > 0) drivers.push(`Labels: ${[...new Set(riskLabels)].join('; ')}`)\n\n const outflowCount = exchangeRows.filter((row) => row['direction'] === 'outflow').length\n const inflowCount = exchangeRows.filter((row) => row['direction'] === 'inflow').length\n if (outflowCount > 0)\n drivers.push(`Forward bounded search reached ${outflowCount} exchange path(s).`)\n if (inflowCount > 0)\n drivers.push(`Backward bounded search found ${inflowCount} source exchange path(s).`)\n\n return [...new Set(drivers)]\n}\n\n// Derives the deterministic labelRows subset from the profile row's three\n// label_risk_* lists (topology), reproducing the retired\n// addressLabelRiskQuery's `ORDER BY label.updated_timestamp DESC LIMIT 10`\n// subset byte-for-byte: same sort, same cap. The lists are parallel: entry i\n// of each one describes the same label row. Missing/empty lists -> empty\n// array, same as \"no labels\" behaved under the old facts read.\nfunction deriveLabelRows(profile: Record<string, unknown>): Array<Record<string, unknown>> {\n // Dozer/Neo4j properties cannot store lists of maps. Sync therefore\n // materializes the three map fields as parallel primitive arrays.\n const labels = Array.isArray(profile['label_risk_labels'])\n ? (profile['label_risk_labels'] as unknown[]).map((value) => String(value))\n : []\n const riskLevels = Array.isArray(profile['label_risk_levels'])\n ? (profile['label_risk_levels'] as unknown[]).map((value) => String(value))\n : []\n const timestamps = Array.isArray(profile['label_risk_updated_timestamps'])\n ? (profile['label_risk_updated_timestamps'] as unknown[]).map((value) => numberValue(value))\n : []\n const rows = labels.map((label, index) => ({\n label,\n risk_level: riskLevels[index] ?? '',\n updated_timestamp: timestamps[index] ?? 0,\n }))\n return [...rows]\n .sort(\n (a, b) =>\n (numberValue(b['updated_timestamp']) ?? 0) - (numberValue(a['updated_timestamp']) ?? 0)\n )\n .slice(0, 10)\n}\n\nconst RISK_LEVEL_ORDER = ['critical', 'high', 'medium', 'low'] as const\n\nfunction strongestLabelRiskLevel(labelRows: Array<Record<string, unknown>>): string | undefined {\n const levels = labelRows\n .map((row) => firstString(row['risk_level'])?.toLowerCase())\n .filter((level): level is string =>\n Boolean(level && (RISK_LEVEL_ORDER as readonly string[]).includes(level))\n )\n if (levels.length === 0) return undefined\n return RISK_LEVEL_ORDER.find((candidate) => levels.includes(candidate))\n}\n\nfunction riskScoreSources(\n profile: Record<string, unknown>,\n labelRows: Array<Record<string, unknown>>\n): Array<Record<string, unknown>> {\n const sources: Array<Record<string, unknown>> = []\n if (numberValue(profile['live_risk_score']) !== undefined) {\n sources.push({\n family: 'ml_risk_score',\n layer: 'topology',\n source: 'address_node',\n fields: ['risk_score', 'risk_level'],\n })\n }\n if (labelRows.length > 0) {\n sources.push({\n family: 'label_risk',\n layer: 'topology',\n source: 'address_node',\n labels: labelRows.map((row) => ({\n label: row['label'],\n risk_level: row['risk_level'],\n })),\n })\n }\n return sources\n}\n\nfunction terminalEdgeProperties(row: Record<string, unknown>): Record<string, unknown> | undefined {\n const edgeProps = Array.isArray(row['edge_props'])\n ? (row['edge_props'] as Array<Record<string, unknown>>)\n : []\n return edgeProps[edgeProps.length - 1]\n}\n\nfunction enrichExchangeRows(rows: Array<Record<string, unknown>>): Array<Record<string, unknown>> {\n return rows.map((row) => {\n const terminal = terminalEdgeProperties(row)\n if (!terminal) return row\n return {\n ...row,\n amount_usd_sum: row['amount_usd_sum'] ?? terminal['amount_usd_sum'],\n tx_count: row['tx_count'] ?? terminal['tx_count'],\n first_seen_timestamp: row['first_seen_timestamp'] ?? terminal['first_seen_timestamp'],\n last_seen_timestamp: row['last_seen_timestamp'] ?? terminal['last_seen_timestamp'],\n }\n })\n}\n\nconst FALLBACK_SHARED_TX_COUNT = 1000\nconst FALLBACK_SHARED_USD_SUM = 5_000_000\nconst FALLBACK_SHARED_DAMPING = 0.1\nconst FALLBACK_VALUE_SATURATION_USD = 1_000_000\nconst FALLBACK_BASE_SCORE = 0.1\nconst FALLBACK_MAX_SCORE = 0.6\n\n/**\n * Score exchange exposure when no ML risk score exists. Topology-grain:\n * log-scaled USD volume across exchange rows, with shared/omnibus edges\n * (high tx_count or USD throughput) dampened, bounded in (0, 0.6] so a\n * fallback can never impersonate a high ML score band.\n */\nexport function exchangeExposureFallbackScore(\n exchangeRows: Array<Record<string, unknown>>\n): number {\n if (exchangeRows.length === 0) return 0\n let weightedUsd = 0\n for (const row of exchangeRows) {\n const usd = numberValue(row['amount_usd_sum']) ?? 0\n const txCount = numberValue(row['tx_count']) ?? 0\n const shared = txCount >= FALLBACK_SHARED_TX_COUNT || usd >= FALLBACK_SHARED_USD_SUM\n weightedUsd += shared ? usd * FALLBACK_SHARED_DAMPING : usd\n }\n const capped = Math.min(weightedUsd, FALLBACK_VALUE_SATURATION_USD)\n const factor = Math.log10(1 + capped) / Math.log10(1 + FALLBACK_VALUE_SATURATION_USD)\n return Math.min(\n FALLBACK_MAX_SCORE,\n FALLBACK_BASE_SCORE + (FALLBACK_MAX_SCORE - FALLBACK_BASE_SCORE) * factor\n )\n}\n\nexport function riskAssessment(\n profile: Record<string, unknown>,\n labelRows: Array<Record<string, unknown>>,\n exchangeRows: Array<Record<string, unknown>>\n): Record<string, unknown> {\n const mlRiskScore = firstNumber(profile['live_risk_score'])\n // UNSCORED is the model's explicit abstention (calibrated-scoring release):\n // the score exists for transparency but carries no stance — deriving a\n // severity band from it would silently launder an abstention into a\n // confident verdict (typically \"low\"). Fall back to labels/exchange\n // exposure and say so.\n const mlAbstained = isUnscoredRiskLevel(profile['live_risk_level'])\n const labelRiskLevel = strongestLabelRiskLevel(labelRows)\n const usableMlScore = mlAbstained ? undefined : mlRiskScore\n const score = usableMlScore ?? exchangeExposureFallbackScore(exchangeRows)\n let level =\n labelRiskLevel ??\n (mlAbstained && exchangeRows.length === 0 ? 'unscored' : riskLevelFromScore(score))\n const drivers = riskDrivers(profile, labelRows, exchangeRows)\n if (mlAbstained)\n drivers.push(\n 'ml_abstained: ML verdict is UNSCORED (insufficient labeled graph context); level derived from labels/exchange exposure only'\n )\n // Labels are curated truth and stay first — but a lower-severity label\n // must never SUPPRESS a more severe usable ML band. Failing toward\n // \"looks safe\" is the one direction an AML triage tool may not fail.\n const usableMlBand = usableMlScore !== undefined ? riskLevelFromScore(usableMlScore) : undefined\n if (\n labelRiskLevel &&\n usableMlBand &&\n riskSeverityRank(usableMlBand) > riskSeverityRank(labelRiskLevel)\n ) {\n level = usableMlBand\n drivers.push(\n `ml_label_divergence: usable ML band ${usableMlBand} exceeds strongest label level ${labelRiskLevel}; reporting the more severe band — review the label`\n )\n }\n return {\n level,\n score,\n ...(mlRiskScore !== undefined ? { ml_risk_score: mlRiskScore } : {}),\n ...(mlAbstained ? { ml_verdict: 'unscored' } : {}),\n confidence:\n usableMlScore !== undefined || labelRiskLevel\n ? 'high'\n : exchangeRows.length > 0\n ? 'medium'\n : 'low',\n recommendation:\n level === 'unscored'\n ? 'Model abstained and no label/exchange signal found; gather more context before clearing.'\n : riskRecommendation(level),\n drivers,\n sources: riskScoreSources(profile, labelRows),\n }\n}\n\nfunction formatRiskScore(score: unknown): string {\n const parsed = numberValue(score)\n if (parsed === undefined) return String(score ?? 'unknown')\n return Number.isInteger(parsed) ? parsed.toString() : parsed.toFixed(2)\n}\n\nfunction stringArrayValue(value: unknown): string[] | undefined {\n if (Array.isArray(value)) return value.map(String)\n if (typeof value === 'string' && value.trim()) return [value]\n return undefined\n}\n\nfunction restoreSystemLabels(\n graph: Record<string, unknown>,\n rawNodes: Array<Record<string, unknown>>\n): Record<string, unknown> {\n if (!Array.isArray(graph['nodes'])) return graph\n const labelsByAddress = new Map(\n rawNodes\n .map(\n (node) =>\n [\n typeof node['address'] === 'string'\n ? node['address']\n : typeof node['id'] === 'string'\n ? node['id']\n : '',\n stringArrayValue(node['system_labels']),\n ] as const\n )\n .filter(\n (entry): entry is readonly [string, string[]] =>\n Boolean(entry[0]) && Array.isArray(entry[1]) && entry[1].length > 0\n )\n )\n return {\n ...graph,\n nodes: graph['nodes'].map((node) => {\n if (typeof node !== 'object' || node === null || Array.isArray(node)) return node\n const record = node as Record<string, unknown>\n const address =\n typeof record['address'] === 'string'\n ? record['address']\n : typeof record['id'] === 'string'\n ? record['id']\n : ''\n const systemLabels = labelsByAddress.get(address)\n return systemLabels ? { ...record, system_labels: systemLabels } : record\n }),\n }\n}\n\nfunction buildRiskGraph(\n address: string,\n profile: Record<string, unknown>,\n rows: Array<Record<string, unknown>>,\n network: string\n): Record<string, unknown> {\n const nodes = new Map<string, Record<string, unknown>>()\n nodes.set(address, {\n id: address,\n address,\n node_type: 'address',\n labels: stringArrayValue(profile['display_labels']) ?? [],\n ...(stringArrayValue(profile['system_labels'])\n ? { system_labels: stringArrayValue(profile['system_labels']) }\n : {}),\n ...(stringArrayValue(profile['member_addresses'])?.length\n ? { member_addresses: stringArrayValue(profile['member_addresses']) }\n : {}),\n ...(numberValue(profile['live_risk_score']) !== undefined\n ? { risk_score: numberValue(profile['live_risk_score']) }\n : {}),\n ...(firstString(profile['live_risk_level'])\n ? { risk_level: firstString(profile['live_risk_level']) }\n : {}),\n roles: ['subject'],\n })\n const edges: Array<Record<string, unknown>> = []\n const mergeNode = (entry: string, metadata?: Record<string, unknown>) => {\n const existing = nodes.get(entry) ?? {\n id: entry,\n address: entry,\n node_type: 'address',\n labels: [],\n }\n const labels = stringArrayValue(metadata?.['labels']) ?? existing['labels']\n const systemLabels = stringArrayValue(metadata?.['system_labels']) ?? existing['system_labels']\n const memberAddresses =\n stringArrayValue(metadata?.['member_addresses']) ?? existing['member_addresses']\n const riskScore = numberValue(metadata?.['risk_score']) ?? existing['risk_score']\n const riskLevel =\n normalizeRiskLevel(firstString(metadata?.['risk_level'])) ?? existing['risk_level']\n nodes.set(entry, {\n ...existing,\n labels,\n ...(systemLabels ? { system_labels: systemLabels } : {}),\n ...(Array.isArray(memberAddresses) && memberAddresses.length > 0\n ? { member_addresses: memberAddresses }\n : {}),\n ...(riskScore !== undefined ? { risk_score: riskScore } : {}),\n ...(riskLevel ? { risk_level: riskLevel } : {}),\n })\n }\n for (const row of rows) {\n const rawPath = Array.isArray(row['path']) ? row['path'] : row['addresses']\n const path = Array.isArray(rawPath) ? rawPath.map(String) : []\n const pathNodes = Array.isArray(row['path_nodes'])\n ? (row['path_nodes'] as Array<Record<string, unknown>>)\n : []\n for (let index = 0; index < path.length; index += 1) {\n const entry = path[index]!\n mergeNode(entry, pathNodes[index])\n }\n const exchange = typeof row['exchange_address'] === 'string' ? row['exchange_address'] : ''\n if (exchange) {\n const displayLabels = stringArrayValue(row['exchange_display_labels']) ?? []\n const systemLabels =\n stringArrayValue(row['exchange_system_labels']) ??\n stringArrayValue(row['exchange_labels']) ??\n []\n nodes.set(exchange, {\n id: exchange,\n address: exchange,\n node_type: 'address',\n labels: displayLabels,\n ...(systemLabels.length > 0 ? { system_labels: systemLabels } : {}),\n roles: ['exchange'],\n })\n }\n for (let index = 0; index < path.length - 1; index += 1) {\n const edgeProps = Array.isArray(row['edge_props'])\n ? (row['edge_props'] as Array<Record<string, unknown>>)\n : []\n const edge = edgeProps[index] ?? row\n edges.push({\n source: path[index],\n target: path[index + 1],\n edge_type: 'flows_to',\n usd_amount: edge['amount_usd_sum'] ?? 0,\n amount_usd_sum: edge['amount_usd_sum'] ?? 0,\n tx_count: edge['tx_count'] ?? 0,\n direction: row['direction'],\n })\n }\n }\n const rawNodes = [...nodes.values()]\n return restoreSystemLabels(\n normalizeGraphPayload({\n schema: 'chain-insights.graph.v1',\n nodes: rawNodes,\n edges,\n flows: [],\n edge_anchors: [],\n metadata: { address, network, generated_at: new Date().toISOString() },\n }),\n rawNodes\n )\n}\n\nexport async function addressRisk(\n remoteClient: Client,\n options: AddressRiskOptions\n): Promise<{\n summaryText: string\n structuredContent: Record<string, unknown>\n graphData: Record<string, unknown>\n}> {\n const address = options.address.trim()\n const network = options.network.trim()\n const compareInput = options.compareAddress?.trim() ?? ''\n if (!address) throw new Error('address is required')\n if (!network) throw new Error('network is required')\n\n // Every internal graph_query_batch round trip this workflow makes is\n // observed here and totaled into a usage block on the response (never\n // blocks/throws on a backend that doesn't emit billing fields yet).\n const usage = createUsageAccumulator()\n const trackedClient = wrapClientForUsageTracking(remoteClient, usage)\n\n // Address-grain has no separate resolution step for the SUBJECT address:\n // the input address IS the graph node key. Its existence is inferred\n // post-hoc from the address_profile row (below) instead of the pre-revert\n // pre-flight lookup -- deliberate: it saves a round trip on the hot path.\n // The COMPARE address keeps a pre-flight existence probe, because the\n // connection probe and shortest-path route queries must be SUPPRESSED (not\n // ignored) when the compare address does not exist -- pre-revert behavior\n // never issued route probes for an unresolved compare input.\n let compareUnresolved = false\n if (compareInput) {\n const compareBatch = await callGraphBatch(trackedClient, network, [\n compareAddressExistsQuery(compareInput),\n ])\n const compareRows = optionalResultsFor(compareBatch, 'compare_address_exists', [])\n compareUnresolved = !firstString(compareRows[0]?.['address'])\n }\n const compareAddress = compareInput && !compareUnresolved ? compareInput : ''\n\n const queries = [\n addressProfileQuery(address),\n addressFeatureQuery(address),\n { id: 'money_trail_incident', query: moneyTrailIncidentQuery(address) },\n ...exchangeOutflowQueries(address),\n ...exchangeInflowQueries(address),\n ...(compareAddress\n ? [connectionProbeQuery(address, compareAddress)]\n : [\n {\n id: 'connection_probe',\n query:\n 'MATCH (n:Address {address: \"__chain_insights_noop__\"}) RETURN n.address AS noop LIMIT 0',\n },\n ]),\n // Route evidence is additive: ISO GQL shortest-path traversal always\n // fires for a compare address whose existence probe succeeded (the\n // 1-hop probe above always runs).\n ...(shouldIncludeRouteQueries(compareAddress)\n ? connectionRouteQueries(address, compareAddress)\n : []),\n ]\n const batch = await callGraphBatch(trackedClient, network, queries)\n const partialQueryFailures: QueryFailure[] = []\n // Deliberate post-hoc existence inference (address grain): an empty\n // address_profile result means the subject :Address does not exist ->\n // report unresolved; this replaces the pre-revert identity pre-flight.\n const addressProfileRows = optionalResultsFor(batch, 'address_profile', partialQueryFailures)\n if (addressProfileRows.length === 0) {\n return {\n summaryText: `Address risk for ${network}:${address}\\n\\nUnresolved: no Address found for \"${address}\". The address may not have on-chain activity in this network.`,\n structuredContent: {\n schema: 'chain-insights.result.v1',\n tool: 'aml_address_risk',\n facts: {\n subject: { network, addresses: [address] },\n unresolved: [address],\n usage: usageBlock(usage),\n },\n },\n graphData: {\n schema: 'chain-insights.graph.v1',\n nodes: [],\n edges: [],\n flows: [],\n edge_anchors: [],\n metadata: { address, network, generated_at: new Date().toISOString() },\n },\n }\n }\n const profile: Record<string, unknown> = {\n address,\n ...(addressProfileRows[0] ?? {}),\n ...(optionalResultsFor(batch, 'address_feature', partialQueryFailures)[0] ?? {}),\n }\n const labelRows = deriveLabelRows(profile)\n const outflows = enrichExchangeRows(\n optionalResultsWithPrefix(batch, 'exchange_outflows_', partialQueryFailures)\n )\n const inflows = enrichExchangeRows(\n optionalResultsWithPrefix(batch, 'exchange_inflows_', partialQueryFailures)\n )\n const connections = compareAddress\n ? optionalResultsFor(batch, 'connection_probe', partialQueryFailures)\n : []\n const routeEvidence = shouldIncludeRouteQueries(compareAddress)\n ? buildRouteEvidence(\n optionalResultsFor(batch, 'connection_route_outbound', partialQueryFailures),\n optionalResultsFor(batch, 'connection_route_inbound', partialQueryFailures)\n )\n : undefined\n const exchangeRows = [...outflows, ...inflows]\n // A hop-depth exchange_outflows_N/exchange_inflows_N query can fail\n // independently (e.g. the archive-tier query-memory limit on a deep\n // multi-hop search) while other hop depths succeed with zero rows. An\n // empty exchangeRows result must then read as \"search incomplete,\" not\n // \"no exchange exposure\" -- the two are not the same claim, and an AML\n // tool that silently reports a false-clean verdict on a partial search\n // failure is a real risk (found during MoA review, 2026-07-05).\n const exchangeSearchFailures = partialQueryFailures.filter(\n (failure) =>\n failure.id.startsWith('exchange_outflows_') || failure.id.startsWith('exchange_inflows_')\n )\n const exchangeSearchComplete = exchangeSearchFailures.length === 0\n // money-trail enrichment (optional): a preliminary block resolves the\n // primary_seed off the incident-only rows, then a second batch call fans\n // out TRAIL_ENDS_AT for that seed so the block can pick the highest-value\n // terminal fact. Both reads are optional-results -- a graph with no\n // money-trail layer never fails the tool.\n const moneyTrailIncidentRows = optionalResultsFor(\n batch,\n 'money_trail_incident',\n partialQueryFailures\n )\n const preliminaryMoneyTrail = buildMoneyTrailBlock(moneyTrailIncidentRows, [])\n let moneyTrailEndRows: Array<Record<string, unknown>> = []\n if (preliminaryMoneyTrail?.primary_seed) {\n try {\n const endsBatch = await callGraphBatch(trackedClient, network, [\n { id: 'money_trail_ends', query: moneyTrailEndsQuery(preliminaryMoneyTrail.primary_seed) },\n ])\n moneyTrailEndRows = optionalResultsFor(endsBatch, 'money_trail_ends', partialQueryFailures)\n } catch (error) {\n // Degrade, don't fail: a transport/parse error on the second batch call\n // (unlike a query-level ok:false, which optionalResultsFor already\n // absorbs) must not blow up the whole tool -- the incident rows are\n // already in hand, so the block still reports on_trail without\n // nearest_trail_end.\n collectQueryFailure(\n partialQueryFailures,\n 'money_trail_ends',\n error instanceof Error ? error.message : String(error)\n )\n }\n }\n const moneyTrail = buildMoneyTrailBlock(moneyTrailIncidentRows, moneyTrailEndRows)\n const graphData = buildRiskGraph(address, profile, exchangeRows, network)\n const risk = riskAssessment(profile, labelRows, exchangeRows)\n const liveRiskScore = numberValue(profile['live_risk_score'])\n const liveRiskLevel = firstString(profile['live_risk_level'])\n const liveNodeVerdict =\n liveRiskScore !== undefined || liveRiskLevel\n ? {\n ...(liveRiskScore !== undefined ? { risk_score: liveRiskScore } : {}),\n ...(liveRiskLevel ? { risk_level: liveRiskLevel } : {}),\n source: 'topology_node',\n }\n : undefined\n\n const lines = [\n `Address risk for ${network}:${address}`,\n '',\n `Risk: ${risk['level']} (${formatRiskScore(risk['score'])})`,\n `Confidence: ${risk['confidence']}`,\n `Recommendation: ${risk['recommendation']}`,\n ...(liveNodeVerdict\n ? [`Live node triage: ${liveRiskLevel ?? 'unknown'} (${formatRiskScore(liveRiskScore)})`]\n : []),\n `Graph degree: in ${profile['degree_in'] ?? 'unknown'}, out ${profile['degree_out'] ?? 'unknown'}.`,\n '',\n 'Exchange behavior',\n ...(exchangeRows.length > 0\n ? [\n formatExchangeRows(exchangeRows).join('\\n'),\n ...(exchangeSearchComplete\n ? []\n : [\n `(incomplete: ${exchangeSearchFailures.length} other hop-depth quer${exchangeSearchFailures.length === 1 ? 'y' : 'ies'} failed -- there may be more exchange exposure than shown here)`,\n ]),\n ]\n : [\n exchangeSearchComplete\n ? '- No exchange inflow/outflow paths found in bounded search.'\n : `- Exchange search incomplete: ${exchangeSearchFailures.length} hop-depth quer${exchangeSearchFailures.length === 1 ? 'y' : 'ies'} failed before returning a result. This is NOT a clean finding -- retry or narrow the search (see Partial query failures below).`,\n ]),\n ]\n if (Array.isArray(risk['drivers']) && risk['drivers'].length > 0) {\n lines.push('', 'Risk drivers', risk['drivers'].map((driver) => `- ${driver}`).join('\\n'))\n }\n if (moneyTrail) {\n lines.push('', moneyTrailSummarySentence(moneyTrail))\n }\n if (compareAddress) {\n lines.push(\n '',\n `Connection compare target: ${compareAddress}`,\n connections.length > 0\n ? `Connection paths found: ${connections.length}`\n : 'Connection paths found: 0'\n )\n }\n if (compareUnresolved) {\n lines.push(\n '',\n `Unresolved compare_address: no Address found for \"${compareInput}\"; comparison skipped.`\n )\n }\n if (partialQueryFailures.length > 0) {\n lines.push(\n '',\n 'Partial query failures',\n partialQueryFailures.map((failure) => `- ${failure.id}: ${failure.error}`).join('\\n')\n )\n }\n const summaryText = lines.join('\\n')\n const structuredContent = {\n schema: 'chain-insights.result.v1',\n tool: 'aml_address_risk',\n facts: {\n subject: {\n network,\n addresses: compareAddress ? [address, compareAddress] : [address],\n },\n risk: {\n ...risk,\n ...(liveNodeVerdict ? { live_node: liveNodeVerdict } : {}),\n },\n exchange_behavior: {\n outflows,\n inflows,\n search_status: exchangeSearchComplete ? 'complete' : 'incomplete',\n ...(exchangeSearchComplete\n ? {}\n : { failed_query_ids: exchangeSearchFailures.map((failure) => failure.id) }),\n },\n connection: compareAddress\n ? {\n compare_address: compareAddress,\n paths: connections,\n ...(routeEvidence ? { route_evidence: routeEvidence } : {}),\n }\n : undefined,\n money_trail: moneyTrail,\n unresolved: compareUnresolved ? [compareInput] : undefined,\n partial_query_errors: partialQueryFailures.length > 0 ? partialQueryFailures : undefined,\n usage: usageBlock(usage),\n },\n }\n const artifacts = options.writeArtifacts\n ? await writeAddressRiskArtifacts(\n network,\n address,\n compareAddress,\n graphData,\n exchangeRows,\n summaryText\n )\n : statelessArtifacts()\n const evidence = artifactEvidence(artifacts)\n\n return {\n summaryText,\n structuredContent: {\n ...structuredContent,\n artifacts,\n evidence: [\n ...evidence,\n {\n evidence_type: 'tool_summary',\n summary: `aml_address_risk ${address} completed for ${network}`,\n },\n ],\n },\n graphData,\n }\n}\n\n/**\n * Routes the public AML tool contract to the requested implementation. An\n * omitted version always follows the latest supported contract.\n */\nexport async function runAmlAddressRisk(\n remoteClient: Client,\n options: AddressRiskOptions,\n requestedVersion?: string\n) {\n const version = resolveAmlAddressRiskVersion(requestedVersion)\n switch (version) {\n case 'v1': {\n const result = await addressRisk(remoteClient, options)\n return {\n ...result,\n structuredContent: {\n ...result.structuredContent,\n tool_version: version,\n },\n }\n }\n }\n}\n\nfunction toCsvValue(value: unknown): string {\n return value === undefined || value === null ? '' : String(value)\n}\n\nfunction subjectNodeForExchangeRow(row: Record<string, unknown>, fallbackAddress: string): string {\n return String(\n row['direction'] === 'inflow'\n ? (row['withdrawal_address'] ?? row['deposit_address'] ?? fallbackAddress)\n : (row['deposit_address'] ?? row['withdrawal_address'] ?? fallbackAddress)\n )\n}\n\nfunction buildAddressRiskTableHtml(\n tool: string,\n network: string,\n rows: Array<Record<string, unknown>>,\n subject: string\n): string {\n const headers = [\n 'direction',\n 'exchange_address',\n 'subject_path_node',\n 'hops',\n 'amount_usd_sum',\n 'tx_count',\n ] as const\n const body = rows\n .map((row) => {\n const exchangeAddress = String(row['exchange_address'] ?? '')\n const subjectNode = subjectNodeForExchangeRow(row, subject)\n const rowValues = [\n row['direction'] ?? '',\n exchangeAddress,\n subjectNode,\n row['hops'] ?? '',\n row['amount_usd_sum'] ?? '',\n row['tx_count'] ?? '',\n ]\n return `<tr>${rowValues.map((value) => `<td>${htmlEscape(toCsvValue(value))}</td>`).join('')}</tr>`\n })\n .join('\\n')\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${htmlEscape(tool)} Risk Table</title>\n<style>\n :root { color-scheme: dark; font-family: Inter, ui-sans-serif, system-ui; background: #0b0d12; color: #f4f2ea; }\n body { margin: 0; background: #0b0d12; color: #f4f2ea; }\n main { padding: 24px; }\n h1 { font-size: 20px; margin: 0 0 8px; font-weight: 650; }\n table { border-collapse: collapse; width: 100%; min-width: 900px; }\n th, td { border-bottom: 1px solid rgba(255,255,255,.08); padding: 8px 10px; text-align: left; }\n th { position: sticky; top: 0; background: #161a24; color: #f2dda6; font-weight: 600; }\n</style>\n</head>\n<body>\n<main>\n <h1>${htmlEscape(tool)} Table</h1>\n <div>Network: <strong>${htmlEscape(network)}</strong></div>\n <div>Generated: <strong>${htmlEscape(new Date().toISOString())}</strong></div>\n <table>\n <thead><tr>${headers.map((header) => `<th>${htmlEscape(header)}</th>`).join('')}</tr></thead>\n <tbody>${body}</tbody>\n </table>\n</main>\n</body>\n</html>\n`\n}\n\nasync function writeAddressRiskArtifacts(\n network: string,\n address: string,\n compareAddress: string | undefined,\n graphData: Record<string, unknown>,\n exchangeRows: Array<Record<string, unknown>>,\n summaryText: string\n): Promise<Record<string, string>> {\n const paths = workspaceOutputPaths()\n await Promise.all([\n mkdir(paths.reportsRoot, { recursive: true }),\n mkdir(paths.reportGraphsRoot, { recursive: true }),\n mkdir(paths.reportTablesRoot, { recursive: true }),\n ])\n const safeNetwork = network.replace(/[^A-Za-z0-9._-]+/g, '_')\n const safeAddress = address.replace(/[^A-Za-z0-9._-]+/g, '_')\n const slug = `${new Date()\n .toISOString()\n .replace(/[-:]/g, '')\n .replace(/\\.\\d{3}Z$/, 'Z')}_aml_address_risk_${safeNetwork}_${safeAddress}`\n const graphPath = path.join(paths.reportGraphsRoot, `${slug}.graph.json`)\n const tableJsonPath = path.join(paths.reportTablesRoot, `${slug}.compact-evidence.json`)\n const csvPath = path.join(paths.reportTablesRoot, `${slug}.flows.csv`)\n const tableHtmlPath = path.join(paths.reportsRoot, `${slug}.table.html`)\n const reportPath = path.join(paths.reportsRoot, `${slug}.aml-address-report.md`)\n const header = [\n 'direction',\n 'exchange_address',\n 'subject_path_node',\n 'hops',\n 'amount_usd_sum',\n 'tx_count',\n ]\n const csv =\n [\n header.join(','),\n ...exchangeRows.map((row) => {\n const exchangeAddress = String(row['exchange_address'] ?? '')\n const subjectPathNode = subjectNodeForExchangeRow(row, address)\n return [\n row['direction'] ?? '',\n exchangeAddress,\n subjectPathNode,\n row['hops'] ?? '',\n row['amount_usd_sum'] ?? '',\n row['tx_count'] ?? '',\n ]\n .map((value) => JSON.stringify(String(value)))\n .join(',')\n }),\n ].join('\\n') + '\\n'\n const evidence = {\n schema: 'chain-insights.trace.v1',\n tool: 'aml_address_risk',\n network,\n input: {\n address,\n ...(compareAddress ? { compare_address: compareAddress } : {}),\n },\n profile: {\n exchange_rows: exchangeRows.map((row) => ({\n direction: row['direction'],\n exchange_address: row['exchange_address'],\n subject_node: subjectNodeForExchangeRow(row, address),\n hops: row['hops'],\n amount_usd_sum: row['amount_usd_sum'],\n tx_count: row['tx_count'],\n })),\n report_summary: summaryText,\n },\n }\n await writeFile(graphPath, JSON.stringify(graphData, null, 2) + '\\n', { mode: 0o600 })\n await writeFile(tableJsonPath, JSON.stringify(evidence, null, 2) + '\\n', { mode: 0o600 })\n await writeFile(csvPath, csv, { mode: 0o600 })\n await writeFile(\n tableHtmlPath,\n buildAddressRiskTableHtml('aml_address_risk', network, exchangeRows, address),\n { mode: 0o600 }\n )\n await writeFile(\n reportPath,\n [\n `# Address Risk Report (${network}:${address})`,\n `- Graph JSON: ${graphPath}`,\n `- Table JSON: ${tableJsonPath}`,\n `- CSV: ${csvPath}`,\n `- Report HTML: ${tableHtmlPath}`,\n '',\n summaryText,\n ].join('\\n'),\n { mode: 0o600 }\n )\n\n return {\n graph_json: graphPath,\n table_json: tableJsonPath,\n flows_csv: csvPath,\n table_html: tableHtmlPath,\n report_md: reportPath,\n }\n}\n\nfunction statelessArtifacts(): Record<string, unknown> {\n return {\n artifacts_written: false,\n artifact_mode: 'stateless',\n }\n}\n\nfunction artifactEvidence(artifacts: Record<string, unknown>): Array<Record<string, unknown>> {\n return Object.entries(artifacts)\n .filter(\n (entry): entry is [string, string] =>\n entry[0] !== 'artifact_mode' && typeof entry[1] === 'string' && entry[1].length > 0\n )\n .map(([kind, filePath]) => ({\n evidence_type: 'artifact_pointer',\n path: filePath,\n summary: `${kind} artifact`,\n }))\n}\n\nfunction htmlEscape(value: unknown): string {\n return String(value ?? '')\n .replaceAll('&', '&')\n .replaceAll('<', '<')\n .replaceAll('>', '>')\n .replaceAll('\"', '"')\n .replaceAll(\"'\", ''')\n}\n\n// Deterministic query-builder surface for the committed corpus and\n// query-with-a-documented-call-contract tests. Reflects the retained\n// aml_address_risk/graph query builders after the aml_trace_* cut.\n\n// pairAnchorQuery resolves a transaction id of a pair through the facts lane\n// (openspec dozerdb-flows-to-slim-schema: the topology edge carries no tx\n// anchors). A facts read names an address pair with one day, or one\n// transaction hash, and takes no ORDER BY, so the read names the UTC day (take\n// it from the link's first_seen_timestamp or last_seen_timestamp) and returns\n// one transfer of the pair on that day. Bounded: LIMIT 1 on the pair and the\n// day. TRANSFER lists every transfer the link counts, internal native transfers\n// included (kind internal), so the anchor query finds a row for a pair that only\n// internal transfers move.\nexport function pairAnchorQuery(from: string, to: string, day: string): string {\n return [\n 'USE facts',\n `MATCH (a:Address {address: \"${escapeCypherString(from)}\"})-[t:TRANSFER]->(b:Address {address: \"${escapeCypherString(to)}\"})`,\n `WHERE t.block_date = \"${escapeCypherString(day)}\"`,\n 'RETURN t.tx_id AS tx_id, t.block_timestamp AS block_timestamp',\n 'LIMIT 1',\n ].join(' ')\n}\n\n// inlineAverageFlowQuery is the documented recipe for the retired\n// avg_tx_size_usd edge property: compute the average at read time from the\n// two fields the slim edge carries.\nexport function inlineAverageFlowQuery(address: string, limit = 25): { query: string } {\n return {\n query: [\n `MATCH (a:Address {address: \"${escapeCypherString(address)}\"})-[r:FLOWS_TO]->(b:Address)`,\n 'RETURN b.address AS neighbor, r.amount_usd_sum AS amount_usd_sum, r.tx_count AS tx_count,',\n ' r.amount_usd_sum / toFloat(r.tx_count) AS avg_tx_size_usd',\n `ORDER BY r.amount_usd_sum DESC LIMIT ${limit}`,\n ].join(' '),\n }\n}\n\nexport const queryBuilderContract = {\n topologyGraphQuery,\n pairAnchorQuery,\n inlineAverageFlowQuery,\n addressProfileQuery,\n compareAddressExistsQuery,\n addressFeatureQuery,\n exchangeOutflowQueries,\n exchangeInflowQueries,\n connectionProbeQuery,\n connectionRouteQueries,\n linkedExposureQueries,\n crossSpaceLinkedQuery,\n}\n"],"mappings":";;;;;AAAA,MAAM,oCAAoB,IAAI,IAAI;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,kCAAkB,IAAI,IAAI;CAAC;CAAY;CAAY;CAAe;AAAc,CAAC;AAavF,SAASA,WAAS,OAAsC;CACtD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,YAAY,OAA0B;CAC7C,OAAO,MAAM,QAAQ,KAAK,IAAI,MAAM,IAAI,MAAM,CAAC,CAAC,OAAO,OAAO,IAAI,CAAC;AACrE;AAEA,SAAS,OAAO,QAA4B;CAC1C,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;AAC5B;AAEA,SAAS,WAAW,OAAuB;CACzC,OAAO,MACJ,KAAK,CAAC,CACN,QAAQ,sBAAsB,OAAO,CAAC,CACtC,QAAQ,kBAAkB,GAAG,CAAC,CAC9B,QAAQ,YAAY,EAAE,CAAC,CACvB,YAAY;AACjB;AAEA,SAAS,iBAAiB,OAAwB;CAChD,OAAO,kBAAkB,IAAI,KAAK;AACpC;AAEA,SAAS,cAAc,MAA6B;CAClD,OAAO,OAAO,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,QAAQ,UAAU,CAAC,iBAAiB,KAAK,CAAC;AACvF;AAEA,SAAS,aAAa,MAA6B;CACjD,OAAO,OAAO;EACZ,GAAG,YAAY,KAAK,gBAAgB;EACpC,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