Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(agent-vitals): read an autonomous agent's pulse instead of guessing at it

nirholas63edc526b13b
diff --git a/api/_lib/agent-vitals/sniper-chart.js b/api/_lib/agent-vitals/sniper-chart.js
new file mode 100644
index 000000000..ee7439ffe
--- /dev/null
+++ b/api/_lib/agent-vitals/sniper-chart.js
@@ -0,0 +1,279 @@
+// @ts-check
+/**
+ * The three.ws sniper fleet expressed as an @three-ws/agent-vitals chart.
+ *
+ * This is the concrete answer to "why is this armed bot not trading", built
+ * from the failure that motivated the whole library. On 2026-08-28 ten of
+ * twelve armed arms had not attempted an entry in weeks while the worker
+ * reported Ready:True with minScale 1, the launch feed was flowing, and every
+ * strategy row said enabled = true. Three independent causes were stacked:
+ *
+ * - the deployed worker image predated the commit that moved every free LLM
+ * rung onto models that still exist, so the whole chain answered 404/410;
+ * - the model providers behind the surviving rungs were out of credit (402)
+ * or on a billing hold (403);
+ * - several arm wallets could not fund a single entry.
+ *
+ * Every one of those was individually invisible, and a flat checklist would
+ * have shown three red rows without saying which to chase. The `needs` edges
+ * below encode the real causality: for an arm that needs a model, cognition
+ * cannot be judged while the image is stale, and an entry cannot be judged
+ * while cognition is down. Attesting this chart returns the deepest cause and
+ * the command that fixes it.
+ *
+ * Every probe reads a real system: the strategies table, the position ledger,
+ * a Solana RPC, the live launch feed, the deployed image digest. Nothing here
+ * is sampled, cached or simulated.
+ *
+ * @example
+ * import { sniperChart } from './api/_lib/agent-vitals/sniper-chart.js';
+ * const verdict = await sniperChart({ strategy, balanceSol }).attest();
+ * verdict.can.enter; // false
+ * verdict.explain(); // 'cannot enter because cognition is blocked, because ...'
+ */
+
+import { vitals } from '../../../packages/agent-vitals/src/index.js';
+import { walletTradeState } from '../sniper-solvency.js';
+import { fundTargetSol } from '../agent-funding-policy.js';
+
+/** How long an armed arm may go without ATTEMPTING an entry before it is stalled. */
+export const STALE_ENTRY_MS = 7 * 24 * 60 * 60 * 1000;
+
+/**
+ * How stale the launch feed may be before an arm has nothing to look at. The
+ * pump.fun feed produces candidates continuously, so a gap this long is an
+ * upstream outage, not a quiet market.
+ */
+export const STALE_FEED_MS = 30 * 60 * 1000;
+
+/** A worker image older than this is a deploy-drift suspect, not a fresh rollout. */
+export const STALE_IMAGE_MS = 7 * 24 * 60 * 60 * 1000;
+
+const SUBMIT_WORKER =
+ 'gcloud builds submit --config workers/agent-sniper/cloudbuild.yaml --region us-central1 ' +
+ '--project aerial-vehicle-466722-p5 --substitutions=SHORT_SHA=manual$(date +%s)';
+
+const humanAge = (ms) => {
+ if (!Number.isFinite(ms) || ms < 0) return 'unknown age';
+ const days = Math.floor(ms / 86_400_000);
+ if (days >= 1) return `${days} day${days === 1 ? '' : 's'}`;
+ const hours = Math.floor(ms / 3_600_000);
+ if (hours >= 1) return `${hours} hour${hours === 1 ? '' : 's'}`;
+ return `${Math.max(1, Math.floor(ms / 60_000))} min`;
+};
+
+/**
+ * @typedef {object} SniperArmInput
+ * @property {object} strategy a row from agent_sniper_strategies
+ * @property {number|null} [balanceSol] live wallet balance; null when unread
+ * @property {string|null} [wallet] the arm's trading wallet address
+ * @property {Date|string|null} [lastEntryAt] most recent entry ATTEMPT
+ * @property {Date|string|null} [feedFreshAt] most recent launch seen by the feed
+ * @property {Date|string|null} [imageBuiltAt] build time of the running worker image
+ * @property {{ ok: boolean|null, detail?: string }} [cognition] model-chain reachability
+ * @property {{ ok: boolean|null, detail?: string }} [rpc] RPC reachability
+ */
+
+const asTime = (v) => {
+ if (!v) return null;
+ const t = v instanceof Date ? v.getTime() : Date.parse(String(v));
+ return Number.isFinite(t) ? t : null;
+};
+
+/**
+ * Build the vitals chart for one sniper arm.
+ *
+ * Readings are injected rather than fetched here so the chart stays pure and
+ * a caller sweeping a whole fleet pays for one RPC round and one feed read
+ * instead of one per arm. `api/_lib/agent-vitals/sniper-probe.js` does that
+ * gathering against the live systems.
+ *
+ * @param {SniperArmInput} input
+ * @param {{ now?: number }} [opts]
+ * @returns {import('../../../packages/agent-vitals/src/index.js').VitalsChart}
+ */
+export function sniperChart(input, opts = {}) {
+ const now = opts.now ?? Date.now();
+ const s = input.strategy || {};
+ const perTradeSol = Number(s.per_trade_lamports || 0) / 1e9;
+ const label = s.label || s.agent_name || s.agent_id || 'arm';
+
+ const chart = vitals({ agent: String(label), timeoutMs: 8_000 });
+
+ // ── Layer 0: the deployment itself ───────────────────────────────────────
+ // First because it CAUSES the failures below it. An image that predates the
+ // fix for a dead dependency will keep reproducing that dependency's failure
+ // forever, and probing the dependency only rediscovers a known answer.
+ chart.vital('deploy-fresh', {
+ describe: 'the running worker image is recent enough to contain current config',
+ remedy: SUBMIT_WORKER,
+ probe: () => {
+ const built = asTime(input.imageBuiltAt);
+ if (built === null) return { ok: null, detail: 'image build time unread' };
+ const age = now - built;
+ return {
+ ok: age <= STALE_IMAGE_MS,
+ detail: `worker image is ${humanAge(age)} old`,
+ data: { ageMs: age, builtAt: new Date(built).toISOString() },
+ };
+ },
+ });
+
+ // ── Layer 0: permission ──────────────────────────────────────────────────
+ // Deliberately independent of the deployment: an owner who disarmed an arm
+ // gets "off by choice", never a stack of infrastructure noise.
+ chart.vital('armed', {
+ describe: 'the owner has this arm enabled and not killed',
+ remedy: 'enable the strategy (or clear its kill switch) from the agent page',
+ probe: () => {
+ if (s.kill_switch) return { ok: false, detail: 'kill switch engaged on the strategy' };
+ if (!s.enabled) return { ok: false, detail: 'strategy is disabled' };
+ return { ok: true };
+ },
+ });
+
+ // ── Layer 0: money ───────────────────────────────────────────────────────
+ // Asked of walletTradeState(), which calls the executor's own resolveEntrySize().
+ // Re-deriving the threshold here is exactly how a report drifts into calling a
+ // wallet tradeable that the executor sits out.
+ chart.vital('solvency', {
+ describe: 'the wallet can fund at least one entry at the executor\'s own sizing rule',
+ remedy: ({ data }) => {
+ const deficit = Number(data && typeof data === 'object' ? data.deficitSol : 0);
+ const target = input.wallet || 'the arm wallet';
+ return deficit > 0
+ ? `send ${deficit.toFixed(4)} SOL to ${target} (or let the auto-funder refill it)`
+ : `fund ${target}`;
+ },
+ probe: () => {
+ if (input.balanceSol == null || !Number.isFinite(Number(input.balanceSol))) {
+ // An unread balance is not a balance of zero. Reporting it as down
+ // would page an operator to a healthy fleet on one RPC blip.
+ return { ok: null, detail: 'wallet balance unread' };
+ }
+ const balanceSol = Number(input.balanceSol);
+ const state = walletTradeState(balanceSol, perTradeSol);
+ const deficitSol = state === 'starved' ? Math.max(0, fundTargetSol({ perTradeSol }) - balanceSol) : 0;
+ return {
+ // 'shrunk' still trades, just below the configured size. Calling that
+ // a failure would mark a working arm dead.
+ ok: state !== 'starved',
+ detail: `${balanceSol.toFixed(6)} SOL against a ${perTradeSol} SOL entry (${state})`,
+ data: { state, balanceSol, perTradeSol, deficitSol },
+ };
+ },
+ });
+
+ // ── Layer 0: the outside world ───────────────────────────────────────────
+ chart.vital('rpc', {
+ describe: 'a Solana RPC is answering, so a quote and a broadcast are possible',
+ remedy: 'check SOLANA_RPC_URL and the provider status; see docs/ops/solana-rpc-lanes.md',
+ probe: () => input.rpc ?? { ok: null, detail: 'RPC not probed' },
+ });
+
+ chart.vital('feed', {
+ describe: 'the launch feed is producing candidates to evaluate',
+ remedy: 'check /api/cron/pumpfun-monitor and the upstream pump.fun feed',
+ probe: () => {
+ const fresh = asTime(input.feedFreshAt);
+ if (fresh === null) return { ok: null, detail: 'feed freshness unread' };
+ const age = now - fresh;
+ return { ok: age <= STALE_FEED_MS, detail: `newest launch seen ${humanAge(age)} ago`, data: { ageMs: age } };
+ },
+ });
+
+ // ── Layer 1: thinking, which a stale image can break ─────────────────────
+ // The deploy-fresh edge exists ONLY for an arm that actually needs a model.
+ // A stale image is a hypothesis about why a model chain died, not by itself a
+ // reason an agent cannot act, and wiring it as a universal precondition said
+ // so: it reported an arm that had entered a position two minutes earlier, on
+ // that very image, as definitively unable. Live evidence beats a proxy every
+ // time, so the proxy only applies where it can actually bite.
+ const needsModel = s.decision_mode === 'llm';
+ chart.vital('cognition', {
+ describe: needsModel
+ ? 'the arm can reach a model and get a buy/skip decision'
+ : 'this arm decides by rules and needs no model',
+ needs: needsModel ? ['deploy-fresh'] : [],
+ remedy: 'restore a working rung in api/_lib/llm.js: top up provider credits or clear the GCP billing hold',
+ probe: () => {
+ if (!needsModel) return { ok: true, detail: 'rules arm: no model required' };
+ return input.cognition ?? { ok: null, detail: 'model chain not probed' };
+ },
+ });
+
+ // ── Layer 2: the capabilities ────────────────────────────────────────────
+ chart.capability('enter', {
+ describe: 'open a new position if a qualifying launch appeared right now',
+ needs: ['armed', 'solvency', 'rpc', 'feed', 'cognition'],
+ });
+
+ // Exiting deliberately needs neither the feed nor a model. A fleet that can
+ // still close its open risk is not fully dead, and collapsing that distinction
+ // is how an operator concludes the positions are stranded when they are not.
+ chart.capability('exit', {
+ describe: 'close an open position (needs no model and no launch feed)',
+ needs: ['rpc'],
+ });
+
+ return chart;
+}
+
+/**
+ * How recently an entry attempt still counts as proof the arm could act. Short
+ * on purpose: it is evidence about the state of the world at that moment, and
+ * the world moves.
+ */
+export const OBSERVED_ACTING_MS = 60 * 60 * 1000;
+
+/**
+ * Does the attestation contradict what the arm was observed doing?
+ *
+ * A capability model is a model, and models are wrong. This one was: an early
+ * revision made every arm depend on deployment freshness, and confidently
+ * reported an arm as unable to act while that arm was opening positions every
+ * few minutes on the very image being complained about.
+ *
+ * A health tool that cannot notice it is wrong will be trusted right up until
+ * it matters. So the ledger gets a vote: if the graph says `unable` and the arm
+ * demonstrably acted inside the observation window, the graph is wrong and says
+ * so, loudly, instead of quietly winning the argument against reality.
+ *
+ * @param {'ready'|'unable'|'unknown'|boolean|null} verdictStatus can.enter, or a capability status
+ * @param {Date|string|null|undefined} lastEntryAt
+ * @param {{ now?: number }} [opts]
+ * @returns {string|null} the contradiction, or null when the model and the ledger agree
+ */
+export function contradiction(verdictStatus, lastEntryAt, opts = {}) {
+ const unable = verdictStatus === false || verdictStatus === 'unable';
+ if (!unable) return null;
+ const now = opts.now ?? Date.now();
+ const last = asTime(lastEntryAt);
+ if (last === null) return null;
+ const ageMs = now - last;
+ if (ageMs > OBSERVED_ACTING_MS) return null;
+ return `attested UNABLE but this arm attempted an entry ${humanAge(ageMs)} ago: ` +
+ 'the vitals model is wrong, not the arm';
+}
+
+/**
+ * Was this arm attempting entries recently? Kept beside the chart rather than
+ * inside it because it is evidence, not a precondition: an arm can be perfectly
+ * capable and simply have found nothing it liked. A stalled arm whose vitals are
+ * all `up` is the interesting case, and it means the filters are the answer.
+ *
+ * @param {Date|string|null|undefined} lastEntryAt
+ * @param {{ now?: number }} [opts]
+ * @returns {{ stalled: boolean, ageMs: number|null, detail: string }}
+ */
+export function entryActivity(lastEntryAt, opts = {}) {
+ const now = opts.now ?? Date.now();
+ const last = asTime(lastEntryAt);
+ if (last === null) return { stalled: true, ageMs: null, detail: 'never attempted an entry' };
+ const ageMs = now - last;
+ return {
+ stalled: ageMs > STALE_ENTRY_MS,
+ ageMs,
+ detail: `last entry attempt ${humanAge(ageMs)} ago`,
+ };
+}
diff --git a/api/_lib/agent-vitals/sniper-probe.js b/api/_lib/agent-vitals/sniper-probe.js
new file mode 100644
index 000000000..ba1dac05d
--- /dev/null
+++ b/api/_lib/agent-vitals/sniper-probe.js
@@ -0,0 +1,375 @@
+// @ts-check
+/**
+ * Live readings for the sniper vitals chart.
+ *
+ * Everything here talks to a real system: the strategies table, the position
+ * ledger, a Solana RPC, the launch feed, the model chain, and the deployed
+ * worker image. Nothing is sampled or simulated.
+ *
+ * The gathering is fleet-wide on purpose. The readings that cost something
+ * (feed freshness, model-chain reachability, RPC liveness, image age) are
+ * identical for every arm on a network, so they are taken ONCE and shared. Only
+ * the per-arm wallet balance is read per arm, and those go out concurrently.
+ * Attesting twelve arms therefore costs one feed read, one model probe and one
+ * image read, not twelve of each: the difference between a report an operator
+ * runs casually and one they avoid.
+ */
+
+import { sql } from '../db.js';
+import { solanaConnection } from '../agent-pumpfun.js';
+import { recentPumpLaunches } from '../pump-launch-feed.js';
+import { providerChain, llmComplete } from '../llm.js';
+import { getGcpAccessToken, gcpAuthConfigured } from '../gcp-auth.js';
+import { sniperChart, entryActivity, contradiction } from './sniper-chart.js';
+
+/** Cloud Run service that executes every sniper arm. */
+export const SNIPER_SERVICE = 'agent-sniper';
+
+const asIso = (v) => (v ? new Date(v).toISOString() : null);
+
+/**
+ * Is a model chain actually reachable? Sends the smallest possible completion
+ * through the real provider chain and reports which rung answered.
+ *
+ * This is the probe that would have caught the outage directly: the chain was
+ * configured, keyed, and answering 404/402/403 on every rung while the worker
+ * logged a cheerful "chain exhausted" and carried on.
+ *
+ * @param {{ timeoutMs?: number }} [opts]
+ * @returns {Promise<{ ok: boolean|null, detail: string }>}
+ */
+export async function probeCognition(opts = {}) {
+ const timeoutMs = opts.timeoutMs ?? 15_000;
+ let chain;
+ try {
+ chain = providerChain({});
+ } catch (err) {
+ return { ok: null, detail: `provider chain would not build: ${err?.message || 'error'}` };
+ }
+ if (!Array.isArray(chain) || chain.length === 0) {
+ return { ok: false, detail: 'no model providers are configured' };
+ }
+
+ try {
+ const answer = await llmComplete({
+ system: 'Reply with the single word OK.',
+ user: 'ping',
+ maxTokens: 8,
+ timeoutMs,
+ });
+ const who = answer?.provider || answer?.model || 'a provider';
+ return { ok: true, detail: `${who} answered across ${chain.length} configured rung(s)` };
+ } catch (err) {
+ const message = String(err?.message || 'error').slice(0, 200);
+ // Exhaustion is the definitive case and it does NOT arrive as a named
+ // error: llmComplete rethrows the LAST provider's own error (an HTTP 401
+ // from one rung, say) with the full `attempts` array attached. Matching on
+ // the error type alone read a total chain outage as merely unreadable,
+ // which is the difference between "your agents cannot think" and "we could
+ // not check". The attempts array is the real signal.
+ const attempts = Array.isArray(err?.attempts) ? err.attempts : [];
+ if (attempts.length) {
+ const tried = attempts.map((a) => `${a.provider}=${a.skipped || a.error}`).join(' | ');
+ return {
+ ok: false,
+ detail: `every rung failed (${attempts.length} tried): ${tried}`.slice(0, 400),
+ };
+ }
+ if (err?.name === 'LlmUnavailableError') {
+ return { ok: false, detail: 'no model provider is reachable' };
+ }
+ return { ok: null, detail: `model probe inconclusive: ${message}` };
+ }
+}
+
+/**
+ * Is a Solana RPC answering? Reads the current slot, the cheapest call that
+ * proves the endpoint is both reachable and synced enough to quote against.
+ *
+ * @param {string} network
+ * @returns {Promise<{ ok: boolean|null, detail: string }>}
+ */
+export async function probeRpc(network = 'mainnet') {
+ try {
+ const slot = await solanaConnection(network).getSlot('confirmed');
+ return Number.isFinite(slot) && slot > 0
+ ? { ok: true, detail: `slot ${slot}` }
+ : { ok: false, detail: 'RPC returned no slot' };
+ } catch (err) {
+ // Unreachable is genuinely undecidable from here: the endpoint may be fine
+ // and this machine's egress may not be.
+ return { ok: null, detail: `RPC unreachable: ${String(err?.message || 'error').slice(0, 120)}` };
+ }
+}
+
+/**
+ * When did the launch feed last produce a candidate? Read from the live feed
+ * rather than a cursor table so a stalled ingest cannot look fresh.
+ *
+ * @param {string} network
+ * @returns {Promise<string|null>}
+ */
+export async function probeFeedFreshness(network = 'mainnet') {
+ // The feed quotes created_at as a NUMERIC epoch in ms. Date.parse() on a
+ // number stringifies it first and returns NaN, which silently reported a
+ // perfectly live feed as unread.
+ const asEpoch = (v) => {
+ if (typeof v === 'number') return Number.isFinite(v) ? v : null;
+ if (typeof v === 'string' && v) {
+ const parsed = Date.parse(v);
+ return Number.isFinite(parsed) ? parsed : null;
+ }
+ return null;
+ };
+ try {
+ const launches = await recentPumpLaunches({ network, limit: 10 });
+ let newest = 0;
+ for (const launch of launches || []) {
+ const t = asEpoch(launch?.created_at ?? launch?.createdAt ?? launch?.timestamp);
+ if (t !== null && t > newest) newest = t;
+ }
+ return newest ? new Date(newest).toISOString() : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Build time of the image the worker is actually running.
+ *
+ * This is the reading nothing else on the platform takes, and it is the one
+ * that closed the case: the code fix was seventeen days old in git and sixteen
+ * days newer than the running image. Uptime, readiness and revision checks all
+ * reported green because the container was, in fact, running perfectly. It was
+ * running the wrong code.
+ *
+ * Uses the Artifact Registry REST API through the repo's own token helper
+ * (api/_lib/gcp-auth.js), which mints from the metadata server or a service
+ * account without pulling in google-auth-library. No credential returns null
+ * (unread), never a false verdict.
+ *
+ * @param {{ project?: string, location?: string, repository?: string, image?: string }} [opts]
+ * @returns {Promise<string|null>}
+ */
+export async function probeDeployedImageAge(opts = {}) {
+ const project = opts.project || process.env.GOOGLE_CLOUD_PROJECT || 'aerial-vehicle-466722-p5';
+ const location = opts.location || 'us-central1';
+ const repository = opts.repository || 'workers';
+ const image = opts.image || SNIPER_SERVICE;
+
+ if (!gcpAuthConfigured()) return null;
+ let token = null;
+ try {
+ token = await getGcpAccessToken();
+ } catch {
+ return null;
+ }
+ if (!token) return null;
+
+ try {
+ const url = `https://artifactregistry.googleapis.com/v1/projects/${project}/locations/${location}` +
+ `/repositories/${repository}/packages/${image}/versions?orderBy=createTime%20desc&pageSize=1`;
+ const res = await fetch(url, {
+ headers: { authorization: `Bearer ${token}` },
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (!res.ok) return null;
+ const body = await res.json();
+ return body?.versions?.[0]?.createTime || null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Every armed arm on a network, with the per-arm ledger facts the chart needs.
+ * @param {string} network
+ * @returns {Promise<object[]>}
+ */
+export async function loadArms(network = 'mainnet') {
+ return sql`
+ SELECT s.*, i.name AS agent_name,
+ (SELECT max(p.opened_at) FROM agent_sniper_positions p WHERE p.strategy_id = s.id) AS last_entry_at,
+ (SELECT p.wallet FROM agent_sniper_positions p
+ WHERE p.strategy_id = s.id AND p.wallet IS NOT NULL AND p.wallet <> 'pending'
+ ORDER BY p.opened_at DESC LIMIT 1) AS wallet
+ FROM agent_sniper_strategies s
+ LEFT JOIN agent_identities i ON i.id = s.agent_id
+ WHERE s.network = ${network} AND s.enabled = true
+ ORDER BY i.name NULLS LAST`;
+}
+
+/**
+ * Live SOL balances for a set of addresses, concurrently. An address that
+ * cannot be read maps to null so the solvency probe reports `unknown` instead
+ * of inventing a zero.
+ *
+ * @param {string[]} addresses
+ * @param {string} network
+ * @returns {Promise<Map<string, number|null>>}
+ */
+export async function loadBalances(addresses, network = 'mainnet') {
+ const unique = [...new Set(addresses.filter(Boolean))];
+ /** @type {Map<string, number|null>} */
+ const out = new Map();
+ if (!unique.length) return out;
+
+ const connection = solanaConnection(network);
+ const { PublicKey } = await import('@solana/web3.js');
+ await Promise.all(unique.map(async (address) => {
+ try {
+ const lamports = await connection.getBalance(new PublicKey(address), 'confirmed');
+ out.set(address, lamports / 1e9);
+ } catch {
+ out.set(address, null);
+ }
+ }));
+ return out;
+}
+
+/**
+ * @typedef {object} ArmAttestation
+ * @property {string} agentId
+ * @property {string} name
+ * @property {string|null} label
+ * @property {string|null} wallet
+ * @property {boolean} stalled
+ * @property {string} activity
+ * @property {string|null} contradiction set when the ledger disproves the verdict
+ * @property {import('../../../packages/agent-vitals/src/index.js').Verdict} verdict
+ */
+
+/**
+ * Attest every armed arm on a network against live systems.
+ *
+ * `imageBuiltAt` may be supplied by the caller. The in-process probe reads
+ * Artifact Registry over HTTP with a platform credential, which a developer
+ * machine authenticated only through the gcloud CLI does not have; an operator
+ * tool can read it from gcloud and pass it in rather than lose the reading that
+ * matters most.
+ *
+ * @param {{ network?: string, now?: number, includeCognition?: boolean,
+ * includeImage?: boolean, imageBuiltAt?: string|null }} [opts]
+ * @returns {Promise<{ network: string, at: string, shared: object, arms: ArmAttestation[] }>}
+ */
+export async function attestFleet(opts = {}) {
+ const network = opts.network || 'mainnet';
+ const now = opts.now ?? Date.now();
+
+ const arms = await loadArms(network);
+ const balances = await loadBalances(arms.map((a) => a.wallet), network);
+
+ // The shared readings: taken once for the whole fleet, in parallel.
+ const [rpc, feedFreshAt, cognition, imageBuiltAt] = await Promise.all([
+ probeRpc(network),
+ probeFeedFreshness(network),
+ opts.includeCognition === false
+ ? Promise.resolve({ ok: null, detail: 'model probe skipped' })
+ : probeCognition(),
+ opts.imageBuiltAt !== undefined
+ ? Promise.resolve(opts.imageBuiltAt)
+ : opts.includeImage === false ? Promise.resolve(null) : probeDeployedImageAge(),
+ ]);
+
+ const attestations = await Promise.all(arms.map(async (strategy) => {
+ const wallet = strategy.wallet || null;
+ const activity = entryActivity(strategy.last_entry_at, { now });
+ const verdict = await sniperChart({
+ strategy,
+ wallet,
+ balanceSol: wallet ? balances.get(wallet) ?? null : null,
+ lastEntryAt: strategy.last_entry_at,
+ feedFreshAt,
+ imageBuiltAt,
+ cognition,
+ rpc,
+ }, { now }).attest();
+
+ return {
+ agentId: strategy.agent_id,
+ name: strategy.agent_name || strategy.agent_id,
+ label: strategy.label || null,
+ wallet,
+ stalled: activity.stalled,
+ activity: activity.detail,
+ contradiction: contradiction(verdict.can.enter, strategy.last_entry_at, { now }),
+ verdict,
+ };
+ }));
+
+ return {
+ network,
+ at: new Date(now).toISOString(),
+ shared: {
+ rpc,
+ cognition,
+ feed_fresh_at: asIso(feedFreshAt),
+ image_built_at: asIso(imageBuiltAt),
+ },
+ arms: attestations,
+ };
+}
+
+/**
+ * The fleet's headline: how many arms can act, and the deduplicated work queue
+ * of root causes across all of them. One stale deployment blocking twelve arms
+ * is one item here, not twelve.
+ *
+ * @param {ArmAttestation[]} arms
+ * A cause keeps every affected arm and every DISTINCT remedy, because a shared
+ * cause does not imply a shared fix: one stale image is one redeploy, but five
+ * starved wallets are five different transfers to five different addresses.
+ * Collapsing those to a single representative remedy prints one arm's wallet as
+ * the fix for the other four.
+ *
+ * @returns {{ total: number, ready: number, unable: number, unknown: number,
+ * canExit: number, stalledButCapable: string[], contradictions: string[],
+ * rootCauses: Array<{ id: string, arms: string[], remedies: string[], details: string[] }> }}
+ */
+export function summarizeFleet(arms) {
+ let ready = 0;
+ let unable = 0;
+ let unknown = 0;
+ let canExit = 0;
+ /** @type {string[]} */
+ const stalledButCapable = [];
+ /** @type {string[]} */
+ const contradictions = [];
+ /** @type {Map<string, { id: string, arms: string[], remedies: string[], details: string[] }>} */
+ const causes = new Map();
+
+ for (const arm of arms) {
+ const enter = arm.verdict.can.enter;
+ if (enter === true) ready += 1;
+ else if (enter === false) unable += 1;
+ else unknown += 1;
+ if (arm.verdict.can.exit === true) canExit += 1;
+
+ // An arm that is fully capable and still silent is the genuinely
+ // interesting case: nothing is broken, so its entry filters are the answer.
+ if (enter === true && arm.stalled) stalledButCapable.push(arm.name);
+ if (arm.contradiction) contradictions.push(`${arm.name}: ${arm.contradiction}`);
+
+ for (const root of arm.verdict.rootCauses) {
+ let cause = causes.get(root.id);
+ if (!cause) {
+ cause = { id: root.id, arms: [], remedies: [], details: [] };
+ causes.set(root.id, cause);
+ }
+ cause.arms.push(arm.name);
+ if (root.remedy && !cause.remedies.includes(root.remedy)) cause.remedies.push(root.remedy);
+ if (root.detail && !cause.details.includes(root.detail)) cause.details.push(root.detail);
+ }
+ }
+
+ return {
+ total: arms.length,
+ ready,
+ unable,
+ unknown,
+ canExit,
+ stalledButCapable,
+ contradictions,
+ rootCauses: [...causes.values()].sort((a, b) => b.arms.length - a.arms.length || a.id.localeCompare(b.id)),
+ };
+}
diff --git a/packages/agent-vitals/LICENSE b/packages/agent-vitals/LICENSE
new file mode 100644
index 000000000..dff21b7f4
--- /dev/null
+++ b/packages/agent-vitals/LICENSE
@@ -0,0 +1,20 @@
+Copyright 2026 nirholas
+
+All rights reserved.
+
+This software is proprietary and may not be used, copied, modified, distributed,
+translated, or made available to any third party without the express written
+permission of the copyright owner.
+
+No rights are granted by implication, estoppel, or otherwise. Use of this
+software is subject to the terms of a separate license agreement with the
+copyright owner.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.
+
+IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE FOR ANY CLAIM, DAMAGES, OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE,
+ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/packages/agent-vitals/README.md b/packages/agent-vitals/README.md
new file mode 100644
index 000000000..fa352f26e
--- /dev/null
+++ b/packages/agent-vitals/README.md
@@ -0,0 +1,244 @@
+<p align="center">
+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" width="72" height="72" alt="three.ws" /></a>
+</p>
+
+<h1 align="center">@three-ws/agent-vitals</h1>
+
+<p align="center"><strong>Your agent says it is healthy. It has not done anything in three weeks.</strong></p>
+
+<p align="center">
+ <a href="https://www.npmjs.com/package/@three-ws/agent-vitals"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/agent-vitals?logo=npm&color=cb3837"></a>
+ <a href="https://www.npmjs.com/package/@three-ws/agent-vitals"><img alt="downloads" src="https://img.shields.io/npm/dm/@three-ws/agent-vitals?color=cb3837"></a>
+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/agent-vitals?color=3b82f6">
+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/agent-vitals?color=339933">
+ <img alt="dependencies" src="https://img.shields.io/badge/dependencies-0-brightgreen">
+</p>
+
+<p align="center">
+ <a href="#install">Install</a> ·
+ <a href="#quick-start">Quick start</a> ·
+ <a href="#the-idea">The idea</a> ·
+ <a href="#api">API</a> ·
+ <a href="#design-rules">Design rules</a> ·
+ <a href="https://three.ws">three.ws</a>
+</p>
+
+---
+
+## The story
+
+On 2026-08-28 we audited twelve autonomous trading agents. All twelve reported
+armed. The worker was `Ready:True` with `minScale: 1`. The launch feed was
+streaming. Every strategy row said `enabled = true`. Every dashboard was green.
+
+Ten of the twelve had not attempted a single action in **weeks**.
+
+Three separate things were wrong, and not one of them was visible to anything
+we were measuring:
+
+1. The deployed container predated the commit that moved our model providers off
+ decommissioned model IDs, so every rung of the chain answered `404`.
+2. The providers behind the surviving rungs were out of credit (`402`) or on a
+ billing hold (`403`).
+3. Several agent wallets could not fund a single action.
+
+Every existing check was correct and every one of them was useless. Liveness
+measures the *process*. Acting requires a chain of preconditions the process
+knows nothing about. **The agent was perfectly healthy and structurally
+incapable of doing its job.**
+
+This library is what we built so that never takes an afternoon to diagnose again.
+
+## Install
+
+```bash
+npm i @three-ws/agent-vitals
+```
+
+Zero dependencies. Node 18+. Works in any runtime with `fetch` and `AbortSignal`.
+
+## Quick start
+
+Declare what your agent *needs* in order to act, and how those needs depend on
+each other. Then ask.
+
+```js
+import { vitals } from '@three-ws/agent-vitals';
+
+const chart = vitals({ agent: 'trader-01' })
+ .vital('deploy-fresh', {
+ describe: 'the running image is the code we think it is',
+ probe: async () => ({
+ ok: (await imageAgeDays()) < 7,
+ detail: `image is ${await imageAgeDays()} days old`,
+ }),
+ remedy: 'gcloud builds submit --config worker/cloudbuild.yaml',
+ })
+ .vital('cognition', {
+ describe: 'the agent can reach a model and get a decision',
+ needs: ['deploy-fresh'], // <- a stale image CAUSES this to fail
+ probe: async () => ({ ok: await modelChainAnswers() }),
+ remedy: 'top up the model provider credits',
+ })
+ .vital('solvency', {
+ describe: 'the wallet can fund one action',
+ probe: async () => ({ ok: balance >= perAction, data: { short: perAction - balance } }),
+ remedy: ({ data }) => `send ${data.short.toFixed(4)} SOL to ${wallet}`,
+ })
+ .capability('trade', { needs: ['cognition', 'solvency'] })
+ .capability('exit', { needs: ['solvency'] }); // exiting needs no model
+
+const verdict = await chart.attest();
+
+verdict.can.trade; // false
+verdict.can.exit; // true <- it can still close its open risk
+verdict.rootCauses[0].id; // 'deploy-fresh' NOT 'cognition'
+verdict.remedies; // ['gcloud builds submit --config worker/cloudbuild.yaml']
+```
+
+```
+> console.log(verdict.explain())
+
+trader-01: cannot trade because cognition is blocked, because deploy-fresh is down (image is 16 days old)
+fix: gcloud builds submit --config worker/cloudbuild.yaml
+```
+
+That output is the entire product. One sentence, the real cause, and the command.
+
+## The idea
+
+### Health checks report symptoms. This reports causes.
+
+A checklist gives you three red rows and makes a human guess which to chase:
+
+```
+✗ decision queue saturated
+✗ model chain unreachable
+✗ deployment stale
+```
+
+Those are not three problems. They are **one problem and two of its
+consequences**. `agent-vitals` takes `needs` edges between preconditions, walks
+the graph, and returns only the nodes that nothing else explains:
+
+```
+ROOT deploy-fresh is down: image is 16 days old
+ fix: gcloud builds submit --config worker/cloudbuild.yaml
+ (blocked downstream, not probed: cognition, decision-queue)
+```
+
+### A vital behind a failing dependency is never probed
+
+If `deploy-fresh` is down, probing `cognition` only spends a timeout to
+rediscover something already known. In the outage that produced this library,
+that mistake meant every decision walked ten dead provider rungs before giving
+up, which saturated the decision queue, which looked like a *third* independent
+fault. Blocked vitals are marked `blocked` and skipped.
+
+### "I could not tell" is never "it is broken"
+
+An unread balance is not a balance of zero. A probe that throws, times out, or
+returns no verdict is `unknown`, and `unknown` never becomes `down`. A
+capability with an unreadable precondition is `null` (cannot say), not `false`
+(cannot act). One flaky RPC call must not page someone to a healthy fleet.
+
+This rule propagates. Blocking on an *unreadable* dependency yields
+`blockedSeverity: 'unknown'` and leaves the capability `unknown`; only a block
+tracing back to something genuinely `down` makes it `unable`. We shipped that
+backwards first, and it reported an agent that had acted sixty seconds earlier
+as definitively unable.
+
+### Every failure carries its fix
+
+`remedy` is part of a vital's declaration, and it can be a function that
+receives the probe's own `detail` and `data`. `send 0.0437 SOL to D5BGRD…`
+is a fix. `solvency: down` is a status page.
+
+### Capabilities are scoped, so partial failure stays partial
+
+`exit` above depends on `solvency` but not `cognition`. When the model chain
+dies, the agent correctly reports that it can still close its open positions.
+Collapsing that into one "agent unhealthy" bit tells an operator their risk is
+stranded when it is not.
+
+## API
+
+### `vitals(opts?) → VitalsChart`
+
+`{ agent?: string, timeoutMs?: number }`. Default per-probe deadline is 10s.
+
+### `.vital(id, spec) → this`
+
+| field | type | meaning |
+|---|---|---|
+| `probe` | `() => ProbeResult \| Promise<ProbeResult>` | **required.** Return `{ ok, detail?, data? }`, or a bare boolean. |
+| `needs` | `string[]` | Vitals that must be `up` before this one is worth probing. |
+| `describe` | `string` | What being `up` means, in a sentence. |
+| `remedy` | `string \| (ctx) => string` | The fix. The function form receives `{ detail, data }`. |
+| `timeoutMs` | `number` | Overrides the chart default for this probe. |
+
+`ok: true` → `up`. `ok: false` → `down`. Anything else (missing, `null`, a
+throw, a timeout, a non-result value) → `unknown`.
+
+### `.capability(id, { needs, describe? }) → this`
+
+An action the agent should be able to perform, as an AND over vitals. The
+transitive `needs` closure is included automatically.
+
+### `.attest({ signal? }) → Promise<Verdict>`
+
+Probes layer by layer. Everything at one dependency depth runs concurrently.
+Throws at call time on a dependency cycle or an edge to an undeclared vital,
+with the offending names in the message.
+
+### `Verdict`
+
+| member | type | meaning |
+|---|---|---|
+| `can` | `Record<string, boolean \| null>` | Per capability. `true` ready, `false` unable, `null` cannot say. |
+| `healthy` | `boolean` | Every capability is ready. |
+| `rootCauses` | `VitalReport[]` | Deduplicated causes across all failing capabilities, worst first. |
+| `remedies` | `string[]` | Distinct fixes, in the same order. |
+| `vitals` | `VitalReport[]` | Every reading, including `blocked` ones. |
+| `capabilities` | `CapabilityReport[]` | Per capability status, root causes and a one-line `explain`. |
+| `vital(id)` | `VitalReport \| null` | One reading by id. |
+| `explain()` | `string` | The whole verdict as a paragraph, written to be pasted into an incident channel. |
+| `toJSON()` | `object` | Plain and serialisable, answer first. |
+
+A `VitalReport` carries `status`, `detail`, `data`, `remedy`, `needs`,
+`blockedBy`, `blockedSeverity` and `ms`.
+
+## Design rules
+
+These are the invariants. Each one is enforced by a test, and each one exists
+because getting it wrong produced a wrong answer in production.
+
+1. **Report causes, never symptoms.** A failing vital with a failing dependency
+ is not a root cause.
+2. **Never probe behind a known failure.** It costs a timeout to learn nothing.
+3. **Unreadable is not failed**, at any depth, including through a chain of
+ blocks.
+4. **A definite failure outranks an unreadable one.** If one precondition is
+ genuinely broken, the agent genuinely cannot act.
+5. **Every failure carries its fix**, with real values in it.
+6. **One cause blocking five capabilities is one work item**, not five.
+7. **Pure core, injected I/O.** Graph building, ordering, cycle detection,
+ blocking and root-cause resolution are synchronous and side-effect free. The
+ whole test suite runs with no network, no clock and no database.
+
+## A note on being wrong
+
+A capability model is a model, and models are wrong. Ours was: the first
+revision made every agent depend on deployment freshness, and confidently
+reported an agent as unable to act while it was opening positions every few
+minutes on the very image being complained about.
+
+So give your ledger a vote. If the graph says `unable` and the agent
+demonstrably acted five minutes ago, the graph is wrong, and it should say so
+rather than quietly winning the argument against reality. The three.ws
+integration ships this as a `contradiction` field; the pattern is worth copying
+wherever you have a record of what the agent actually did.
+
+## License
+
+Apache-2.0 · [three.ws](https://three.ws)
diff --git a/packages/agent-vitals/package.json b/packages/agent-vitals/package.json
new file mode 100644
index 000000000..2efc0e5cc
--- /dev/null
+++ b/packages/agent-vitals/package.json
@@ -0,0 +1,59 @@
+{
+ "name": "@three-ws/agent-vitals",
+ "version": "0.1.0",
+ "description": "Capability attestation for autonomous agents. Not \"is it up\" but \"can it act\": model an agent's preconditions as a causal graph, get back the root blocker and the command that fixes it.",
+ "type": "module",
+ "main": "./src/index.js",
+ "module": "./src/index.js",
+ "types": "./src/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./src/index.d.ts",
+ "import": "./src/index.js",
+ "default": "./src/index.js"
+ },
+ "./package.json": "./package.json"
+ },
+ "files": [
+ "src",
+ "README.md",
+ "LICENSE"
+ ],
+ "scripts": {
+ "test": "node --test test/*.test.js"
+ },
+ "keywords": [
+ "agent",
+ "autonomous",
+ "health-check",
+ "healthcheck",
+ "observability",
+ "root-cause",
+ "liveness",
+ "readiness",
+ "capability",
+ "attestation",
+ "monitoring",
+ "sre",
+ "ai-agent",
+ "three.ws"
+ ],
+ "author": "nirholas <[email protected]>",
+ "license": "Apache-2.0",
+ "homepage": "https://three.ws",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/nirholas/three.ws.git",
+ "directory": "packages/agent-vitals"
+ },
+ "bugs": {
+ "url": "https://github.com/nirholas/three.ws/issues"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "dependencies": {},
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/packages/agent-vitals/src/index.d.ts b/packages/agent-vitals/src/index.d.ts
new file mode 100644
index 000000000..748cbcaf9
--- /dev/null
+++ b/packages/agent-vitals/src/index.d.ts
@@ -0,0 +1,141 @@
+/**
+ * @three-ws/agent-vitals
+ * Capability attestation for autonomous agents: not "is it up" but "can it act".
+ */
+
+/** Where a single precondition stands. */
+export type VitalStatus =
+ /** Probed and satisfied. */
+ | 'up'
+ /** Probed and definitively not satisfied. */
+ | 'down'
+ /** Not probed at all: a dependency was already not `up`. */
+ | 'blocked'
+ /** Probed but undecidable (threw, timed out, or returned no verdict). Never treated as `down`. */
+ | 'unknown';
+
+/** Whether the agent can perform a declared action. */
+export type CapabilityStatus =
+ /** Every precondition in the closure is `up`. */
+ | 'ready'
+ /** At least one precondition is `down`, or blocked by something that is `down`. */
+ | 'unable'
+ /** Nothing is definitively broken, but at least one precondition is unreadable. */
+ | 'unknown';
+
+/**
+ * What a probe may return. A bare boolean is shorthand for `{ ok }`.
+ * A missing or null `ok` means "could not decide", which becomes `unknown`.
+ */
+export type ProbeResult =
+ | boolean
+ | {
+ ok?: boolean | null;
+ /** One short clause explaining the reading, shown in reports and explanations. */
+ detail?: string;
+ /** Arbitrary payload passed through to a remedy function and kept on the report. */
+ data?: unknown;
+ };
+
+export interface RemedyContext {
+ detail: string | null;
+ data: unknown;
+}
+
+export interface VitalSpec {
+ /** Human sentence describing what being `up` means. */
+ describe?: string;
+ /** Ids of vitals that must be `up` before this one is worth probing. */
+ needs?: string[];
+ probe: () => ProbeResult | Promise<ProbeResult>;
+ /** The fix. A function receives the probe's own detail and data so it can name real values. */
+ remedy?: string | ((ctx: RemedyContext) => string);
+ /** Per-probe deadline in ms. Overrides the chart default. */
+ timeoutMs?: number;
+}
+
+export interface CapabilitySpec {
+ describe?: string;
+ /** Vitals that must all be `up`. Their transitive `needs` are included automatically. */
+ needs: string[];
+}
+
+export interface VitalReport {
+ id: string;
+ status: VitalStatus;
+ describe: string | null;
+ detail: string | null;
+ data: unknown;
+ /** Populated only when the vital is not `up`. */
+ remedy: string | null;
+ needs: string[];
+ /** Direct dependencies that were not `up`. Non-empty only when `status` is `blocked`. */
+ blockedBy: string[];
+ /**
+ * For a `blocked` vital: whether the block traces back to a definite failure
+ * (`down`) or merely to an unreadable one (`unknown`). Null when not blocked.
+ * A block behind an unreadable probe leaves a capability `unknown`, never `unable`.
+ */
+ blockedSeverity: 'down' | 'unknown' | null;
+ /** Probe duration in ms; null when the vital was never probed. */
+ ms: number | null;
+}
+
+export interface CapabilityReport {
+ id: string;
+ describe: string | null;
+ status: CapabilityStatus;
+ needs: string[];
+ /** Failing vitals with no failing dependency of their own: causes, not symptoms. */
+ rootCauses: VitalReport[];
+ remedies: string[];
+ /** One sentence reading from the capability down to its root cause. */
+ explain: string;
+}
+
+export interface VerdictJSON {
+ agent: string | null;
+ at: string;
+ ms: number;
+ healthy: boolean;
+ can: Record<string, boolean | null>;
+ capabilities: CapabilityReport[];
+ vitals: VitalReport[];
+ root_causes: string[];
+ remedies: string[];
+}
+
+export declare class Verdict {
+ readonly agent: string | null;
+ readonly at: Date;
+ /** Wall-clock duration of the whole attestation. */
+ readonly ms: number;
+ readonly vitals: VitalReport[];
+ readonly capabilities: CapabilityReport[];
+ /** Per capability: true = ready, false = unable, null = cannot say. */
+ readonly can: Record<string, boolean | null>;
+ /** Every capability is ready. */
+ readonly healthy: boolean;
+ /** Distinct root causes across all failing capabilities, most severe first. */
+ readonly rootCauses: VitalReport[];
+ /** Distinct remedies for those root causes, in the same order. */
+ readonly remedies: string[];
+ vital(id: string): VitalReport | null;
+ /** The whole verdict as a human paragraph, written to be pasted into an incident channel. */
+ explain(): string;
+ toJSON(): VerdictJSON;
+}
+
+export declare class VitalsChart {
+ constructor(opts?: { agent?: string; timeoutMs?: number });
+ readonly agent: string | null;
+ readonly timeoutMs: number;
+ vital(id: string, spec: VitalSpec): this;
+ capability(id: string, spec: CapabilitySpec): this;
+ /** Probe the graph layer by layer and return the verdict. */
+ attest(opts?: { signal?: AbortSignal }): Promise<Verdict>;
+}
+
+export declare function vitals(opts?: { agent?: string; timeoutMs?: number }): VitalsChart;
+
+export declare const DEFAULT_TIMEOUT_MS: number;
diff --git a/packages/agent-vitals/src/index.js b/packages/agent-vitals/src/index.js
new file mode 100644
index 000000000..91d2dd4d5
--- /dev/null
+++ b/packages/agent-vitals/src/index.js
@@ -0,0 +1,666 @@
+// @ts-check
+/**
+ * @three-ws/agent-vitals
+ *
+ * Capability attestation for autonomous agents: not "is it up" but "can it act".
+ *
+ * The failure this library exists for
+ * -----------------------------------
+ * An autonomous agent reports perfectly healthy while being structurally
+ * incapable of doing the one thing it exists to do. The process is up. The
+ * feed is connected. The strategy is armed. Every dashboard is green. And it
+ * has not acted in three weeks.
+ *
+ * That is not a monitoring gap, it is a modelling gap. Liveness checks measure
+ * the agent's *process*. Acting requires a whole chain of preconditions the
+ * process knows nothing about: it must be permitted to act, be able to pay for
+ * the action, be able to decide, be able to see an opportunity, and be able to
+ * land the result. Each link fails independently and silently, and the agent
+ * keeps looping cheerfully through a decision it can never complete.
+ *
+ * Why a DAG and not a checklist
+ * -----------------------------
+ * Preconditions are not independent, and a flat list of failures buries the
+ * answer. A stale deployment causes a dead model chain, which causes a
+ * saturated decision queue, which causes zero entries. A checklist reports
+ * three red rows and makes a human guess which one to chase. This library
+ * models `needs` edges between vitals and reports the *root*: the deepest
+ * failing node with no failing dependency of its own. Symptoms are recorded
+ * but never presented as causes.
+ *
+ * Three consequences fall out of that model, and each one is a bug this
+ * library refuses to reproduce:
+ *
+ * 1. A vital whose dependency is already down is `blocked`, never probed.
+ * Probing it would spend a timeout to rediscover a known failure. That is
+ * exactly how one dead model chain turned every decision into a ten-rung
+ * walk through ten timeouts.
+ * 2. A probe that could not be read is `unknown`, never `down`. An unread
+ * balance is not a balance of zero, and an RPC blip must not page someone
+ * to a healthy fleet.
+ * 3. Every vital carries a `remedy`. A verdict that says "cognition: down"
+ * is a status page. A verdict that says "run this command" is a fix.
+ *
+ * Pure core, injected I/O
+ * -----------------------
+ * Graph construction, ordering, cycle detection, blocking and root-cause
+ * resolution are pure and synchronous over probe results. Every side effect
+ * lives in a probe the caller supplies, so the interesting logic is testable
+ * without a network, a clock, or a database.
+ *
+ * @example
+ * import { vitals } from '@three-ws/agent-vitals';
+ *
+ * const chart = vitals()
+ * .vital('deploy-fresh', {
+ * describe: 'the running image is the code we think it is',
+ * probe: async () => ({ ok: deployedSha === headSha, detail: `image ${imageAge} old` }),
+ * remedy: 'gcloud builds submit --config workers/agent-sniper/cloudbuild.yaml',
+ * })
+ * .vital('cognition', {
+ * describe: 'the agent can reach a model and get a decision',
+ * needs: ['deploy-fresh'],
+ * probe: async () => ({ ok: await modelChainReachable() }),
+ * remedy: 'top up the model provider credits',
+ * })
+ * .vital('solvency', {
+ * describe: 'the wallet can fund one action',
+ * probe: async () => ({ ok: balance >= perAction }),
+ * remedy: () => `send ${(perAction - balance).toFixed(4)} SOL to ${wallet}`,
+ * })
+ * .capability('trade', { needs: ['cognition', 'solvency'] });
+ *
+ * const verdict = await chart.attest();
+ * verdict.can.trade; // false
+ * verdict.rootCauses[0].id; // 'deploy-fresh' (not 'cognition')
+ * verdict.explain(); // 'cannot trade because cognition is blocked, because ...'
+ */
+
+/** @typedef {'up'|'down'|'blocked'|'unknown'} VitalStatus */
+/** @typedef {'ready'|'unable'|'unknown'} CapabilityStatus */
+
+/**
+ * What a probe may return. `true`/`false` are accepted as shorthand for
+ * `{ ok }` so a one-line predicate does not have to build an object.
+ * @typedef {boolean | { ok?: boolean|null, detail?: string, data?: unknown }} ProbeResult
+ */
+
+/**
+ * @typedef {object} VitalSpec
+ * @property {string} [describe] human sentence: what being `up` means
+ * @property {string[]} [needs] ids of vitals this one depends on
+ * @property {() => (ProbeResult | Promise<ProbeResult>)} probe
+ * @property {string | ((ctx: { detail: string|null, data: unknown }) => string)} [remedy]
+ * @property {number} [timeoutMs] per-probe deadline; overrides the chart default
+ */
+
+/**
+ * @typedef {object} VitalReport
+ * @property {string} id
+ * @property {VitalStatus} status
+ * @property {string|null} describe
+ * @property {string|null} detail
+ * @property {unknown} data
+ * @property {string|null} remedy
+ * @property {string[]} needs
+ * @property {string[]} blockedBy direct dependencies that were not `up`
+ * @property {'down'|'unknown'|null} blockedSeverity
+ * For a `blocked` vital: whether the block traces back to a definite failure
+ * (`down`) or merely to an unreadable one (`unknown`). Null when not blocked.
+ * @property {number|null} ms probe duration; null when never probed
+ */
+
+const DEFAULT_TIMEOUT_MS = 10_000;
+
+/** Statuses that stop a dependent from being probed at all. */
+const NOT_UP = new Set(['down', 'blocked', 'unknown']);
+
+/**
+ * How bad a block is, propagated down the graph.
+ *
+ * Blocking on an unreadable dependency is NOT the same as blocking on a broken
+ * one, and collapsing the two inverts the library's own rule one level up: a
+ * single unread probe would cascade into "this agent cannot act" for every
+ * vital downstream of it. That is how an arm which had traded sixty seconds
+ * earlier was reported as definitively unable, purely because a credential for
+ * an unrelated probe was missing.
+ *
+ * A block is definite only when something in its chain is actually `down`.
+ *
+ * @param {string[]} blockedBy
+ * @param {Map<string, VitalReport>} reports
+ * @returns {'down'|'unknown'}
+ */
+function blockSeverity(blockedBy, reports) {
+ for (const id of blockedBy) {
+ const dep = reports.get(id);
+ if (!dep) continue;
+ if (dep.status === 'down') return 'down';
+ if (dep.status === 'blocked' && dep.blockedSeverity === 'down') return 'down';
+ }
+ return 'unknown';
+}
+
+const isPlainObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
+
+/**
+ * A probe's raw return, normalised. `ok: null` (or a missing `ok`) means the
+ * probe ran but could not decide, which is `unknown`, never `down`.
+ * @param {ProbeResult} raw
+ * @returns {{ ok: boolean|null, detail: string|null, data: unknown }}
+ */
+function normalizeProbeResult(raw) {
+ if (typeof raw === 'boolean') return { ok: raw, detail: null, data: undefined };
+ if (!isPlainObject(raw)) return { ok: null, detail: 'probe returned a non-result value', data: raw };
+ const ok = raw.ok === true ? true : raw.ok === false ? false : null;
+ const detail = typeof raw.detail === 'string' && raw.detail ? raw.detail : null;
+ return { ok, detail, data: raw.data };
+}
+
+/**
+ * Run one probe under a deadline. A probe that throws or overruns is `unknown`
+ * with the reason in `detail`: the library never converts "I could not tell"
+ * into "it is broken", because that inversion is what makes a health system
+ * page someone at 3am for a network blip.
+ *
+ * The deadline is a race, not a cancellation. A probe that ignores it keeps
+ * running in the background; that is the caller's contract to honour with an
+ * AbortSignal of their own if they need one.
+ *
+ * @param {VitalSpec} spec
+ * @param {number} timeoutMs
+ * @returns {Promise<{ ok: boolean|null, detail: string|null, data: unknown, ms: number }>}
+ */
+async function runProbe(spec, timeoutMs) {
+ const started = Date.now();
+ /** @type {ReturnType<typeof setTimeout>|undefined} */
+ let timer;
+ try {
+ const deadline = new Promise((_resolve, reject) => {
+ timer = setTimeout(() => reject(new Error(`probe exceeded ${timeoutMs}ms`)), timeoutMs);
+ // Never hold the event loop open on our own deadline.
+ if (typeof timer?.unref === 'function') timer.unref();
+ });
+ const raw = await Promise.race([Promise.resolve().then(() => spec.probe()), deadline]);
+ return { ...normalizeProbeResult(/** @type {ProbeResult} */ (raw)), ms: Date.now() - started };
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ return { ok: null, detail: `probe failed: ${message}`, data: undefined, ms: Date.now() - started };
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+/**
+ * Resolve a vital's remedy. A function remedy is handed the probe's own detail
+ * and data so the fix can name the real number: "send 0.0187 SOL to <address>"
+ * beats "fund the wallet" every time an operator reads it at speed.
+ *
+ * @param {VitalSpec} spec
+ * @param {{ detail: string|null, data: unknown }} ctx
+ * @returns {string|null}
+ */
+function resolveRemedy(spec, ctx) {
+ const { remedy } = spec;
+ if (typeof remedy === 'string') return remedy || null;
+ if (typeof remedy !== 'function') return null;
+ try {
+ const out = remedy(ctx);
+ return typeof out === 'string' && out ? out : null;
+ } catch {
+ // A remedy that throws must never take down an attestation: the verdict
+ // is the point, the suggested fix is a convenience on top of it.
+ return null;
+ }
+}
+
+/**
+ * Kahn layering. Returns vitals grouped into dependency levels so an
+ * attestation can probe a whole level concurrently, and throws on a cycle
+ * with the members named.
+ *
+ * Cycles are a construction bug, so this runs at `attest()` time over the
+ * assembled graph rather than being deferred into per-probe failures.
+ *
+ * @param {Map<string, VitalSpec>} vitals
+ * @returns {string[][]}
+ */
+function layer(vitals) {
+ /** @type {Map<string, number>} */
+ const pending = new Map();
+ /** @type {Map<string, string[]>} */
+ const dependents = new Map();
+
+ for (const [id, spec] of vitals) {
+ const needs = spec.needs || [];
+ pending.set(id, needs.length);
+ for (const need of needs) {
+ if (!dependents.has(need)) dependents.set(need, []);
+ /** @type {string[]} */ (dependents.get(need)).push(id);
+ }
+ }
+
+ /** @type {string[][]} */
+ const layers = [];
+ let ready = [...pending.entries()].filter(([, n]) => n === 0).map(([id]) => id);
+ let placed = 0;
+
+ while (ready.length) {
+ // Stable order inside a layer keeps reports and test fixtures readable.
+ ready.sort();
+ layers.push(ready);
+ placed += ready.length;
+ /** @type {string[]} */
+ const next = [];
+ for (const id of ready) {
+ for (const dep of dependents.get(id) || []) {
+ const left = /** @type {number} */ (pending.get(dep)) - 1;
+ pending.set(dep, left);
+ if (left === 0) next.push(dep);
+ }
+ }
+ ready = next;
+ }
+
+ if (placed !== vitals.size) {
+ const cyclic = [...pending.entries()].filter(([, n]) => n > 0).map(([id]) => id).sort();
+ throw new Error(`agent-vitals: dependency cycle among [${cyclic.join(', ')}]`);
+ }
+ return layers;
+}
+
+/**
+ * Every vital reachable from a set of roots, following `needs` edges.
+ * @param {string[]} roots
+ * @param {Map<string, VitalSpec>} vitals
+ * @returns {Set<string>}
+ */
+function closure(roots, vitals) {
+ const seen = new Set();
+ const stack = [...roots];
+ while (stack.length) {
+ const id = /** @type {string} */ (stack.pop());
+ if (seen.has(id)) continue;
+ seen.add(id);
+ for (const need of vitals.get(id)?.needs || []) stack.push(need);
+ }
+ return seen;
+}
+
+/**
+ * The point of the whole library: given a set of failing vitals, return only
+ * the ones that are not explained by another failure.
+ *
+ * A vital is a root cause when it is itself not `up` AND every vital it
+ * depends on IS `up`. Anything with a failing dependency is a symptom, and
+ * presenting symptoms as causes is what makes an operator chase a dead model
+ * chain for an hour when the real answer was a stale deployment.
+ *
+ * @param {Set<string>} scope vitals in the failing capability's closure
+ * @param {Map<string, VitalReport>} reports
+ * @returns {VitalReport[]}
+ */
+function rootCausesIn(scope, reports) {
+ /** @type {VitalReport[]} */
+ const roots = [];
+ for (const id of scope) {
+ const report = reports.get(id);
+ if (!report || report.status === 'up') continue;
+ const explained = report.needs.some((need) => {
+ const dep = reports.get(need);
+ return dep ? dep.status !== 'up' : false;
+ });
+ if (!explained) roots.push(report);
+ }
+ // `down` before `unknown`: a definite failure outranks an unreadable one
+ // when an operator only reads the first line.
+ const rank = { down: 0, blocked: 1, unknown: 2, up: 3 };
+ return roots.sort((a, b) => (rank[a.status] - rank[b.status]) || a.id.localeCompare(b.id));
+}
+
+/**
+ * A capability's verdict over its dependency closure.
+ *
+ * `unable` outranks `unknown` deliberately. If one precondition is definitively
+ * broken, the agent cannot act, and an unreadable second precondition does not
+ * make that any less true. Only when nothing is definitively broken does an
+ * unreadable input downgrade the answer to "cannot say".
+ *
+ * @param {Set<string>} scope
+ * @param {Map<string, VitalReport>} reports
+ * @returns {CapabilityStatus}
+ */
+function capabilityStatus(scope, reports) {
+ let sawUnknown = false;
+ for (const id of scope) {
+ const report = reports.get(id);
+ if (!report) { sawUnknown = true; continue; }
+ if (report.status === 'down') return 'unable';
+ // A block only makes the capability definitively unable when the block
+ // traces to something actually broken. A block behind an unread probe
+ // leaves the answer unknown, exactly like the unread probe itself.
+ if (report.status === 'blocked') {
+ if (report.blockedSeverity === 'down') return 'unable';
+ sawUnknown = true;
+ continue;
+ }
+ if (report.status === 'unknown') sawUnknown = true;
+ }
+ return sawUnknown ? 'unknown' : 'ready';
+}
+
+/**
+ * Build the causal sentence for one capability: the chain from the capability
+ * down to its root cause, in the order a human would say it out loud.
+ *
+ * @param {string} capabilityId
+ * @param {CapabilityStatus} status
+ * @param {VitalReport[]} roots
+ * @param {Map<string, VitalReport>} reports
+ * @returns {string}
+ */
+function explainCapability(capabilityId, status, roots, reports) {
+ if (status === 'ready') return `can ${capabilityId}`;
+ if (!roots.length) return `cannot say whether it can ${capabilityId}`;
+
+ const verb = status === 'unable' ? 'cannot' : 'may not be able to';
+ const clauses = roots.map((root) => {
+ // Walk UP from the root through whatever it blocked, so the sentence reads
+ // outermost symptom first and lands on the cause: an operator scanning one
+ // line gets "cognition is blocked, because deploy-fresh is down", which is
+ // the order they would say it out loud.
+ /** @type {VitalReport[]} */
+ const chain = [root];
+ const seen = new Set([root.id]);
+ for (;;) {
+ const head = chain[0];
+ const symptom = [...reports.values()].find((r) => r.status === 'blocked' && !seen.has(r.id) && r.blockedBy.includes(head.id));
+ if (!symptom) break;
+ seen.add(symptom.id);
+ chain.unshift(symptom);
+ }
+ const because = chain.map((r) => `${r.id} is ${r.status}`).join(', because ');
+ return root.detail ? `${because} (${root.detail})` : because;
+ });
+ return `${verb} ${capabilityId} because ${clauses.join('; and ')}`;
+}
+
+/**
+ * A vitals chart: the graph of preconditions plus the capabilities defined over
+ * them. Build with {@link vitals}, then call {@link VitalsChart#attest}.
+ */
+class VitalsChart {
+ /** @param {{ agent?: string, timeoutMs?: number }} [opts] */
+ constructor(opts = {}) {
+ /** @type {string|null} */
+ this.agent = opts.agent ?? null;
+ this.timeoutMs = Number.isFinite(opts.timeoutMs) && Number(opts.timeoutMs) > 0
+ ? Number(opts.timeoutMs)
+ : DEFAULT_TIMEOUT_MS;
+ /** @type {Map<string, VitalSpec>} */
+ this._vitals = new Map();
+ /** @type {Map<string, { describe: string|null, needs: string[] }>} */
+ this._capabilities = new Map();
+ }
+
+ /**
+ * Declare a precondition.
+ * @param {string} id
+ * @param {VitalSpec} spec
+ * @returns {this}
+ */
+ vital(id, spec) {
+ if (!id || typeof id !== 'string') throw new TypeError('agent-vitals: a vital needs a string id');
+ if (this._vitals.has(id)) throw new Error(`agent-vitals: duplicate vital "${id}"`);
+ if (typeof spec?.probe !== 'function') throw new TypeError(`agent-vitals: vital "${id}" needs a probe function`);
+ this._vitals.set(id, { ...spec, needs: [...(spec.needs || [])] });
+ return this;
+ }
+
+ /**
+ * Declare something the agent should be able to do, as an AND over vitals.
+ * @param {string} id
+ * @param {{ describe?: string, needs: string[] }} spec
+ * @returns {this}
+ */
+ capability(id, spec) {
+ if (!id || typeof id !== 'string') throw new TypeError('agent-vitals: a capability needs a string id');
+ if (this._capabilities.has(id)) throw new Error(`agent-vitals: duplicate capability "${id}"`);
+ if (!Array.isArray(spec?.needs) || !spec.needs.length) {
+ throw new TypeError(`agent-vitals: capability "${id}" needs a non-empty needs array`);
+ }
+ this._capabilities.set(id, { describe: spec.describe ?? null, needs: [...spec.needs] });
+ return this;
+ }
+
+ /**
+ * Every edge must land on a declared vital. Checked once, up front, so a
+ * typo in `needs` is a build error with a name in it rather than a silently
+ * ignored dependency that makes a broken agent look healthy.
+ */
+ _assertEdges() {
+ for (const [id, spec] of this._vitals) {
+ for (const need of spec.needs || []) {
+ if (!this._vitals.has(need)) throw new Error(`agent-vitals: vital "${id}" needs unknown vital "${need}"`);
+ }
+ }
+ for (const [id, spec] of this._capabilities) {
+ for (const need of spec.needs) {
+ if (!this._vitals.has(need)) throw new Error(`agent-vitals: capability "${id}" needs unknown vital "${need}"`);
+ }
+ }
+ }
+
+ /**
+ * Probe the graph and return the verdict.
+ *
+ * Vitals are probed layer by layer: everything at one dependency depth runs
+ * concurrently, and a vital whose dependency is not `up` is marked `blocked`
+ * without ever being probed.
+ *
+ * @param {{ signal?: AbortSignal }} [opts]
+ * @returns {Promise<Verdict>}
+ */
+ async attest(opts = {}) {
+ this._assertEdges();
+ const layers = layer(this._vitals);
+
+ /** @type {Map<string, VitalReport>} */
+ const reports = new Map();
+ const startedAt = new Date();
+
+ for (const level of layers) {
+ await Promise.all(level.map(async (id) => {
+ const spec = /** @type {VitalSpec} */ (this._vitals.get(id));
+ const needs = spec.needs || [];
+ const blockedBy = needs.filter((need) => NOT_UP.has(/** @type {VitalStatus} */ (reports.get(need)?.status)));
+
+ if (blockedBy.length) {
+ reports.set(id, {
+ id,
+ status: 'blocked',
+ describe: spec.describe ?? null,
+ detail: `not probed: ${blockedBy.join(', ')} ${blockedBy.length > 1 ? 'are' : 'is'} not up`,
+ data: undefined,
+ remedy: null,
+ needs,
+ blockedBy,
+ blockedSeverity: blockSeverity(blockedBy, reports),
+ ms: null,
+ });
+ return;
+ }
+
+ if (opts.signal?.aborted) {
+ reports.set(id, {
+ id,
+ status: 'unknown',
+ describe: spec.describe ?? null,
+ detail: 'attestation aborted before this probe ran',
+ data: undefined,
+ remedy: null,
+ needs,
+ blockedBy: [],
+ blockedSeverity: null,
+ ms: null,
+ });
+ return;
+ }
+
+ const result = await runProbe(spec, spec.timeoutMs ?? this.timeoutMs);
+ /** @type {VitalStatus} */
+ const status = result.ok === true ? 'up' : result.ok === false ? 'down' : 'unknown';
+ reports.set(id, {
+ id,
+ status,
+ describe: spec.describe ?? null,
+ detail: result.detail,
+ data: result.data,
+ remedy: status === 'up' ? null : resolveRemedy(spec, { detail: result.detail, data: result.data }),
+ needs,
+ blockedBy: [],
+ blockedSeverity: null,
+ ms: result.ms,
+ });
+ }));
+ }
+
+ /** @type {Record<string, boolean|null>} */
+ const can = {};
+ /** @type {CapabilityReport[]} */
+ const capabilities = [];
+ for (const [id, spec] of this._capabilities) {
+ const scope = closure(spec.needs, this._vitals);
+ const status = capabilityStatus(scope, reports);
+ const roots = status === 'ready' ? [] : rootCausesIn(scope, reports);
+ can[id] = status === 'ready' ? true : status === 'unable' ? false : null;
+ capabilities.push({
+ id,
+ describe: spec.describe,
+ status,
+ needs: spec.needs,
+ rootCauses: roots,
+ remedies: roots.map((r) => r.remedy).filter((r) => typeof r === 'string'),
+ explain: explainCapability(id, status, roots, reports),
+ });
+ }
+
+ return new Verdict({
+ agent: this.agent,
+ at: startedAt,
+ ms: Date.now() - startedAt.getTime(),
+ vitals: [...reports.values()],
+ capabilities,
+ });
+ }
+}
+
+/**
+ * @typedef {object} CapabilityReport
+ * @property {string} id
+ * @property {string|null} describe
+ * @property {CapabilityStatus} status
+ * @property {string[]} needs
+ * @property {VitalReport[]} rootCauses
+ * @property {string[]} remedies
+ * @property {string} explain
+ */
+
+/**
+ * The result of an attestation. Carries the raw reports plus the two things a
+ * caller actually wants: whether the agent can act, and what to do about it.
+ */
+class Verdict {
+ /**
+ * @param {{ agent: string|null, at: Date, ms: number, vitals: VitalReport[], capabilities: CapabilityReport[] }} p
+ */
+ constructor(p) {
+ this.agent = p.agent;
+ this.at = p.at;
+ this.ms = p.ms;
+ /** @type {VitalReport[]} */
+ this.vitals = p.vitals;
+ /** @type {CapabilityReport[]} */
+ this.capabilities = p.capabilities;
+ /** @type {Record<string, boolean|null>} true = ready, false = unable, null = cannot say */
+ this.can = Object.fromEntries(
+ p.capabilities.map((c) => [c.id, c.status === 'ready' ? true : c.status === 'unable' ? false : null]),
+ );
+ }
+
+ /** Every capability is ready. */
+ get healthy() {
+ return this.capabilities.every((c) => c.status === 'ready');
+ }
+
+ /**
+ * The distinct root causes across every failing capability, most severe
+ * first. This is the operator's work queue, deduplicated: one stale
+ * deployment blocking four capabilities is one item, not four.
+ * @returns {VitalReport[]}
+ */
+ get rootCauses() {
+ /** @type {Map<string, VitalReport>} */
+ const byId = new Map();
+ for (const capability of this.capabilities) {
+ for (const root of capability.rootCauses) if (!byId.has(root.id)) byId.set(root.id, root);
+ }
+ const rank = { down: 0, blocked: 1, unknown: 2, up: 3 };
+ return [...byId.values()].sort((a, b) => (rank[a.status] - rank[b.status]) || a.id.localeCompare(b.id));
+ }
+
+ /**
+ * Distinct remedies for every root cause, in the same order. Deduplicated,
+ * because one fix that unblocks three capabilities should be read once.
+ * @returns {string[]}
+ */
+ get remedies() {
+ const out = [];
+ for (const root of this.rootCauses) if (root.remedy && !out.includes(root.remedy)) out.push(root.remedy);
+ return out;
+ }
+
+ /** One vital by id. @param {string} id @returns {VitalReport|null} */
+ vital(id) {
+ return this.vitals.find((v) => v.id === id) ?? null;
+ }
+
+ /**
+ * The whole verdict as a human paragraph: one line per capability, then the
+ * remedies. Written to be pasted into an incident channel as-is.
+ * @returns {string}
+ */
+ explain() {
+ const who = this.agent ? `${this.agent}: ` : '';
+ if (this.healthy) return `${who}${this.capabilities.map((c) => `can ${c.id}`).join(', ')}`;
+ const lines = this.capabilities.filter((c) => c.status !== 'ready').map((c) => `${who}${c.explain}`);
+ for (const remedy of this.remedies) lines.push(`fix: ${remedy}`);
+ return lines.join('\n');
+ }
+
+ /** Plain JSON, safe to log or serve. @returns {object} */
+ toJSON() {
+ return {
+ agent: this.agent,
+ at: this.at.toISOString(),
+ ms: this.ms,
+ healthy: this.healthy,
+ can: this.can,
+ capabilities: this.capabilities,
+ vitals: this.vitals,
+ root_causes: this.rootCauses.map((r) => r.id),
+ remedies: this.remedies,
+ };
+ }
+}
+
+/**
+ * Start a vitals chart.
+ * @param {{ agent?: string, timeoutMs?: number }} [opts]
+ * @returns {VitalsChart}
+ */
+export function vitals(opts) {
+ return new VitalsChart(opts);
+}
+
+export { VitalsChart, Verdict, DEFAULT_TIMEOUT_MS };
diff --git a/packages/agent-vitals/test/vitals.test.js b/packages/agent-vitals/test/vitals.test.js
new file mode 100644
index 000000000..42a6de687
--- /dev/null
+++ b/packages/agent-vitals/test/vitals.test.js
@@ -0,0 +1,391 @@
+// Core behaviour of the vitals graph. Every probe here is a plain function, so
+// the whole suite runs with no network, no clock and no database: the point of
+// the pure-core / injected-I/O split is that the interesting logic is testable
+// on its own.
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { vitals } from '../src/index.js';
+
+const up = () => ({ ok: true });
+const down = (detail) => () => ({ ok: false, detail });
+
+test('a capability over healthy vitals is ready', async () => {
+ const verdict = await vitals({ agent: 'a1' })
+ .vital('solvency', { probe: up })
+ .vital('cognition', { probe: up })
+ .capability('trade', { needs: ['solvency', 'cognition'] })
+ .attest();
+
+ assert.equal(verdict.can.trade, true);
+ assert.equal(verdict.healthy, true);
+ assert.deepEqual(verdict.rootCauses, []);
+ assert.equal(verdict.explain(), 'a1: can trade');
+});
+
+test('reports the root cause, not the symptom it caused', async () => {
+ const verdict = await vitals()
+ .vital('deploy-fresh', { probe: down('image is 16 days old'), remedy: 'redeploy the worker' })
+ .vital('cognition', { needs: ['deploy-fresh'], probe: up })
+ .vital('solvency', { probe: up })
+ .capability('trade', { needs: ['cognition', 'solvency'] })
+ .attest();
+
+ assert.equal(verdict.can.trade, false);
+ assert.deepEqual(verdict.rootCauses.map((r) => r.id), ['deploy-fresh']);
+ assert.equal(verdict.vital('cognition').status, 'blocked');
+ assert.deepEqual(verdict.remedies, ['redeploy the worker']);
+});
+
+test('a vital behind a failing dependency is never probed', async () => {
+ let probed = 0;
+ await vitals()
+ .vital('deploy-fresh', { probe: down() })
+ .vital('cognition', {
+ needs: ['deploy-fresh'],
+ probe: () => {
+ probed += 1;
+ return { ok: true };
+ },
+ })
+ .capability('trade', { needs: ['cognition'] })
+ .attest();
+
+ // Probing it would spend a timeout rediscovering a failure we already know.
+ assert.equal(probed, 0);
+});
+
+test('an unreadable probe is unknown, never down', async () => {
+ const verdict = await vitals()
+ .vital('balance', { probe: () => { throw new Error('rpc 429'); } })
+ .capability('trade', { needs: ['balance'] })
+ .attest();
+
+ assert.equal(verdict.vital('balance').status, 'unknown');
+ // "cannot say" and "cannot act" are different answers and must not collapse.
+ assert.equal(verdict.can.trade, null);
+ assert.match(verdict.vital('balance').detail, /rpc 429/);
+});
+
+test('a probe returning no verdict is unknown, not a silent pass', async () => {
+ const verdict = await vitals()
+ .vital('feed', { probe: () => ({ detail: 'upstream gave no answer' }) })
+ .capability('trade', { needs: ['feed'] })
+ .attest();
+
+ assert.equal(verdict.vital('feed').status, 'unknown');
+ assert.equal(verdict.can.trade, null);
+});
+
+test('a definite failure outranks an unreadable one', async () => {
+ const verdict = await vitals()
+ .vital('solvency', { probe: down('wallet empty') })
+ .vital('feed', { probe: () => { throw new Error('timeout'); } })
+ .capability('trade', { needs: ['solvency', 'feed'] })
+ .attest();
+
+ // One precondition is definitively broken, so the agent definitively cannot
+ // act; an unreadable second precondition does not soften that.
+ assert.equal(verdict.can.trade, false);
+ assert.equal(verdict.rootCauses[0].id, 'solvency');
+});
+
+test('a probe that overruns its deadline is unknown, and the chart keeps going', async () => {
+ const verdict = await vitals({ timeoutMs: 20 })
+ .vital('slow', { probe: () => new Promise((resolve) => { setTimeout(() => resolve({ ok: true }), 5_000).unref?.(); }) })
+ .vital('fast', { probe: up })
+ .capability('trade', { needs: ['slow', 'fast'] })
+ .attest();
+
+ assert.equal(verdict.vital('slow').status, 'unknown');
+ assert.equal(verdict.vital('fast').status, 'up');
+ assert.match(verdict.vital('slow').detail, /exceeded 20ms/);
+});
+
+test('a per-vital timeout overrides the chart default', async () => {
+ const verdict = await vitals({ timeoutMs: 5_000 })
+ .vital('slow', {
+ timeoutMs: 20,
+ probe: () => new Promise((resolve) => { setTimeout(() => resolve({ ok: true }), 5_000).unref?.(); }),
+ })
+ .capability('trade', { needs: ['slow'] })
+ .attest();
+
+ assert.equal(verdict.vital('slow').status, 'unknown');
+ assert.match(verdict.vital('slow').detail, /exceeded 20ms/);
+});
+
+test('a remedy function is handed the probe detail so the fix names real numbers', async () => {
+ const verdict = await vitals()
+ .vital('solvency', {
+ probe: () => ({ ok: false, detail: 'short by 0.0187 SOL', data: { deficit: 0.0187 } }),
+ remedy: ({ data }) => `send ${data.deficit} SOL to the arm wallet`,
+ })
+ .capability('trade', { needs: ['solvency'] })
+ .attest();
+
+ assert.deepEqual(verdict.remedies, ['send 0.0187 SOL to the arm wallet']);
+});
+
+test('a remedy that throws does not take down the attestation', async () => {
+ const verdict = await vitals()
+ .vital('solvency', { probe: down(), remedy: () => { throw new Error('bad template'); } })
+ .capability('trade', { needs: ['solvency'] })
+ .attest();
+
+ assert.equal(verdict.can.trade, false);
+ assert.equal(verdict.vital('solvency').remedy, null);
+ assert.deepEqual(verdict.remedies, []);
+});
+
+test('a healthy vital carries no remedy', async () => {
+ const verdict = await vitals()
+ .vital('solvency', { probe: up, remedy: 'fund it' })
+ .capability('trade', { needs: ['solvency'] })
+ .attest();
+
+ assert.equal(verdict.vital('solvency').remedy, null);
+});
+
+test('independent vitals at the same depth probe concurrently', async () => {
+ let peak = 0;
+ let active = 0;
+ const slow = () => new Promise((resolve) => {
+ active += 1;
+ peak = Math.max(peak, active);
+ setTimeout(() => { active -= 1; resolve({ ok: true }); }, 25).unref?.();
+ });
+
+ await vitals()
+ .vital('a', { probe: slow })
+ .vital('b', { probe: slow })
+ .vital('c', { probe: slow })
+ .capability('trade', { needs: ['a', 'b', 'c'] })
+ .attest();
+
+ assert.equal(peak, 3);
+});
+
+test('a dependent probes strictly after its dependency', async () => {
+ const order = [];
+ await vitals()
+ .vital('first', { probe: async () => { order.push('first'); return { ok: true }; } })
+ .vital('second', { needs: ['first'], probe: async () => { order.push('second'); return { ok: true }; } })
+ .capability('trade', { needs: ['second'] })
+ .attest();
+
+ assert.deepEqual(order, ['first', 'second']);
+});
+
+test('one root cause blocking several capabilities is reported once', async () => {
+ const verdict = await vitals()
+ .vital('deploy-fresh', { probe: down(), remedy: 'redeploy' })
+ .vital('cognition', { needs: ['deploy-fresh'], probe: up })
+ .vital('execution', { needs: ['deploy-fresh'], probe: up })
+ .capability('trade', { needs: ['cognition'] })
+ .capability('exit', { needs: ['execution'] })
+ .attest();
+
+ assert.equal(verdict.can.trade, false);
+ assert.equal(verdict.can.exit, false);
+ // The operator's work queue is one item, not two.
+ assert.deepEqual(verdict.rootCauses.map((r) => r.id), ['deploy-fresh']);
+ assert.deepEqual(verdict.remedies, ['redeploy']);
+});
+
+test('explain() reads as a causal chain from symptom to cause', async () => {
+ const verdict = await vitals({ agent: 'sniper-1' })
+ .vital('deploy-fresh', { probe: down('image is 16 days old'), remedy: 'redeploy the worker' })
+ .vital('cognition', { needs: ['deploy-fresh'], probe: up })
+ .capability('trade', { needs: ['cognition'] })
+ .attest();
+
+ const text = verdict.explain();
+ assert.match(text, /sniper-1: cannot trade because cognition is blocked, because deploy-fresh is down \(image is 16 days old\)/);
+ assert.match(text, /fix: redeploy the worker/);
+});
+
+test('a capability scoped to healthy vitals stays ready while another fails', async () => {
+ const verdict = await vitals()
+ .vital('solvency', { probe: up })
+ .vital('cognition', { probe: down() })
+ .capability('exit', { needs: ['solvency'] })
+ .capability('trade', { needs: ['solvency', 'cognition'] })
+ .attest();
+
+ // Closing a position needs no model. Failing to notice that is how a fleet
+ // gets marked fully dead while it can still get out of its open risk.
+ assert.equal(verdict.can.exit, true);
+ assert.equal(verdict.can.trade, false);
+ assert.equal(verdict.healthy, false);
+});
+
+test('a dependency cycle is a build error naming its members', async () => {
+ const chart = vitals()
+ .vital('a', { needs: ['b'], probe: up })
+ .vital('b', { needs: ['a'], probe: up })
+ .capability('trade', { needs: ['a'] });
+
+ await assert.rejects(() => chart.attest(), /cycle among \[a, b\]/);
+});
+
+test('an edge to an undeclared vital fails loudly with the name in it', async () => {
+ const chart = vitals().vital('a', { needs: ['ghost'], probe: up }).capability('trade', { needs: ['a'] });
+ await assert.rejects(() => chart.attest(), /vital "a" needs unknown vital "ghost"/);
+
+ const chart2 = vitals().vital('a', { probe: up }).capability('trade', { needs: ['ghost'] });
+ await assert.rejects(() => chart2.attest(), /capability "trade" needs unknown vital "ghost"/);
+});
+
+test('malformed declarations are rejected at build time', () => {
+ assert.throws(() => vitals().vital('a', {}), /needs a probe function/);
+ assert.throws(() => vitals().vital('', { probe: up }), /needs a string id/);
+ assert.throws(() => vitals().vital('a', { probe: up }).vital('a', { probe: up }), /duplicate vital "a"/);
+ assert.throws(() => vitals().vital('a', { probe: up }).capability('c', { needs: [] }), /non-empty needs array/);
+ assert.throws(
+ () => vitals().vital('a', { probe: up }).capability('c', { needs: ['a'] }).capability('c', { needs: ['a'] }),
+ /duplicate capability "c"/,
+ );
+});
+
+test('an aborted attestation marks the unrun probes unknown rather than passing them', async () => {
+ const controller = new AbortController();
+ controller.abort();
+ const verdict = await vitals()
+ .vital('a', { probe: up })
+ .capability('trade', { needs: ['a'] })
+ .attest({ signal: controller.signal });
+
+ assert.equal(verdict.vital('a').status, 'unknown');
+ assert.equal(verdict.can.trade, null);
+});
+
+test('toJSON is plain, serialisable, and carries the answer up front', async () => {
+ const verdict = await vitals({ agent: 'a1' })
+ .vital('solvency', { probe: down('empty'), remedy: 'fund it' })
+ .capability('trade', { needs: ['solvency'] })
+ .attest();
+
+ const json = JSON.parse(JSON.stringify(verdict));
+ assert.equal(json.agent, 'a1');
+ assert.equal(json.healthy, false);
+ assert.equal(json.can.trade, false);
+ assert.deepEqual(json.root_causes, ['solvency']);
+ assert.deepEqual(json.remedies, ['fund it']);
+ assert.equal(typeof json.at, 'string');
+});
+
+test('a boolean probe is accepted as shorthand', async () => {
+ const verdict = await vitals()
+ .vital('a', { probe: () => true })
+ .vital('b', { probe: () => false })
+ .capability('trade', { needs: ['a', 'b'] })
+ .attest();
+
+ assert.equal(verdict.vital('a').status, 'up');
+ assert.equal(verdict.vital('b').status, 'down');
+});
+
+test('a probe returning a non-result value is unknown, and keeps the value for debugging', async () => {
+ const verdict = await vitals()
+ .vital('a', { probe: () => 'yes' })
+ .capability('trade', { needs: ['a'] })
+ .attest();
+
+ assert.equal(verdict.vital('a').status, 'unknown');
+ assert.equal(verdict.vital('a').data, 'yes');
+});
+
+test('a deep chain reports the deepest cause, not the middle of the chain', async () => {
+ const verdict = await vitals()
+ .vital('billing', { probe: down('account on hold'), remedy: 'clear the billing hold' })
+ .vital('deploy', { needs: ['billing'], probe: up })
+ .vital('cognition', { needs: ['deploy'], probe: up })
+ .vital('decision', { needs: ['cognition'], probe: up })
+ .capability('trade', { needs: ['decision'] })
+ .attest();
+
+ assert.deepEqual(verdict.rootCauses.map((r) => r.id), ['billing']);
+ assert.equal(verdict.vital('deploy').status, 'blocked');
+ assert.equal(verdict.vital('decision').status, 'blocked');
+ assert.match(verdict.explain(), /fix: clear the billing hold/);
+});
+
+// ── block severity ───────────────────────────────────────────────────────────
+// Blocking on an unreadable dependency is not the same as blocking on a broken
+// one. Collapsing the two inverts the library's own "unread is not failed" rule
+// one level down the graph, and it reported an agent that had acted sixty
+// seconds earlier as definitively unable.
+
+test('a block behind an unreadable probe leaves the capability unknown, not unable', async () => {
+ const verdict = await vitals()
+ .vital('image', { probe: () => ({ ok: null, detail: 'build time unread' }) })
+ .vital('cognition', { needs: ['image'], probe: up })
+ .capability('trade', { needs: ['cognition'] })
+ .attest();
+
+ assert.equal(verdict.vital('cognition').status, 'blocked');
+ assert.equal(verdict.vital('cognition').blockedSeverity, 'unknown');
+ assert.equal(verdict.can.trade, null);
+});
+
+test('a block behind a real failure makes the capability unable', async () => {
+ const verdict = await vitals()
+ .vital('image', { probe: down('16 days old') })
+ .vital('cognition', { needs: ['image'], probe: up })
+ .capability('trade', { needs: ['cognition'] })
+ .attest();
+
+ assert.equal(verdict.vital('cognition').blockedSeverity, 'down');
+ assert.equal(verdict.can.trade, false);
+});
+
+test('block severity propagates through a chain of blocks', async () => {
+ const verdict = await vitals()
+ .vital('billing', { probe: down('on hold') })
+ .vital('deploy', { needs: ['billing'], probe: up })
+ .vital('cognition', { needs: ['deploy'], probe: up })
+ .capability('trade', { needs: ['cognition'] })
+ .attest();
+
+ assert.equal(verdict.vital('deploy').blockedSeverity, 'down');
+ assert.equal(verdict.vital('cognition').blockedSeverity, 'down');
+ assert.equal(verdict.can.trade, false);
+});
+
+test('one broken dependency outranks an unreadable sibling when both block a vital', async () => {
+ const verdict = await vitals()
+ .vital('unreadable', { probe: () => ({ ok: null }) })
+ .vital('broken', { probe: down('really down') })
+ .vital('dependent', { needs: ['unreadable', 'broken'], probe: up })
+ .capability('trade', { needs: ['dependent'] })
+ .attest();
+
+ assert.equal(verdict.vital('dependent').blockedSeverity, 'down');
+ assert.equal(verdict.can.trade, false);
+});
+
+test('an unreadable probe never makes a healthy sibling capability unable', async () => {
+ const verdict = await vitals()
+ .vital('image', { probe: () => ({ ok: null }) })
+ .vital('rpc', { probe: up })
+ .vital('cognition', { needs: ['image'], probe: up })
+ .capability('enter', { needs: ['cognition', 'rpc'] })
+ .capability('exit', { needs: ['rpc'] })
+ .attest();
+
+ // Exiting never depended on the unreadable reading, so it stays definitively
+ // ready. A fleet that can still close its open risk must not read as dead.
+ assert.equal(verdict.can.exit, true);
+ assert.equal(verdict.can.enter, null);
+});
+
+test('a blocked vital carries no blockedSeverity when it was actually probed', async () => {
+ const verdict = await vitals()
+ .vital('a', { probe: up })
+ .vital('b', { probe: down() })
+ .capability('trade', { needs: ['a', 'b'] })
+ .attest();
+
+ assert.equal(verdict.vital('a').blockedSeverity, null);
+ assert.equal(verdict.vital('b').blockedSeverity, null);
+});
diff --git a/scripts/agent-vitals.mjs b/scripts/agent-vitals.mjs
new file mode 100644
index 000000000..d690688c1
--- /dev/null
+++ b/scripts/agent-vitals.mjs
@@ -0,0 +1,141 @@
+#!/usr/bin/env node
+// scripts/agent-vitals.mjs
+//
+// "Why is this armed agent not doing anything?" answered in one command.
+//
+// Attests every armed sniper arm against live systems (strategies table,
+// position ledger, Solana RPC, launch feed, model chain, deployed image) and
+// prints the ROOT blocker per arm plus the command that fixes it. Symptoms are
+// suppressed: an arm blocked by a dead model chain that is itself caused by a
+// stale deployment reports the deployment, not the chain.
+//
+// Read-only. It never signs, funds, deploys, or closes anything.
+//
+// Usage:
+// npm run agent:vitals # attest the mainnet fleet
+// node scripts/agent-vitals.mjs --json # machine-readable
+// node scripts/agent-vitals.mjs --no-llm # skip the model probe (it costs a token or two)
+// node scripts/agent-vitals.mjs --network devnet
+//
+// Env: DATABASE_URL (.env.local). SOLANA_RPC_URL and Google credentials are
+// optional: without them those probes report `unknown`, never a false verdict.
+
+import { readFileSync } from 'node:fs';
+
+for (const file of ['.env.local', '.env']) {
+ try {
+ for (const line of readFileSync(new URL(`../${file}`, import.meta.url), 'utf8').split('\n')) {
+ const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)$/);
+ if (m && !process.env[m[1]]) process.env[m[1]] = m[2].replace(/^["']|["']$/g, '');
+ }
+ } catch { /* file absent: env may already be exported */ }
+}
+
+const args = process.argv.slice(2);
+const asJson = args.includes('--json');
+const skipLlm = args.includes('--no-llm');
+const networkArg = args.indexOf('--network');
+const network = networkArg >= 0 && args[networkArg + 1] ? args[networkArg + 1] : 'mainnet';
+
+if (!process.env.DATABASE_URL) {
+ console.error('DATABASE_URL is not set. It lives in .env.local (Neon) or on the Cloud Run service.');
+ process.exit(1);
+}
+
+const { attestFleet, summarizeFleet, SNIPER_SERVICE } = await import('../api/_lib/agent-vitals/sniper-probe.js');
+
+// The in-process image probe needs a platform credential (metadata server or a
+// service-account key). An operator running this from a laptop usually has only
+// a gcloud CLI login, so read it from gcloud when that is what is available.
+// This is the single most valuable reading in the report and losing it to a
+// credential shape would gut the tool.
+async function imageBuiltAtFromGcloud() {
+ try {
+ const { execFile } = await import('node:child_process');
+ const { promisify } = await import('node:util');
+ const { stdout } = await promisify(execFile)('gcloud', [
+ 'artifacts', 'docker', 'images', 'list',
+ `us-central1-docker.pkg.dev/aerial-vehicle-466722-p5/workers/${SNIPER_SERVICE}`,
+ '--sort-by=~CREATE_TIME', '--limit=1',
+ '--project', 'aerial-vehicle-466722-p5',
+ '--format=value(createTime)',
+ ], { timeout: 90_000 });
+ const line = String(stdout).trim().split('\n')[0];
+ return line && Number.isFinite(Date.parse(line)) ? new Date(line).toISOString() : null;
+ } catch {
+ return null;
+ }
+}
+
+const { probeDeployedImageAge } = await import('../api/_lib/agent-vitals/sniper-probe.js');
+const imageBuiltAt = (await probeDeployedImageAge()) ?? (await imageBuiltAtFromGcloud());
+
+const fleet = await attestFleet({ network, includeCognition: !skipLlm, imageBuiltAt });
+const summary = summarizeFleet(fleet.arms);
+
+if (asJson) {
+ console.log(JSON.stringify({ ...fleet, arms: fleet.arms.map((a) => ({ ...a, verdict: a.verdict.toJSON() })), summary }, null, 2));
+ process.exit(0);
+}
+
+const MARK = { ready: 'CAN ACT', unable: 'CANNOT ACT', unknown: 'UNKNOWN' };
+const statusOf = (arm) => (arm.verdict.can.enter === true ? 'ready' : arm.verdict.can.enter === false ? 'unable' : 'unknown');
+
+console.log(`\nAGENT VITALS · ${network} · ${fleet.at.slice(0, 16).replace('T', ' ')} UTC`);
+console.log('Capability attestation, not liveness: can each armed arm actually open a position right now?\n');
+
+console.log('SHARED READINGS (taken once for the whole fleet)');
+console.log(` RPC ${fleet.shared.rpc.ok === true ? 'up' : fleet.shared.rpc.ok === false ? 'DOWN' : 'unknown'} ${fleet.shared.rpc.detail}`);
+console.log(` model ${fleet.shared.cognition.ok === true ? 'up' : fleet.shared.cognition.ok === false ? 'DOWN' : 'unknown'} ${fleet.shared.cognition.detail}`);
+console.log(` feed newest launch ${fleet.shared.feed_fresh_at ? `at ${fleet.shared.feed_fresh_at.slice(0, 16).replace('T', ' ')}` : 'unread'}`);
+console.log(` image ${fleet.shared.image_built_at ? `built ${fleet.shared.image_built_at.slice(0, 10)}` : 'unread (no Google credential in this environment)'}`);
+
+console.log('\nPER ARM');
+for (const arm of fleet.arms) {
+ const status = statusOf(arm);
+ console.log(`\n ${arm.name}${arm.label ? ` [${arm.label}]` : ''} ${MARK[status]}`);
+ console.log(` ${arm.activity}${arm.stalled ? ' (STALLED)' : ''}`);
+ if (status === 'ready') {
+ // Nothing is broken, so the entry filters are the answer. Saying that
+ // plainly stops an operator hunting infrastructure that is already fine.
+ console.log(arm.stalled
+ ? ' every precondition is up: this arm is capable and its entry filters are simply not matching'
+ : ' every precondition is up');
+ } else {
+ for (const root of arm.verdict.rootCauses) {
+ console.log(` ROOT ${root.id} is ${root.status}${root.detail ? `: ${root.detail}` : ''}`);
+ if (root.remedy) console.log(` fix: ${root.remedy}`);
+ }
+ const symptoms = arm.verdict.vitals.filter((v) => v.status === 'blocked').map((v) => v.id);
+ if (symptoms.length) console.log(` (blocked downstream, not probed: ${symptoms.join(', ')})`);
+ }
+ if (arm.verdict.can.exit !== true) console.log(' cannot close open positions either');
+ // The ledger gets a vote. If it disproves the verdict, say so here rather
+ // than letting a wrong model quietly win the argument against reality.
+ if (arm.contradiction) console.log(` CONTRADICTION ${arm.contradiction}`);
+}
+
+console.log('\nFLEET');
+console.log(` ${summary.ready}/${summary.total} arms can open a position now · ${summary.unable} cannot · ${summary.unknown} unreadable`);
+console.log(` ${summary.canExit}/${summary.total} can still close an open position`);
+if (summary.stalledButCapable.length) {
+ console.log(` Capable but silent (filters, not faults): ${summary.stalledButCapable.join(', ')}`);
+}
+
+if (summary.contradictions.length) {
+ console.log('\nMODEL CONTRADICTED BY THE LEDGER');
+ for (const line of summary.contradictions) console.log(` ${line}`);
+}
+
+if (summary.rootCauses.length) {
+ console.log('\nWORK QUEUE (deduplicated across the fleet, widest blast radius first)');
+ for (const cause of summary.rootCauses) {
+ console.log(` ${cause.id} blocks ${cause.arms.length} arm${cause.arms.length === 1 ? '' : 's'}: ${cause.arms.join(', ')}`);
+ // One shared cause does not mean one shared fix. Five starved wallets are
+ // five transfers, so every distinct remedy is printed, not a representative.
+ for (const remedy of cause.remedies) console.log(` ${remedy}`);
+ }
+} else {
+ console.log('\nWORK QUEUE empty: nothing is blocking the fleet.');
+}
+console.log('');
diff --git a/tests/agent-vitals-sniper-chart.test.js b/tests/agent-vitals-sniper-chart.test.js
new file mode 100644
index 000000000..c00f84dfd
--- /dev/null
+++ b/tests/agent-vitals-sniper-chart.test.js
@@ -0,0 +1,198 @@
+// The sniper fleet's vitals chart: the wiring that decides WHY an armed arm is
+// not trading. Every case here is a real verdict this chart got wrong at some
+// point during the 2026-08-28 investigation, kept so it cannot get them wrong
+// again. Pure: readings are injected, so nothing here touches a network or a DB.
+import { describe, it, expect } from 'vitest';
+import {
+ sniperChart,
+ entryActivity,
+ contradiction,
+ STALE_ENTRY_MS,
+ STALE_FEED_MS,
+ STALE_IMAGE_MS,
+ OBSERVED_ACTING_MS,
+} from '../api/_lib/agent-vitals/sniper-chart.js';
+
+const NOW = Date.parse('2026-08-28T03:00:00.000Z');
+const ago = (ms) => new Date(NOW - ms).toISOString();
+
+/** A fully healthy set of readings for a rules arm. Individual tests break one thing. */
+const healthy = (overrides = {}) => ({
+ wallet: 'Wa11etAddre55',
+ balanceSol: 0.5,
+ feedFreshAt: ago(60_000),
+ imageBuiltAt: ago(2 * 86_400_000),
+ rpc: { ok: true, detail: 'slot 1' },
+ cognition: { ok: true, detail: 'model answered' },
+ ...overrides,
+ // Merged last and explicitly: spreading `overrides` over a pre-built
+ // `strategy` replaces the whole row, so a test overriding one field would
+ // silently drop `enabled` and assert against a disarmed arm.
+ strategy: {
+ agent_id: 'arm-1',
+ label: 'rules-arm',
+ enabled: true,
+ kill_switch: false,
+ decision_mode: 'rules',
+ per_trade_lamports: 2_000_000, // 0.002 SOL
+ ...overrides.strategy,
+ },
+});
+
+const attest = (input) => sniperChart(input, { now: NOW }).attest();
+
+describe('sniperChart', () => {
+ it('attests a fully healthy rules arm as able to enter', async () => {
+ const verdict = await attest(healthy());
+ expect(verdict.can.enter).toBe(true);
+ expect(verdict.can.exit).toBe(true);
+ expect(verdict.rootCauses).toEqual([]);
+ });
+
+ it('names a starved wallet and the exact SOL that fixes it', async () => {
+ const verdict = await attest(healthy({ balanceSol: 0.000001 }));
+
+ expect(verdict.can.enter).toBe(false);
+ expect(verdict.rootCauses.map((r) => r.id)).toEqual(['solvency']);
+ // The remedy has to carry the real number and the real address, or an
+ // operator has to go and derive both before they can act on it.
+ expect(verdict.remedies[0]).toMatch(/^send \d+\.\d{4} SOL to Wa11etAddre55/);
+ });
+
+ it('treats a shrunk wallet as able to trade, because the executor does', async () => {
+ // resolveEntrySize shrinks rather than skips: an arm trading below its
+ // configured size is working, and calling that a failure marks a live arm dead.
+ // 0.02 SOL against a 0.05 SOL configured size: too little for the full
+ // entry, enough for a smaller one once fee and ATA-rent headroom is kept.
+ const verdict = await attest(healthy({ balanceSol: 0.02, strategy: { per_trade_lamports: 50_000_000 } }));
+ expect(verdict.vital('solvency').status).toBe('up');
+ expect(verdict.vital('solvency').detail).toMatch(/shrunk/);
+ });
+
+ it('reports an unread balance as unknown, never as a starved wallet', async () => {
+ const verdict = await attest(healthy({ balanceSol: null }));
+ expect(verdict.vital('solvency').status).toBe('unknown');
+ // "cannot say" must not become "cannot act": one RPC blip would otherwise
+ // page an operator to a fleet that is entirely fine.
+ expect(verdict.can.enter).toBeNull();
+ });
+
+ it('reports a disarmed arm as a choice, not an infrastructure fault', async () => {
+ const verdict = await attest(healthy({ strategy: { enabled: false } }));
+ expect(verdict.rootCauses.map((r) => r.id)).toEqual(['armed']);
+ expect(verdict.vital('armed').detail).toMatch(/disabled/);
+ });
+
+ it('reports an engaged kill switch distinctly from a disabled arm', async () => {
+ const verdict = await attest(healthy({ strategy: { enabled: true, kill_switch: true } }));
+ expect(verdict.vital('armed').detail).toMatch(/kill switch/);
+ });
+
+ it('does not make a rules arm depend on the deployment or the model chain', async () => {
+ // The bug this pins: an early revision made every arm depend on deploy
+ // freshness and reported an arm that had entered a position two minutes
+ // earlier, on that very image, as definitively unable.
+ const verdict = await attest(healthy({ imageBuiltAt: ago(60 * 86_400_000), cognition: { ok: false } }));
+ expect(verdict.can.enter).toBe(true);
+ expect(verdict.vital('cognition').status).toBe('up');
+ expect(verdict.vital('cognition').detail).toMatch(/no model required/);
+ });
+
+ it('blocks an llm arm on a stale image and blames the image, not the model', async () => {
+ const verdict = await attest(healthy({
+ strategy: { decision_mode: 'llm' },
+ imageBuiltAt: ago(STALE_IMAGE_MS + 86_400_000),
+ cognition: { ok: false, detail: 'every rung failed' },
+ }));
+
+ expect(verdict.can.enter).toBe(false);
+ // The model chain is a symptom of the stale image, so the image is the answer.
+ expect(verdict.rootCauses.map((r) => r.id)).toEqual(['deploy-fresh']);
+ expect(verdict.vital('cognition').status).toBe('blocked');
+ expect(verdict.remedies[0]).toMatch(/gcloud builds submit/);
+ });
+
+ it('blames the model chain directly when the image is current', async () => {
+ const verdict = await attest(healthy({
+ strategy: { decision_mode: 'llm' },
+ cognition: { ok: false, detail: 'every rung failed' },
+ }));
+
+ expect(verdict.rootCauses.map((r) => r.id)).toEqual(['cognition']);
+ expect(verdict.remedies[0]).toMatch(/provider credits|billing hold/);
+ });
+
+ it('reports a stale launch feed as its own cause', async () => {
+ const verdict = await attest(healthy({ feedFreshAt: ago(STALE_FEED_MS + 60_000) }));
+ expect(verdict.rootCauses.map((r) => r.id)).toEqual(['feed']);
+ expect(verdict.can.enter).toBe(false);
+ });
+
+ it('keeps exit available when only entry-side preconditions fail', async () => {
+ // A fleet that can still close its open risk is not dead, and collapsing
+ // that distinction tells an operator their positions are stranded when
+ // they are not.
+ const verdict = await attest(healthy({ balanceSol: 0, feedFreshAt: ago(10 * 86_400_000) }));
+ expect(verdict.can.enter).toBe(false);
+ expect(verdict.can.exit).toBe(true);
+ });
+
+ it('makes exit unavailable when the RPC is the thing that is down', async () => {
+ const verdict = await attest(healthy({ rpc: { ok: false, detail: 'no slot' } }));
+ expect(verdict.can.exit).toBe(false);
+ expect(verdict.can.enter).toBe(false);
+ });
+
+ it('reports several independent causes at once without inventing an order', async () => {
+ const verdict = await attest(healthy({ balanceSol: 0, feedFreshAt: ago(10 * 86_400_000) }));
+ expect(verdict.rootCauses.map((r) => r.id).sort()).toEqual(['feed', 'solvency']);
+ });
+
+ it('explains itself as a causal sentence an operator can paste into a channel', async () => {
+ const verdict = await attest(healthy({
+ strategy: { decision_mode: 'llm', label: 'llm-kimi' },
+ imageBuiltAt: ago(STALE_IMAGE_MS + 86_400_000),
+ }));
+ expect(verdict.explain()).toMatch(/llm-kimi: cannot enter because cognition is blocked, because deploy-fresh is down/);
+ });
+});
+
+describe('entryActivity', () => {
+ it('marks an arm that has never attempted an entry as stalled', () => {
+ expect(entryActivity(null, { now: NOW })).toMatchObject({ stalled: true, ageMs: null });
+ });
+
+ it('marks a long-silent arm as stalled', () => {
+ const activity = entryActivity(ago(STALE_ENTRY_MS + 86_400_000), { now: NOW });
+ expect(activity.stalled).toBe(true);
+ expect(activity.detail).toMatch(/last entry attempt \d+ days ago/);
+ });
+
+ it('does not mark a recently active arm as stalled', () => {
+ expect(entryActivity(ago(60_000), { now: NOW }).stalled).toBe(false);
+ });
+});
+
+describe('contradiction', () => {
+ it('flags a verdict the ledger disproves', () => {
+ // The whole point: a health model that cannot notice it is wrong will be
+ // trusted right up until it matters.
+ const text = contradiction(false, ago(2 * 60_000), { now: NOW });
+ expect(text).toMatch(/attested UNABLE but this arm attempted an entry 2 min ago/);
+ });
+
+ it('stays silent when the model and the ledger agree', () => {
+ expect(contradiction(true, ago(2 * 60_000), { now: NOW })).toBeNull();
+ expect(contradiction(false, ago(OBSERVED_ACTING_MS + 60_000), { now: NOW })).toBeNull();
+ expect(contradiction(false, null, { now: NOW })).toBeNull();
+ });
+
+ it('does not flag an unknown verdict, which claims nothing to contradict', () => {
+ expect(contradiction(null, ago(60_000), { now: NOW })).toBeNull();
+ });
+
+ it('accepts a capability status string as well as can.enter', () => {
+ expect(contradiction('unable', ago(60_000), { now: NOW })).toMatch(/attested UNABLE/);
+ expect(contradiction('ready', ago(60_000), { now: NOW })).toBeNull();
+ });
+});