From cf1cc70ba0e81edb29b99769299b60edc7b36270 Mon Sep 17 00:00:00 2001 From: p-diogo Date: Fri, 4 Dec 2026 20:41:24 +0000 Subject: [PATCH 1/2] test(mcp): staging E2E for fact ids on DataEdge V2 (#908) Co-Authored-By: Claude Code --- mcp/CHANGELOG.md | 3 + mcp/tests/e2e/fact-ids-staging-e2e.mjs | 1582 ++++++++++++++++++++++++ 2 files changed, 1585 insertions(+) create mode 100644 mcp/tests/e2e/fact-ids-staging-e2e.mjs diff --git a/mcp/CHANGELOG.md b/mcp/CHANGELOG.md index 208fa4b0..e35c2ae2 100644 --- a/mcp/CHANGELOG.md +++ b/mcp/CHANGELOG.md @@ -10,6 +10,9 @@ ### Changed - **Forget only when the user asks (internal#866).** The agent-facing forget guidance now says it with MUST and NEVER: call `totalreclaw_forget` only when the user asks to forget, delete or remove a memory. When the user corrects or contradicts a stored memory (a new car, a new city), NEVER forget the old one: call `totalreclaw_remember` with `replaces=` (keeps the history), or leave it to auto-extraction. If unsure whether the user wants a memory removed, ask. Changed text: the forget tool description, the server instructions (new "Forgetting" section; other sections shortened to stay at 2,000 characters), the usage guide, and the NanoClaw skill files (`skill-nanoclaw/SKILL.md`, `skill-nanoclaw/mcp/SKILL.md`). The pinned-memory confirmation text is unchanged. No tool behaviour changed. The tools/list golden is regenerated for the new forget description. Tests: `tests/forget-guidance.test.ts`. +### Added +- **Staging E2E script for fact ids on DataEdge V2 ([#908](https://github.com/graphprotocol/totalreclaw/issues/908)).** `mcp/tests/e2e/fact-ids-staging-e2e.mjs` drives the built server over stdio against the staging relay with a throwaway account: `--self-test` checks its own safety code offline, `--report ` is the staging run (pin, retype, set_scope, unpin, `replaces`, forget, and refused ids, by bare id and by `:`). No product code changed. + ## [3.7.0] - 2026-12-03 ### Changed diff --git a/mcp/tests/e2e/fact-ids-staging-e2e.mjs b/mcp/tests/e2e/fact-ids-staging-e2e.mjs new file mode 100644 index 00000000..074b7e6b --- /dev/null +++ b/mcp/tests/e2e/fact-ids-staging-e2e.mjs @@ -0,0 +1,1582 @@ +#!/usr/bin/env node +/** + * Staging E2E for fact ids on DataEdge V2 (totalreclaw#908). + * + * What it proves + * -------------- + * Drives the BUILT MCP server (mcp/dist/index.js) over stdio with the MCP client SDK, the way a host does, against + * the STAGING relay, chain and subgraph, and checks that the fact-id code of #901 / #903 works on DataEdge V2. The V2 + * subgraph keys a fact by `:`; V1 keys it by the bare payload id. So every tool must name a + * fact by its payload id, accept `:` in any address case, refuse another account's id before any read or + * write, change nothing for a fact the subgraph does not return, and confirm a forget only by an inactive row. + * `mcp/tests/fact-ids-v1-v2.test.ts` runs the same flows on an in-memory subgraph (tests/helpers/fake-subgraph.ts); + * this script is the run on a real one. + * + * Steps: S0 preflight (refuse to write unless billing says chain 100 + the staging V2 DataEdge), S1 remember A-D, + * S2 recall, S3 pin by bare id, S4 retype by `:`, S5 set_scope by the upper-case sender form, + * S6 unpin by `:`, S7 remember with `replaces`, S8 forget by `:`, S9 forget of a pinned + * memory (asks first), S10 another account's id is refused, S11 a missing id changes nothing, S12 cleanup. + * + * Safety rules + * ------------ + * - STAGING ONLY. The relay URL is the constant STAGING_URL, passed to the child in TOTALRECLAW_SERVER_URL: the + * server's own default is PRODUCTION when that variable is unset. The child's environment is built here (no + * TOTALRECLAW_DATA_EDGE_ADDRESS, no TOTALRECLAW_SUBGRAPH_URL: it must take the DataEdge from the staging relay's + * billing, as a host's server does). Never api.totalreclaw.xyz. + * - The script refuses to write (exit 2, before any remember) unless the staging relay's billing reports chain_id 100 + * and data_edge_address equal (any case) to the staging V2 DataEdge. The production DataEdge, or anything else, stops it. + * - THROWAWAY ACCOUNT ONLY. A fresh 12-word phrase is generated in memory and never printed, logged, written to a + * file or put in argv. It reaches the child only through its environment (TOTALRECLAW_RECOVERY_PHRASE). + * - Everything data-derived that this script prints or writes (tool results, the child's stderr, paths, the + * report) goes through clean(): secret shapes are masked (32 bytes of hex that is not a tx hash the run saw in a + * tx_hash field, bearer and JWT tokens, key = value pairs), then redact() replaces the full phrase and every + * phrase word of 3+ letters with [REDACTED], whatever their case. Only lines made of this script's own fixed + * words (PASS, FAIL, a check name, the final line) print as they are. + * - The child gets a fresh temp directory as HOME (also its cwd, state dir, credentials path and cache path). At the + * end every file under it is scanned: the run FAILS if 3 consecutive phrase words appear in any of them. Then the + * directory is deleted. The embedding model is not in it: transformers keeps its cache next to its own package + * (mcp/node_modules/@huggingface/transformers/.cache/), whatever HOME is. + * - Never printed: the phrase, bearer tokens, auth keys, private keys, confirm tokens. Wallet and Smart Account + * addresses, payload ids and tx hashes are printed. + * - ONE server process per run. The relay allows about one /v1/register per IP per 19 minutes, and a server registers + * at startup. The client is pinned to the legacy `initialize` handshake: an SDK v2 client in `auto` negotiation mode + * spawns a second, probe copy of the server. + * + * Usage + * ----- + * cd mcp && npm run build + * node tests/e2e/fact-ids-staging-e2e.mjs --self-test # offline, no network, no child process + * node tests/e2e/fact-ids-staging-e2e.mjs --report # staging (without --report the report is printed) + * + * `--self-test` is offline whatever else is on the command line. + * + * Exit codes: 0 every check passed; 1 a check failed (a phrase hit in the temp dir included); 2 refused to write; + * 130 interrupted (Ctrl-C or a kill: the server is closed and the temp directory deleted first). + * If a run fails on a `/v1/register` rate limit, wait 20 minutes before the next one. + * + * Port of the safety design of python/tests/e2e/fact_ids_staging_e2e.py. + */ + +import fs from 'node:fs'; +import { createRequire } from 'node:module'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +import { Client } from '@modelcontextprotocol/client'; +import { StdioClientTransport } from '@modelcontextprotocol/client/stdio'; +import { generateMnemonic } from '@scure/bip39'; +import { wordlist } from '@scure/bip39/wordlists/english.js'; + +// ── constants ──────────────────────────────────────────────────────────────── + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const MCP_ROOT = path.resolve(HERE, '..', '..'); +const SERVER_ENTRY = path.join(MCP_ROOT, 'dist', 'index.js'); + +const STAGING_URL = 'https://api-staging.totalreclaw.xyz'; +const STAGING_HOST = 'api-staging.totalreclaw.xyz'; +const GNOSIS_CHAIN_ID = 100; +// contracts/deployed-addresses.json: the DataEdge the staging subgraph indexes since 2026-12-03. +const STAGING_V2_DATA_EDGE = '0xd3dce61edbcfc76c781a617bed722bbdc23a57c6'; +const PROD_DATA_EDGE = '0xc445af1d4eb9fce4e1e61fe96ea7b8febf03c5ca'; + +const OTHER = '0x' + '77'.repeat(20); // an account that is not this one +const MISSING = '00000000-0000-4000-8000-000000000000'; + +/** What a tool gets and returns: the payload id, never the subgraph's `:` row id. */ +const PAYLOAD_ID = /^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/; +const ADDRESS = /^0x[0-9a-f]{40}$/; +const TX_HASH = /^0x[0-9a-f]{64}$/; + +const CLIENT_NAME = 'totalreclaw-fact-ids-staging-e2e'; +const CLIENT_VERSION = '1.0.0'; +/** `X-TotalReclaw-Client`: the relay buckets analytics on the part before the first `/`. */ +const CLIENT_ID = `mcp-server:${CLIENT_NAME}`; + +const STARTUP_TIMEOUT_MS = 180_000; // register + billing lookup + Smart Account derivation, then `initialize` +const TOOL_TIMEOUT_MS = 600_000; // a slow UserOp and a 30 s index confirm exceed the SDK's 60 s default +const INDEX_TIMEOUT_MS = 120_000; // one write to show on the subgraph + +const EXIT_OK = 0; +const EXIT_FAILED = 1; +const EXIT_REFUSED = 2; + +// ── redaction ──────────────────────────────────────────────────────────────── + +/** Every phrase this process ever used (only ever one). */ +const PHRASES = new Set(); + +/** The full phrase(s) and every phrase word of 3+ letters, longest first. */ +function fragments() { + const out = new Set(); + for (const p of PHRASES) { + out.add(p); + for (const w of p.split(/\s+/)) if (w.length >= 3) out.add(w); + } + return [...out].sort((a, b) => b.length - a.length); +} + +const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + +/** What redact() leaves alone: the [REDACTED] marker, addresses (0x + 40 hex), tx hashes (0x + 64 hex), payload ids. */ +const KEPT = /\[REDACTED\]|0x[0-9a-f]{64}\b|0x[0-9a-f]{40}\b|\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi; + +/** + * `text` with the full phrase and every phrase word of 3+ letters replaced by [REDACTED], whatever their case and + * whatever they are glued to ("word", "Word", "prefix_word_suffix"). Addresses, tx hashes, payload ids and the + * [REDACTED] marker itself are put aside and returned unchanged: a phrase word made of hex letters (dead, face, + * ...) must not cut an address in two, and "red" is a dictionary word, so redacting a redacted line is a no-op. + * Display only. Nothing a check parses goes through here. + */ +function redact(text, frags = fragments()) { + let out = String(text); + if (frags.length === 0) return out; + // One pattern for all fragments, longest first, applied in ONE pass: a marker one fragment produced can then + // never be matched again by a shorter fragment ("red" is a dictionary word). + const pattern = new RegExp([...frags].sort((a, b) => b.length - a.length) + .map((f) => escapeRe(f).replace(/ /g, '\\s+')).join('|'), 'gi'); + const kept = []; + let rest = out.replace(KEPT, (m) => { + kept.push(m); + return `\u0000${kept.length - 1}\u0000`; + }); + rest = rest.replace(pattern, '[REDACTED]'); + out = rest.replace(/\u0000(\d+)\u0000/g, (_, i) => kept[Number(i)]); + return out; +} + +/** + * Secret shapes that nothing from the server (a tool result, a line of stderr, an error body) may carry into the + * log or the report: 32 bytes of hex (an auth key, a signing key: the same shape as a tx hash), a bearer or JWT + * token, a `key = value` pair. The only 32-byte hex values shown are tx hashes the run itself read from a tool + * result's `tx_hash` field (`knownTx`). Display only. + */ +const knownTx = new Set(); +const hex32 = (m) => (knownTx.has(m) ? m : ''); +const SECRET_SHAPES = [ + [/\b0x[0-9a-fA-F]{64}\b/g, hex32], + [/(? 'Bearer [REDACTED]'], + [/\beyJ[A-Za-z0-9_-]{8,}(?:\.[A-Za-z0-9_-]*)*/g, () => '[REDACTED]'], + [/((?:auth|private|secret|api|signing|recovery)[_-]?key|secret|token|password|mnemonic|phrase|seed)(["']?\s*[:=]\s*["']?)[^\s"',}]{4,}/gi, + (_m, key, sep) => `${key}${sep}[REDACTED]`], +]; + +function scrubSecrets(text) { + return SECRET_SHAPES.reduce((acc, [re, to]) => acc.replace(re, to), String(text)); +} + +function phraseTriples() { + const out = []; + for (const p of PHRASES) { + const w = p.toLowerCase().split(/\s+/); + for (let i = 0; i + 3 <= w.length; i++) out.push(w.slice(i, i + 3)); + } + return out; +} + +/** + * Files under `root` that hold 3 consecutive words of any phrase this process used, in any case and with anything + * but letters between the words (spaces, newlines, the `","` of a JSON array). Every file is read as bytes: a + * UTF-16 copy has a NUL between the letters, so those are dropped first. + */ +function scanForPhrase(root) { + const triples = phraseTriples(); + if (triples.length === 0) return []; + const re = new RegExp(triples.map((t) => t.map(escapeRe).join('[^a-z]+')).join('|'), 'i'); + const hits = []; + const walk = (dir) => { + for (const ent of fs.readdirSync(dir, { withFileTypes: true })) { + const file = path.join(dir, ent.name); + if (ent.isDirectory()) { + walk(file); + } else if (ent.isFile()) { + let data; + try { + data = fs.readFileSync(file, 'latin1'); + } catch { + hits.push(`${path.relative(root, file)} (unreadable)`); + continue; + } + if (re.test(data.replace(/\0/g, ''))) hits.push(path.relative(root, file)); + } + } + }; + try { + walk(root); + } catch (err) { + hits.push(`(could not list ${root}: ${err instanceof Error ? err.message : String(err)})`); + } + return hits; +} + +// ── small helpers ──────────────────────────────────────────────────────────── + +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** + * Poll until `fn()` answers something truthy (subgraph indexing lag). A `fn` that throws is polled again. Returns + * that answer, `false` at the timeout, and `false` at once once a signal interrupted the run. A relay outage does + * not cut a wait short: a short one must be ridden out, and the steps after it are gated separately. + */ +async function waitFor(fn, timeoutMs = INDEX_TIMEOUT_MS, intervalMs = 5_000) { + const deadline = Date.now() + timeoutMs; + for (;;) { + if (interruptHandled) return false; + try { + const value = await fn(); + if (value) return value; + } catch { + /* not yet */ + } + const left = deadline - Date.now(); + if (left <= 0) return false; + await sleep(Math.min(intervalMs, left)); + } +} + +/** + * What a tool call answered: `json` is `content[0]` parsed (the payload every handler puts there), `raw` all the + * text blocks, `isError` the MCP error flag. `json` is `undefined` when the first block is not JSON. + */ +function toolJson(res) { + const blocks = Array.isArray(res?.content) ? res.content : []; + const texts = blocks.filter((c) => c && c.type === 'text' && typeof c.text === 'string').map((c) => c.text); + let json; + try { + json = texts.length ? JSON.parse(texts[0]) : undefined; + } catch { + json = undefined; + } + if (!json || typeof json !== 'object') json = undefined; + return { + json, + raw: texts.join('\n'), + isError: res?.isError === true, + }; +} + +/** `:` with any sender, or anything else glued in front of a payload id with a ":". */ +const COMPOSITE_ID = /[0-9a-f]{40}:[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}|\S:[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}/gi; + +/** Every distinct id with a ":" in it, anywhere in a parsed result (nested objects and arrays included). */ +function compositeIds(value) { + const found = new Set(); + const walk = (v) => { + if (typeof v === 'string') { + for (const m of v.matchAll(COMPOSITE_ID)) found.add(m[0]); + } else if (Array.isArray(v)) { + v.forEach(walk); + } else if (v && typeof v === 'object') { + Object.values(v).forEach(walk); + } + }; + walk(value); + return [...found]; +} + +/** The result fields that name one fact, or a list of facts. */ +const ID_KEYS = ['fact_id', 'memory_id', 'new_fact_id', 'new_memory_id', 'replaced_fact_id', 'existing_fact_id']; + +/** `where.key=value` for every id field that is not a payload id (an empty id on a gate stop is not one). */ +function idFieldsOffFormat(value) { + const bad = []; + const walk = (v, where) => { + if (Array.isArray(v)) { + v.forEach((x, i) => walk(x, `${where}[${i}]`)); + return; + } + if (!v || typeof v !== 'object') return; + for (const [k, x] of Object.entries(v)) { + if (ID_KEYS.includes(k)) { + if (typeof x === 'string' && x !== '' && !PAYLOAD_ID.test(x)) bad.push(`${where}.${k}=${x}`); + } else if (k === 'fact_ids' && Array.isArray(x)) { + x.forEach((id, i) => { + if (!PAYLOAD_ID.test(String(id))) bad.push(`${where}.fact_ids[${i}]=${String(id)}`); + }); + } else { + walk(x, `${where}.${k}`); + } + } + }; + walk(value, '$'); + return bad; +} + +/** + * The write gate of S0. Write only when billing says chain 100 and the staging V2 DataEdge, in any case. Anything + * else (the production DataEdge, the retired staging V1, another chain, a missing or malformed field) refuses. + */ +function preflightDecision(billing) { + const chain = billing?.chain_id; + const edge = typeof billing?.data_edge_address === 'string' ? billing.data_edge_address.toLowerCase() : ''; + const chainOk = chain === GNOSIS_CHAIN_ID; + const edgeOk = edge === STAGING_V2_DATA_EDGE; + return { ok: chainOk && edgeOk, chainOk, edgeOk, chain, edge }; +} + +/** Deep copy with every `confirm_token` replaced, for display. */ +function maskTokens(value) { + if (Array.isArray(value)) return value.map(maskTokens); + if (value && typeof value === 'object') { + const out = {}; + for (const [k, v] of Object.entries(value)) { + out[k] = k === 'confirm_token' && typeof v === 'string' ? '' : maskTokens(v); + } + return out; + } + return value; +} + +/** A compact, printable form of a result or an exception (confirm tokens masked). */ +function short(value, limit = 500) { + let text; + if (value instanceof Error) { + text = `Error: ${value.message}`; + } else { + try { + text = typeof value === 'string' ? value : JSON.stringify(maskTokens(value)) ?? String(value); + } catch { + text = String(value); + } + } + text = String(text).replace(/\s+/g, ' '); + return text.length <= limit ? text : `${text.slice(0, limit)}…`; +} + +// ── output and checks ──────────────────────────────────────────────────────── + +/** + * What every data-derived string passes through before it is printed or written: secret shapes masked, then the + * phrase redacted. + */ +function clean(text) { + return redact(scrubSecrets(text)); +} + +/** + * Every data-derived string the script prints (a tool result, a line of the server's stderr, a path) goes through + * here, and so through clean(). The one exception is a line made only of this script's own fixed words (PASS, + * FAIL, a step or check name, the final line) next to a detail that was redacted on its way in: `say`. A word of + * the phrase can be in such a line only by coincidence, and redact() works on parts of words. + */ +function out(line) { + try { + // Masked and redacted first, cut after: a secret that starts before the cut must not come out in part. + process.stdout.write(`${clean(String(line)).slice(0, 4_000)}\n`); + } catch { + /* a closed pipe ends the run anyway */ + } +} + +function say(prefix, detail = '') { + try { + process.stdout.write(`${prefix}${detail}\n`); + } catch { + /* idem */ + } +} + +const checks = []; +const notes = []; + +function check(step, name, cond, detail) { + const pass = Boolean(cond); + const got = pass ? '' : clean(short(detail)); + checks.push({ step, name, pass, ...(pass ? {} : { detail: got }) }); + say(`${pass ? 'PASS' : 'FAIL'} [${step}] ${name}${pass ? '' : ` -- got: ${got}`}`); + return pass; +} + +function note(step, text) { + const line = clean(short(text, 700)); + notes.push({ step, text: line }); + say(`NOTE [${step}] `, line); +} + +function notRun(step, why) { + const got = clean(`not run: ${why}`); + checks.push({ step, name: 'the step ran', pass: false, detail: got }); + say(`FAIL [${step}] `, got); +} + +// ── child environment ──────────────────────────────────────────────────────── + +/** + * The whole environment of the server process. Built here, nothing inherited from this process (the SDK adds only + * HOME / PATH / USER and the like, and HOME below wins). No TOTALRECLAW_DATA_EDGE_ADDRESS, no TOTALRECLAW_SUBGRAPH_URL: + * the server must take the DataEdge from the staging relay's billing, as a host's does. + */ +function childEnv(tmp, phrase) { + const env = { + HOME: tmp, + TMPDIR: path.join(tmp, 'tmp'), + TOTALRECLAW_SERVER_URL: STAGING_URL, + TOTALRECLAW_STATE_DIR: path.join(tmp, 'state'), + TOTALRECLAW_CREDENTIALS_PATH: path.join(tmp, 'credentials.json'), + TOTALRECLAW_CACHE_PATH: path.join(tmp, 'cache'), + }; + if (new URL(env.TOTALRECLAW_SERVER_URL).hostname !== STAGING_HOST) { + throw new Error('refusing to start the server: the relay URL is not the staging one'); + } + return phrase ? { ...env, TOTALRECLAW_RECOVERY_PHRASE: phrase } : env; +} + +// ── offline self-test ──────────────────────────────────────────────────────── + +async function selfTest() { + const results = []; + const that = (name, ok) => { + results.push(Boolean(ok)); + say(`${ok ? 'PASS' : 'FAIL'} [self-test] ${name}`); + }; + + const phrase = generateMnemonic(wordlist, 128); + PHRASES.add(phrase); + const words = phrase.split(' '); + // A phrase word left in `text`. The [REDACTED] marker and ids are not text: "red" and "act" are dictionary words. + const leaks = (text) => { + const plain = text.replace(/\[REDACTED\]/gi, '').replace(/0x[0-9a-f]+\b|\b[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}\b/gi, '').toLowerCase(); + return words.filter((w) => w.length >= 3 && plain.includes(w.toLowerCase())); + }; + try { + // redact(): the full phrase, single words, words inside other text, in any case. + const lines = [ + `traceback: mnemonic='${phrase}'`, + ...words.map((w) => `word=${w}`), + ...words.map((w) => `prefix_${w}_suffix and ${w.toUpperCase()} and ${w[0].toUpperCase()}${w.slice(1)}.`), + `two words ${words[0]} ${words[1]} and the whole thing again: ${phrase.split(/\s+/).join(' ')}`, + ]; + const leaked = lines.flatMap((line) => leaks(redact(line))); + that('redact(): no phrase word survives (full phrase, single words, words inside other text, any case)', leaked.length === 0); + + // Identifiers are random hex, never words: they print as they are, even when a phrase word is hex-shaped. + const idText = `sa 0xd3Dce61eDBCFc76c781a617BEd722bBDC23a57C6 tx 0xdeadbeeffacefeed${'0'.repeat(48)}` + + ' id 0000face-0000-4000-8000-deadbeef0000'; + const hexWords = ['dead', 'beef', 'face', 'feed']; + that('redact(): an address, a tx hash and a payload id stay intact next to redacted text', + redact(`mnemonic ${hexWords.join(' ')} ${idText}`, hexWords) === `mnemonic [REDACTED] [REDACTED] [REDACTED] [REDACTED] ${idText}`); + that('redact(): with nothing to hide, text is returned unchanged', redact(idText) === idText); + that('redact(): redacting a redacted line changes nothing (the marker contains the word "red")', + redact(redact(`already ${words.join(' ')} gone`)) === redact(`already ${words.join(' ')} gone`) && + redact('red [REDACTED] red', ['red']) === '[REDACTED] [REDACTED] [REDACTED]'); + const secretLine = `key=0x${'ab'.repeat(32)} auth ${'cd'.repeat(32)} Authorization: Bearer abc.DEF-123 xyz ` + + `eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.c2lnbmF0dXJl private_key: "0x1234567890"`; + const scrubbed = scrubSecrets(secretLine); + that('scrubSecrets(): a 32-byte hex, a bearer token, a JWT and a key = value pair are masked', + !scrubbed.includes('ab') && !scrubbed.includes('cd'.repeat(4)) && !/Bearer abc/.test(scrubbed) && !scrubbed.includes('eyJ') && + !scrubbed.includes('0x1234567890') && scrubSecrets('tx=0xabc123 sa 0xd3Dce61eDBCFc76c781a617BEd722bBDC23a57C6 total_reclaw_token=5') === + 'tx=0xabc123 sa 0xd3Dce61eDBCFc76c781a617BEd722bBDC23a57C6 total_reclaw_token=5'); + const aTx = `0x${'ab'.repeat(32)}`; + const maskedBefore = scrubSecrets(aTx) === ''; + knownTx.add(aTx); + const x1 = `Bearer abc token=${'ab'.repeat(32)} mnemonic='${phrase}' q ${words[0].toUpperCase()} z1 0x${'cd'.repeat(32)}`; + const cleaned = clean(x1); + that('scrubSecrets(): a tx hash the run saw in a tx_hash field is shown, any other 32-byte hex is not', + maskedBefore && scrubSecrets(`tx ${aTx}`) === `tx ${aTx}`); + // The fixed words of the sample (Bearer, token, mnemonic, hex32) are not the text under test: some are + // dictionary words, and redact() works on parts of words. + const sampleFixed = cleaned.replace(/bearer|token|mnemonic|hex32|q|z1/gi, ''); + that('clean(): a bearer token, a key = value and a 32-byte hex are gone from one line', + !/Bearer abc/.test(cleaned) && !/token=ab/.test(cleaned) && !cleaned.includes('cd'.repeat(4)) && + (cleaned.match(/\[REDACTED\]/g) ?? []).length >= 3 && cleaned.endsWith('')); + that('clean(): every phrase word is gone from that line', leaks(sampleFixed).length === 0 && !cleaned.includes('ab'.repeat(4))); + knownTx.clear(); + that('clean(): cleaning a cleaned string changes nothing (whatever the phrase)', clean(clean(x1)) === clean(x1)); + + // Leak scan: a clean temp dir, then 3 consecutive words in a file. + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'tr-mcp-fact-ids-selftest-')); + try { + fs.mkdirSync(path.join(tmp, 'state')); + fs.writeFileSync(path.join(tmp, 'state', 'innocent.txt'), 'nothing to see here, just a cache and some ids'); + const cleanHits = scanForPhrase(tmp); + that('leak scan: a temp dir without phrase words has no hits', cleanHits.length === 0); + fs.writeFileSync(path.join(tmp, 'state', 'leak.txt'), `oops ${words[3]} ${words[4]} ${words[5]}`); + const caught = scanForPhrase(tmp); + that('leak scan: 3 consecutive phrase words in a file are caught', caught.length === 1 && caught[0] === path.join('state', 'leak.txt')); + fs.writeFileSync(path.join(tmp, 'state', 'leak.json'), JSON.stringify({ mnemonic: words.slice(0, 4) })); + const caughtJson = scanForPhrase(tmp); + that('leak scan: the words in a JSON array (quotes between them) are caught too', + caughtJson.includes(path.join('state', 'leak.json'))); + fs.writeFileSync(path.join(tmp, 'state', 'leak.json'), JSON.stringify({ a: words.slice(2, 3) })); + const twoWords = scanForPhrase(tmp).filter((h) => h.endsWith('leak.json')); + that('leak scan: two words alone are not a hit', twoWords.length === 0); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + + // The write gate of S0. + const v2Upper = STAGING_V2_DATA_EDGE.toUpperCase().replace('0X', '0x'); + that('preflight: chain 100 + the staging V2 DataEdge (any case) is allowed', + preflightDecision({ chain_id: 100, data_edge_address: STAGING_V2_DATA_EDGE }).ok && + preflightDecision({ chain_id: 100, data_edge_address: v2Upper }).ok); + that('preflight: the production DataEdge is refused', + !preflightDecision({ chain_id: 100, data_edge_address: PROD_DATA_EDGE }).ok); + const refused = [ + { chain_id: 100, data_edge_address: '0xe7a4d2677b686e13775ba9092631089e35f0bb91' }, // the retired staging V1 + { chain_id: 84532, data_edge_address: STAGING_V2_DATA_EDGE }, + { chain_id: '100', data_edge_address: STAGING_V2_DATA_EDGE }, + { chain_id: 100 }, { chain_id: 100, data_edge_address: 'not-an-address' }, + { chain_id: 100, data_edge_address: `${STAGING_V2_DATA_EDGE}00` }, {}, + ]; + that('preflight: any other chain, any other DataEdge, a missing or malformed field is refused', + refused.every((b) => !preflightDecision(b).ok)); + + // waitFor(): polls until truthy, gives up at the timeout. + let polls = 0; + const late = await waitFor(() => (++polls >= 3 ? 'indexed' : false), 5_000, 1); + that('waitFor(): polls until the function is truthy', late === 'indexed' && polls === 3); + let failing = 0; + const never = await waitFor(() => { failing++; throw new Error('not yet'); }, 30, 5); + that('waitFor(): a function that keeps failing gives up at the timeout', never === false && failing >= 2); + + // What a tool call returns. + const parsed = toolJson({ + content: [{ type: 'text', text: '{"memories":[{"fact_id":"x"}]}' }, { type: 'text', text: 'block' }], + structuredContent: { memories: [{ fact_id: 'x' }] }, + }); + const failed = toolJson({ content: [{ type: 'text', text: 'not json' }], isError: true }); + that('toolJson(): content[0] is the JSON payload; the other blocks are kept; isError is seen', + parsed.json?.memories?.[0]?.fact_id === 'x' && parsed.isError === false && parsed.raw.includes('block') && + failed.isError === true && failed.json === undefined && failed.raw === 'not json'); + + // Id shapes. + const id = '0190ab00-cdef-7000-8000-000000000001'; // with letters, so the case matters + const dirty = { results: [{ fact_id: id, memory_id: `0x${'ab'.repeat(20)}:${id}` }], text: `id ${id.replace(/-/g, '')}:${id}` }; + that('compositeIds(): finds a `:` wherever it is, and nothing in a clean result', + compositeIds(dirty).length === 2 && compositeIds({ fact_id: id, fact_ids: [id], error: 'x' }).length === 0); + that('idFieldsOffFormat(): an id field that is not a payload id is reported', + idFieldsOffFormat({ new_fact_id: id, fact_ids: [id] }).length === 0 && + idFieldsOffFormat({ fact_id: `0x${'ab'.repeat(20)}:${id}`, results: [{ memory_id: 'nope' }] }).length === 2); + that('payload id pattern: lowercase UUID only', PAYLOAD_ID.test(id) && !PAYLOAD_ID.test(id.toUpperCase()) && !PAYLOAD_ID.test(`${id}:`)); + + // A recall that carries an error is no answer, even with an empty `memories` next to it (the server's own error shape). + const outage = [ + { + content: [{ type: 'text', text: JSON.stringify({ + memories: [], latency_ms: 3, error: 'Failed to recall memories: boom', mode: 'subgraph', + }) }], + }, + { + content: [{ type: 'text', text: JSON.stringify({ + error: 'Read quota exceeded', error_code: 'read_quota_exceeded', reads_paused_until: 'x', mode: 'subgraph', + }) }], + }, + { isError: true, content: [{ type: 'text', text: JSON.stringify({ error: 'not_configured' }) }] }, + { content: [{ type: 'text', text: 'not json' }] }, + ]; + const lists = []; + for (const res of outage) lists.push((await recall({ callTool: async () => res }, 'q')).list); + recallState.failures = 0; + for (let i = 0; i < RECALL_OUTAGE_CALLS - 1; i++) await recall({ callTool: async () => outage[i % 2] }, 'q'); + const stillPolling = !recallOut(); + await recall({ callTool: async () => outage[0] }, 'q'); + const outageCalls = recallState.failures; + const wasOut = recallOut(); + const inOutage = await waitFor(() => 'polled', 5_000, 1); + const probeDown = await recallIsBack({ callTool: async () => outage[0] }); + const probeUp = await recallIsBack({ callTool: async () => ({ content: [{ type: 'text', text: '{"memories":[]}' }] }) }); + that('recall: an error, an error_code, an isError or a non-JSON answer is "no answer" (null), never "nothing stored"', + lists.every((l) => l === null)); + that('recall: after enough silent calls the breaker trips, a wait in progress still polls, and one answered recall ends the outage', + stillPolling && outageCalls === RECALL_OUTAGE_CALLS && wasOut && inOutage === 'polled' && + probeDown === false && probeUp === true && !recallOut() && recallState.failures === 0); + + // Arguments: --self-test is offline whatever else is on the command line. + const plain = (o) => JSON.stringify(o); + that('parseArgs(): --self-test is the offline self-test, with or without --report, in any order', + plain(parseArgs(['--self-test'])) === plain({ mode: 'self-test', reportPath: null }) && + plain(parseArgs(['--self-test', '--report', 'x.json'])) === plain({ mode: 'self-test', reportPath: null }) && + plain(parseArgs(['--report', 'x.json', '--self-test'])) === plain({ mode: 'self-test', reportPath: null }) && + parseArgs(['--report', '--self-test']).mode === 'self-test'); + that('parseArgs(): --report is the staging run with that file; no argument is the staging run with the report ' + + 'printed; anything else is the usage line', + plain(parseArgs(['--report', 'x.json'])) === plain({ mode: 'staging', reportPath: path.resolve('x.json') }) && + plain(parseArgs([])) === plain({ mode: 'staging', reportPath: null }) && + parseArgs(['--report']).mode === 'usage' && parseArgs(['--bogus']).mode === 'usage' && parseArgs(['--help']).mode === 'usage'); + + // What goes out is masked first and cut after: a secret that starts before the cut must not come out in part. + const written = []; + const realWrite = process.stdout.write.bind(process.stdout); + const capture = (chunk) => { + written.push(String(chunk)); + return true; + }; + process.stdout.write = capture; + try { + out(`${'x'.repeat(3_990)} 0x${'cd'.repeat(32)} then Bearer abcdefghijklmnop.qrstuv`); + } finally { + process.stdout.write = realWrite; + } + const printed = written.join(''); + that('out(): a line is masked before it is cut, so no part of a secret past the cut is printed', + !printed.includes('cdcd') && !printed.includes('abcdefghijklmnop') && printed.length <= 4_001); + written.length = 0; + process.stdout.write = capture; + try { + printReport(`${'y'.repeat(100)}\n`.repeat(130)); + } finally { + process.stdout.write = realWrite; + } + that('printReport(): a long report is printed whole, line by line', written.join('').replace(/\n/g, '').length === 100 * 130); + + // A pinned-memory result "asks" only when it asks for THIS confirmation, with a token, and wrote nothing. + that('askedFor(): true only for a result that asks for this confirmation and carries a token, with no write', + askedFor({ confirmation_required: 'pinned_unpin', confirm_token: 'abc123' }, 'pinned_unpin') && + !askedFor({ success: false, fact_id: id, error: `Fact not found: ${id}` }, 'pinned_unpin') && + !askedFor({ deleted_count: 0, fact_ids: [], not_found: true }, 'pinned_forget') && + !askedFor({ confirmation_required: 'pinned_unpin', confirm_token: 'abc123', tx_hash: `0x${'ab'.repeat(32)}` }, 'pinned_unpin') && + !askedFor({ confirmation_required: 'pinned_forget', confirm_token: 'abc123' }, 'pinned_unpin') && + !askedFor({ confirmation_required: 'pinned_unpin', confirm_token: '' }, 'pinned_unpin') && + !askedFor(undefined, 'pinned_unpin') && !askedFor({ confirmation_required: 'pinned_unpin' }, 'pinned_unpin')); + + // The child environment. + const env = childEnv(path.join(os.tmpdir(), 'x'), phrase); + that('child env: staging relay, the phrase, and a temp HOME for everything the server writes', + env.TOTALRECLAW_SERVER_URL === STAGING_URL && env.HOME === path.join(os.tmpdir(), 'x') && + env.TOTALRECLAW_RECOVERY_PHRASE === phrase && env.TOTALRECLAW_STATE_DIR.startsWith(env.HOME) && + env.TOTALRECLAW_CREDENTIALS_PATH.startsWith(env.HOME) && env.TOTALRECLAW_CACHE_PATH.startsWith(env.HOME) && + !('TOTALRECLAW_DATA_EDGE_ADDRESS' in env) && !('TOTALRECLAW_SUBGRAPH_URL' in env) && + !('TOTALRECLAW_SELF_HOSTED' in env) && childEnv(path.join(os.tmpdir(), 'x'), '').TOTALRECLAW_RECOVERY_PHRASE === undefined); + } finally { + PHRASES.clear(); + } + + const failedCount = results.filter((ok) => !ok).length; + say(`== self-test: ${results.length - failedCount} passed, ${failedCount} failed`); + return failedCount === 0 ? EXIT_OK : EXIT_FAILED; +} + +// ── the staging run ────────────────────────────────────────────────────────── + +/** + * What the command line asks for. `--self-test` is the offline self-test whatever else is on the line: it must + * never start the staging run. `--report ` is the staging run with a report file; no argument is the staging + * run with the report printed; anything else is the usage line. + */ +function parseArgs(argv) { + if (argv.includes('--self-test')) return { mode: 'self-test', reportPath: null }; + const reportAt = argv.indexOf('--report'); + if (reportAt !== -1) { + const value = argv[reportAt + 1]; + const ok = typeof value === 'string' && value !== '' && !value.startsWith('--'); + return ok ? { mode: 'staging', reportPath: path.resolve(value) } : { mode: 'usage', reportPath: null }; + } + return argv.length === 0 ? { mode: 'staging', reportPath: null } : { mode: 'usage', reportPath: null }; +} + +/** A report without a file is printed line by line (each line goes through out(), whole). */ +function printReport(text) { + for (const line of String(text).split('\n')) out(line); +} + +/** True when a result on a pinned memory is the ask itself: this confirmation, a token, and no write. */ +function askedFor(json, category) { + return Boolean(json) && json.confirmation_required === category && + typeof json.confirm_token === 'string' && json.confirm_token !== '' && json.tx_hash === undefined; +} + +/** + * Start the server: ONE process, the legacy `initialize` handshake (an SDK v2 client in `auto` mode would spawn a + * second, probe copy), a fresh temp HOME, and its stderr handed to `onLine` line by line (unredacted: `onLine` + * prints through clean()). The phrase goes to the child through its environment only. + */ +async function connectServer({ tmp, phrase, onLine, onClosed }) { + const env = childEnv(tmp, phrase); + const transport = new StdioClientTransport({ + command: process.execPath, + args: [SERVER_ENTRY], + env, + stderr: 'pipe', + cwd: tmp, + }); + // Attached before `connect()` spawns the child, so no early line is lost. A line can arrive in two chunks. + let pending = ''; + const flush = (rest) => { + pending += rest; + const lines = pending.split('\n'); + pending = lines.pop(); + for (const line of lines) if (line.trim() !== '') onLine(line); + }; + transport.stderr?.on('data', (chunk) => flush(String(chunk))); + transport.onerror = (err) => onLine(`[transport] ${err?.message ?? err}`); + transport.onclose = () => { + if (pending.trim() !== '') onLine(pending); + onClosed?.(); + }; + // Known to the signal handler from here on: the child exists (with the phrase) before the handshake does. + live.transport = transport; + const client = new Client({ name: CLIENT_NAME, version: CLIENT_VERSION }, { capabilities: {}, versionNegotiation: { mode: 'legacy' } }); + live.client = client; + try { + await client.connect(transport, { timeout: STARTUP_TIMEOUT_MS }); + } catch (err) { + // The child is already running, with the phrase in its environment: never leave it behind. + live.client = null; + live.transport = null; + await transport.close().catch(() => {}); + throw err; + } + // The child has its copy; the env object this process keeps does not need one any more. + env.TOTALRECLAW_RECOVERY_PHRASE = ''; + return { client, transport }; +} + +async function callTool(client, name, args = {}) { + try { + const res = await client.callTool({ name, arguments: args }, { timeout: TOOL_TIMEOUT_MS }); + return { ok: true, name, args, ...toolJson(res) }; + } catch (err) { + return { ok: false, name, args, error: String(err?.message ?? err), json: undefined, raw: '', isError: true }; + } +} + +/** A tool result as a short line for the log: never the confirm token, never a key. */ +const shown = (r) => (r.ok ? r.json ?? r.raw : `tool call failed: ${r.error}`); + +/** `results[0]` of a totalreclaw_remember envelope, or `undefined`. */ +const firstResult = (r) => (Array.isArray(r.json?.results) ? r.json.results[0] : undefined); + +/** + * Recall calls in a row that did not answer, and the last thing it said. A relay read outage must not turn every + * step into a row of 2-minute timeouts: once this reaches RECALL_OUTAGE_CALLS, a step that needs recall does not + * run and says why. Each such step tries one recall first, so a relay that answers again is seen at once, and a + * wait already in progress keeps its own timeout (a short outage is ridden out). + */ +const recallState = { failures: 0, lastError: '' }; +const RECALL_OUTAGE_CALLS = 6; +const recallOut = () => recallState.failures >= RECALL_OUTAGE_CALLS; +const outageWhy = () => `recall has not answered for ${recallState.failures} calls in a row (${recallState.lastError || 'no answer'})`; + +/** While the breaker is tripped, before a step that needs recall: one more recall. True when the relay answers again. */ +async function recallIsBack(client) { + await recall(client, 'totalreclaw vault'); + return !recallOut(); +} + +/** + * One totalreclaw_recall. `list` is the memories, or `null` when the recall did not answer: that is "unknown", + * never "nothing stored". The server's error paths answer with an `error` (and the generic one also with an empty + * `memories`), and a read denial with an `error_code`: none of them is a statement about the vault. + */ +async function recall(client, query) { + const r = await callTool(client, 'totalreclaw_recall', { query, k: 50 }); + const j = r.json; + const answered = r.ok && !r.isError && Array.isArray(j?.memories) && j.error === undefined && j.error_code === undefined; + if (answered) { + recallState.failures = 0; + recallState.lastError = ''; + } else { + recallState.failures++; + recallState.lastError = r.ok ? short({ error: j?.error, error_code: j?.error_code, relay_message: j?.relay_message }, 200) : short(r.error, 200); + } + const list = answered ? j.memories : null; + const ids = list ? list.map((m) => m.fact_id) : null; + return { ...r, list, ids }; +} + +function runCtx({ client, authKeyHex, facts, serverFlags }) { + // S0 fills in `sa`: the Smart Account, lower case. + const ctx = { + client, + sa: '', + authKeyHex, + facts, + serverFlags, + cur: {}, // label -> the payload id that holds the fact now (pin, retype, set_scope and unpin write a new id) + old: {}, // label -> the payload id the last rewrite replaced (now a tombstone) + lost: {}, // label -> why the fact can no longer be followed by its id + ever: new Set(), // every payload id this run created + tx: [], + }; + /** `:` as the V2 subgraph keys a fact: the sender in lower case. */ + ctx.colon = (id) => `${ctx.sa}:${id}`; + /** The same id with the sender in upper case but a lower-case `0x`. */ + ctx.colonUpper = (id) => `${ctx.sa.toUpperCase().replace('0X', '0x')}:${id}`; + /** Record that `label` can no longer be named: the steps that need it then say why they cannot run. */ + ctx.lose = (label, why) => { + delete ctx.cur[label]; + ctx.lost[label] = why; + }; + ctx.track = (...ids) => { + for (const id of ids) if (typeof id === 'string' && PAYLOAD_ID.test(id)) ctx.ever.add(id); + }; + ctx.rememberedTx = (...values) => { + for (const v of values) { + if (typeof v === 'string' && TX_HASH.test(v) && !ctx.tx.includes(v)) { + ctx.tx.push(v); + knownTx.add(v); + } + } + }; + return ctx; +} + +const isPayloadId = (id) => typeof id === 'string' && PAYLOAD_ID.test(id); + +/** + * Poll the subgraph through recall until `id` is back with `pred` true. Returns the memory, or `false`. An id that + * is not a payload id is never "found": the check that uses this must fail, not pass by accident. + */ +const waitRecall = (client, id, pred = () => true) => + isPayloadId(id) + ? waitFor(async () => { + const r = await recall(client, 'totalreclaw vault'); + const hit = r.ids?.includes(id) ? r.list.find((m) => m.fact_id === id) : null; + return hit && pred(hit) ? hit : false; + }, INDEX_TIMEOUT_MS, 5_000) + : Promise.resolve(false); + +/** + * Poll until `id` is no longer returned by recall (a tombstone, indexed). Returns `true`, or `false`: `false` too + * when recall does not answer (unknown is not "gone") or `id` is not a payload id. + */ +const waitGone = (client, id, timeoutMs = INDEX_TIMEOUT_MS) => + isPayloadId(id) + ? waitFor(async () => { + const r = await recall(client, 'totalreclaw vault'); + return r.ids && !r.ids.includes(id) ? true : false; + }, timeoutMs, 5_000) + : Promise.resolve(false); + +/** What must not change when a refused call names a fact: its identity and its metadata (not the ranking scores). */ +const shapeOf = (m) => + m && typeof m === 'object' + ? { + fact_id: m.fact_id, memory_id: m.memory_id, fact_text: m.fact_text, type: m.type, scope: m.scope, + source: m.source, importance: m.importance, pinned: m.pinned, + } + : m; + +/** + * totalreclaw_remember for one fact. If the store-time gate answers already_stored / possible_duplicate, the plan + * is to ask again with force: the texts here are made to be separate facts. + */ +async function remember(client, text, extra = {}) { + let r = await callTool(client, 'totalreclaw_remember', { fact: text, ...extra }); + const item = firstResult(r); + if (item && (item.action === 'already_stored' || item.action === 'possible_duplicate') && !extra.force) { + note('remember', `the store-time gate answered ${item.action} (similarity ${item.similarity}); asking again with force`); + r = await callTool(client, 'totalreclaw_remember', { fact: text, ...extra, force: true }); + } + return { r, item: firstResult(r) }; +} + +/** + * Call a tool on a pinned memory: the first call must stop with `confirmation_required` and a confirm_token; + * after the token's minimum age the same call with the token goes through. `second` is `null` when the first + * call did not ask. `onAsked` runs between the two calls: what must be observed about the untouched fact + * ("still pinned", "still active") is observed there, before the change. + */ +async function withConfirm(client, name, args, category, onAsked) { + const first = await callTool(client, name, args); + if (!askedFor(first.json, category)) return { first, second: null }; + if (onAsked) await onAsked(first); + await sleep(confirmMinAgeMs() + 1_000); + return { first, second: await callTool(client, name, { ...args, confirm_token: first.json.confirm_token }) }; +} + +let _confirmMinAgeMs; +/** `CONFIRM_TOKEN_MIN_AGE_MS` of the built server (mcp/dist/pii.js). */ +function confirmMinAgeMs() { + if (_confirmMinAgeMs === undefined) { + try { + const pii = createRequire(import.meta.url)(path.join(MCP_ROOT, 'dist', 'pii.js')); + _confirmMinAgeMs = Number(pii.CONFIRM_TOKEN_MIN_AGE_MS); + } catch { + _confirmMinAgeMs = NaN; + } + if (!Number.isFinite(_confirmMinAgeMs) || _confirmMinAgeMs < 0) _confirmMinAgeMs = 5_000; + } + return _confirmMinAgeMs; +} + +/** The account's auth key, the same derivation the server uses (cli/setup.ts deriveAuthKey). In memory only. */ +function deriveAuthKeyHex(phrase) { + const core = createRequire(import.meta.url)('@totalreclaw/core'); + const key = core.deriveKeysFromMnemonic(phrase.trim())?.auth_key; + if (typeof key !== 'string' || !/^[0-9a-f]{64}$/.test(key)) throw new Error('could not derive the auth key'); + return key; +} + +async function fetchBilling(ctx) { + const url = `${STAGING_URL}/v1/billing/status?wallet_address=${encodeURIComponent(ctx.sa)}`; + try { + const resp = await fetch(url, { + method: 'GET', + headers: { Authorization: `Bearer ${ctx.authKeyHex}`, 'Content-Type': 'application/json', 'X-TotalReclaw-Client': CLIENT_ID }, + redirect: 'error', // never follow a redirect to another host + signal: AbortSignal.timeout(20_000), + }); + const text = await resp.text(); + let json; + try { + json = JSON.parse(text); + } catch { + json = undefined; + } + return { ok: resp.ok, status: resp.status, json, body: resp.ok ? undefined : text.slice(0, 300) }; + } catch (err) { + return { ok: false, status: 0, error: String(err?.message ?? err) }; + } +} + +const billingView = (b) => + b && typeof b === 'object' + ? { chain_id: b.chain_id, data_edge_address: b.data_edge_address, tier: b.tier } + : b; + +/** Nothing an agent needs to see again from a refusal: just the `error` text and the flags. */ +const refusalView = (r) => r.json && typeof r.json === 'object' + ? { error: r.json.error, success: r.json.success, deleted_count: r.json.deleted_count, not_found: r.json.not_found } + : shown(r); + +// ── steps ──────────────────────────────────────────────────────────────────── + +async function s0Preflight(ctx, report) { + const step = 'S0 preflight'; + // The server listens on stdio only after its startup (register, billing lookup, Smart Account derivation). + let acct = null; + const ready = await waitFor(async () => { + acct = await callTool(ctx.client, 'totalreclaw_account'); + if (acct.json?.wallet_address) return acct; + // Registration failed at startup and billing cannot know this wallet: waiting will not help. + return ctx.serverFlags.registerFailed && acct.json?.error ? { refused: true } : false; + }, STARTUP_TIMEOUT_MS, 3_000); + if (!ready?.json?.wallet_address) { + check(step, 'the server is configured and reports its Smart Account', false, acct); + if (ctx.serverFlags.registerFailed) { + note(step, 'the server could not register with the relay (its stderr says so). ' + + 'After a /v1/register rate limit, wait 20 minutes before another run.'); + } + return EXIT_REFUSED; + } + const sa = String(ready.json.wallet_address).toLowerCase(); + ctx.sa = sa; + report.smart_account = sa; + report.tier = ready.json.tier; + report.server = ctx.serverFlags.version ?? null; + // Nothing is written through an account the relay does not know (a failed /v1/register, a rate limit included). + if (!check(step, 'the server registered this account with the relay', !ctx.serverFlags.registerFailed, + 'its stderr reports a failed /v1/register: after a rate limit, wait 20 minutes before another run')) { + return EXIT_REFUSED; + } + note(step, `server ${ctx.serverFlags.name ?? '?'} ${ctx.serverFlags.version ?? '?'}, ` + + `${ctx.serverFlags.toolCount ?? '?'} tools; tier ${String(ready.json.tier)}`); + + const billing = await fetchBilling(ctx); + const b = billing.json; + const d = preflightDecision(b); + report.chain_id = b?.chain_id ?? null; + report.data_edge = typeof b?.data_edge_address === 'string' ? b.data_edge_address.toLowerCase() : null; + note(step, `billing: ${short(billing.ok ? billingView(b) : { status: billing.status, error: billing.error, body: billing.body })}`); + const chainOk = check(step, 'billing reports chain 100 (Gnosis)', d.chainOk, billing.ok ? billingView(b) : billing); + const edgeOk = check(step, 'billing reports the staging V2 DataEdge (not the production one)', d.edgeOk, billing.ok ? billingView(b) : billing); + if (!check(step, 'the Smart Account is an address', ADDRESS.test(sa), sa)) return EXIT_REFUSED; + return chainOk && edgeOk ? EXIT_OK : EXIT_REFUSED; +} + +async function s1Remember(ctx) { + const step = 'S1 remember'; + const results = []; + for (const label of ['A', 'B', 'C', 'D']) { + const { r, item } = await remember(ctx.client, ctx.facts[label].text); + results.push(r); + const id = item?.fact_id; + const stored = check(step, `${label} is stored and its id matches the payload id pattern`, + item?.success === true && typeof id === 'string' && PAYLOAD_ID.test(id) && (item.action === 'created'), item ?? shown(r)); + if (stored) { + ctx.cur[label] = id; + ctx.track(id); + ctx.rememberedTx(item.tx_hash); + note(step, `${label} ${id} tx ${item.tx_hash ?? '(none)'}`); + } + } + const dirty = results.flatMap((r) => [...compositeIds(r.json).map((x) => `composite id ${x}`), ...idFieldsOffFormat(r.json)]); + check(step, 'no id with a ":" in any result', results.every((r) => r.ok) && dirty.length === 0, dirty.length ? dirty : results.map((r) => r.json)); + return results.every((r) => r.ok) && ['A', 'B', 'C', 'D'].every((l) => ctx.cur[l]) ? EXIT_OK : EXIT_FAILED; +} + +async function s2Recall(ctx) { + const step = 'S2 recall'; + const a = ctx.cur.A; + if (!a) return notRun(step, ctx.lost.A ?? `A was not stored`), EXIT_FAILED; + // Indexing lag: wait until a recall for A's text returns A's id. + const seen = await waitFor(async () => { + const r = await recall(ctx.client, ctx.facts.A.query); + return r.ids?.includes(a) ? r : false; + }, INDEX_TIMEOUT_MS, 5_000); + check(step, 'A is indexed: a recall for its text returns its id', Boolean(seen), + seen ? `${seen.ids.length} memories back` : 'not returned within the index timeout'); + + const recalls = []; + for (const label of ['A', 'B', 'C', 'D']) recalls.push([label, await recall(ctx.client, ctx.facts[label].query)]); + const off = recalls.flatMap(([label, r]) => [ + ...compositeIds(r.json).map((x) => `${label}: composite id ${x}`), + ...idFieldsOffFormat(r.json), + ...(r.ids ?? []).filter((id) => !PAYLOAD_ID.test(id)).map((id) => `${label}: id ${id}`), + ]); + check(step, 'every id recall returns is a payload id', recalls.every(([, r]) => r.ok && r.list !== null) && off.length === 0, + off.length ? off : recalls.map(([, r]) => shown(r))); + const missing = recalls + .filter(([label, r]) => !r.ids?.includes(ctx.cur[label])) + .map(([label, r]) => `${label} ${ctx.cur[label]} (${short(shown(r), 200)})`); + check(step, 'A, B, C and D are all found by their text', missing.length === 0, missing); + ctx.track(...(recalls.flatMap(([, r]) => r.ids ?? []))); + return missing.length === 0 && off.length === 0 ? EXIT_OK : EXIT_FAILED; +} + +/** After a rewrite: the new id is what recall returns, the old one is gone. */ +async function settledChecks(ctx, step, label, pred, what) { + const old = ctx.old[label]; + const cur = ctx.cur[label]; + const hit = await waitRecall(ctx.client, cur, pred); + check(step, `recall shows ${label}'s new id with ${what}`, Boolean(hit), + hit ? { id: hit.fact_id, type: hit.type, scope: hit.scope, pinned: hit.pinned } + : 'not returned as expected within the index timeout'); + const gone = await waitGone(ctx.client, old); + check(step, `the old ${label} id is no longer active (recall does not return it)`, Boolean(gone), + gone ? old : `${old ?? '(no old id recorded)'} still returned`); + return Boolean(hit) && Boolean(gone); +} + +async function s3Pin(ctx) { + const step = 'S3 pin by bare id'; + const a = ctx.cur.A; + if (!a) return notRun(step, ctx.lost.A ?? `A was not stored`), EXIT_FAILED; + const r = await callTool(ctx.client, 'totalreclaw_pin', { memory_id: a }); + const j = r.json ?? {}; + const ok = check(step, 'pin by the bare payload id succeeds', r.ok && j.success === true && j.fact_id === a, r.ok ? j : r); + check(step, 'the ids pin returns are payload ids', + ok && (!j.new_fact_id || isPayloadId(j.new_fact_id)) && idFieldsOffFormat(j).length === 0 && + compositeIds(j).length === 0, + j); + if (!ok) return EXIT_FAILED; + ctx.rememberedTx(j.tx_hash); + note(step, `${j.idempotent ? 'already pinned, no write' : 'pinned'}: ${a} -> ${j.new_fact_id ?? a} ` + + `tx ${j.tx_hash ?? '(none)'}${j.partial ? ' (partial: index confirm timed out)' : ''}`); + ctx.old.A = a; + ctx.cur.A = isPayloadId(j.new_fact_id) ? j.new_fact_id : a; + ctx.track(ctx.cur.A); + const hit = await waitRecall(ctx.client, ctx.cur.A, (m) => m.pinned === true); + const showsPinned = check(step, 'recall shows A pinned', Boolean(hit), + hit ? { id: hit.fact_id, pinned: hit.pinned } : 'the current A id does not come back with pinned: true'); + return showsPinned ? EXIT_OK : EXIT_FAILED; +} + +async function s4Retype(ctx) { + const step = 'S4 retype by :'; + const b = ctx.cur.B; + if (!b) return notRun(step, ctx.lost.B ?? `B was not stored`), EXIT_FAILED; + const r = await callTool(ctx.client, 'totalreclaw_retype', { memory_id: ctx.colon(b), new_type: 'preference' }); + const j = r.json ?? {}; + const ok = check(step, 'retype succeeds with the id given as :', + r.ok && j.success === true && j.memory_id === b && !j.idempotent, r.ok ? j : r); + check(step, 'the ids retype returns are payload ids', + ok && isPayloadId(j.new_memory_id) && idFieldsOffFormat(j).length === 0 && compositeIds(j).length === 0, j); + if (!ok) return EXIT_FAILED; + ctx.rememberedTx(j.tx_hash); + note(step, `${b} -> ${j.new_memory_id} (${j.previous_value} -> ${j.new_value}) ` + + `tx ${j.tx_hash ?? '(none)'}${j.partial ? ' (partial: index confirm timed out)' : ''}`); + if (!isPayloadId(j.new_memory_id)) { + ctx.lose('B', `retype returned a new id that is not a payload id (${short(j.new_memory_id, 80)})`); + return EXIT_FAILED; + } + ctx.old.B = b; + ctx.cur.B = j.new_memory_id; + ctx.track(ctx.cur.B); + // recall's `type` is the short category key: preference is "pref". + const settled = await settledChecks(ctx, step, 'B', (m) => m.type === 'pref', 'type preference ("pref" in recall)'); + return settled ? EXIT_OK : EXIT_FAILED; +} + +async function s5SetScope(ctx) { + const step = 'S5 set_scope by upper-case sender'; + const c = ctx.cur.C; + if (!c) return notRun(step, ctx.lost.C ?? `C was not stored`), EXIT_FAILED; + const r = await callTool(ctx.client, 'totalreclaw_set_scope', { memory_id: ctx.colonUpper(c), scope: 'work' }); + const j = r.json ?? {}; + const ok = check(step, 'set_scope succeeds with the id given as 0xUPPER-CASE-SENDER:', + r.ok && j.success === true && j.memory_id === c && !j.idempotent, r.ok ? j : r); + check(step, 'the ids set_scope returns are payload ids', + ok && isPayloadId(j.new_memory_id) && idFieldsOffFormat(j).length === 0 && compositeIds(j).length === 0, j); + if (!ok) return EXIT_FAILED; + ctx.rememberedTx(j.tx_hash); + note(step, `${c} -> ${j.new_memory_id} (${j.previous_value} -> ${j.new_value}) ` + + `tx ${j.tx_hash ?? '(none)'}${j.partial ? ' (partial: index confirm timed out)' : ''}`); + if (!isPayloadId(j.new_memory_id)) { + ctx.lose('C', `set_scope returned a new id that is not a payload id (${short(j.new_memory_id, 80)})`); + return EXIT_FAILED; + } + ctx.old.C = c; + ctx.cur.C = j.new_memory_id; + ctx.track(ctx.cur.C); + const settled = await settledChecks(ctx, step, 'C', (m) => m.scope === 'work', 'scope work'); + return settled ? EXIT_OK : EXIT_FAILED; +} + +async function s6Unpin(ctx) { + const step = 'S6 unpin by :'; + const a = ctx.cur.A; + if (!a) return notRun(step, ctx.lost.A ?? `A was not stored`), EXIT_FAILED; + // A is pinned. internal#778: the server stops the first call with a confirmation request and a token; the + // same call with that token unpins. Same flow as S9. + const args = { memory_id: ctx.colon(a) }; + let still = false; // seen between the ask and the confirmed call + const { first, second } = await withConfirm(ctx.client, 'totalreclaw_unpin', args, 'pinned_unpin', async () => { + still = await waitRecall(ctx.client, a, (m) => m.pinned === true); + }); + const asked = check(step, 'unpin of a pinned memory asks first (confirmation_required "pinned_unpin" with a confirm_token), nothing changed', + first.ok && askedFor(first.json, 'pinned_unpin') && first.json.success === false && first.json.new_fact_id === undefined, + first.ok ? refusalView(first) : first); + if (asked) { + check(step, 'A is still pinned after the ask', Boolean(still), + still ? { id: a, pinned: still.pinned } + : `${a} not returned as pinned between the ask and the confirmed call`); + } + const r = asked && second ? second : first; + const j = r.json ?? {}; + const ok = check(step, 'unpin by : succeeds', r.ok && j.success === true && j.fact_id === a, r.ok ? j : r); + if (!ok) return EXIT_FAILED; + ctx.rememberedTx(j.tx_hash); + note(step, `${a} -> ${j.new_fact_id} (${j.previous_status} -> ${j.new_status}) ` + + `tx ${j.tx_hash ?? '(none)'}${j.partial ? ' (partial: index confirm timed out)' : ''}`); + ctx.old.A = a; + ctx.cur.A = isPayloadId(j.new_fact_id) ? j.new_fact_id : a; + ctx.track(ctx.cur.A); + const hit = await waitRecall(ctx.client, ctx.cur.A, (m) => m.pinned !== true); + const showsUnpinned = check(step, 'recall shows A not pinned', Boolean(hit), + hit ? { id: hit.fact_id, pinned: hit.pinned ?? '(key absent)' } + : 'the current A id does not come back unpinned'); + return showsUnpinned ? EXIT_OK : EXIT_FAILED; +} + +async function s7Replaces(ctx) { + const step = 'S7 replaces'; + const d = ctx.cur.D; + if (!d) return notRun(step, ctx.lost.D ?? `D was not stored`), EXIT_FAILED; + const { r, item } = await remember(ctx.client, ctx.facts.D2.text, { replaces: ctx.colon(d) }); + const ok = check(step, 'remember with replaces=: stores the new fact and names the old one by its payload id', + r.ok && item?.success === true && item.action === 'replaced' && item.replaced_fact_id === d && + isPayloadId(item.fact_id), + item ?? shown(r)); + check(step, 'the ids the replace returns are payload ids', + ok && idFieldsOffFormat(r.json).length === 0 && compositeIds(r.json).length === 0, r.ok ? r.json : r); + if (!ok) return EXIT_FAILED; + ctx.rememberedTx(item.tx_hash); + note(step, `${d} replaced by ${item.fact_id} tx ${item.tx_hash ?? '(none)'}`); + ctx.old.D = d; + ctx.cur.D = item.fact_id; + ctx.track(ctx.cur.D); + const hit = await waitRecall(ctx.client, ctx.cur.D); + check(step, 'D2 is recallable', Boolean(hit), hit ? { id: hit.fact_id, text: hit.fact_text } : 'D2 not returned within the index timeout'); + const gone = await waitGone(ctx.client, d); + check(step, "D's old id is no longer returned by recall", Boolean(gone), gone ? d : `${d} still returned`); + return Boolean(hit) && Boolean(gone) ? EXIT_OK : EXIT_FAILED; +} + +async function s8Forget(ctx) { + const step = 'S8 forget by :'; + const c = ctx.cur.C; + if (!c) return notRun(step, ctx.lost.C ?? `C was not stored`), EXIT_FAILED; + const r = await callTool(ctx.client, 'totalreclaw_forget', { memory_id: ctx.colon(c) }); + const j = r.json ?? {}; + const ok = check(step, 'forget by : is confirmed: deleted_count 1, the payload id, not partial, no error', + r.ok && j.deleted_count === 1 && Array.isArray(j.fact_ids) && j.fact_ids.length === 1 && + j.fact_ids[0] === c && j.partial !== true && j.error === undefined, + r.ok ? j : r); + if (!ok) return EXIT_FAILED; + ctx.rememberedTx(j.tx_hash); + note(step, `${c} forgotten tx ${j.tx_hash ?? '(none)'}${j.was_pinned ? ' (was pinned)' : ''}`); + const gone = await waitGone(ctx.client, c); + return check(step, 'recall no longer returns C', Boolean(gone), gone ? c : `${c} still returned`) ? EXIT_OK : EXIT_FAILED; +} + +async function s9ForgetPinned(ctx) { + const step = 'S9 forget a pinned memory'; + const b = ctx.cur.B; + if (!b) return notRun(step, ctx.lost.B ?? `B was not stored`), EXIT_FAILED; + const pin = await callTool(ctx.client, 'totalreclaw_pin', { memory_id: ctx.colon(b) }); + const pinned = pin.json?.success === true && pin.json.fact_id === b; + check(step, 'B is pinned (id given as :)', pinned, pin.ok ? pin.json : pin); + if (!pinned) return EXIT_FAILED; + ctx.rememberedTx(pin.json.tx_hash); + ctx.old.B = b; + ctx.cur.B = isPayloadId(pin.json.new_fact_id) ? pin.json.new_fact_id : b; + ctx.track(ctx.cur.B); + note(step, `${b} -> ${ctx.cur.B} tx ${pin.json.tx_hash ?? '(none)'}`); + const isPinned = await waitRecall(ctx.client, ctx.cur.B, (m) => m.pinned === true); + const showsPinned = check(step, 'recall shows B pinned', Boolean(isPinned), + isPinned ? { id: ctx.cur.B, pinned: true } : 'the current B id does not come back with pinned: true'); + if (!showsPinned) return EXIT_FAILED; + + const pinnedB = ctx.cur.B; // the id of B now that it is pinned + const args = { memory_id: pinnedB }; + let still = false; // seen between the ask and the confirmed call + const { first, second } = await withConfirm(ctx.client, 'totalreclaw_forget', args, 'pinned_forget', async () => { + still = await waitRecall(ctx.client, pinnedB, (m) => m.pinned === true); + }); + const asked = check(step, 'forget of the pinned memory returns confirmation_required "pinned_forget" with a confirm_token, and deletes nothing', + first.ok && askedFor(first.json, 'pinned_forget') && first.json.deleted_count === 0 && + Array.isArray(first.json.fact_ids) && first.json.fact_ids.length === 0, + first.ok ? refusalView(first) : first); + if (asked) { + check(step, 'B is still active (and pinned) after the ask', Boolean(still), + still ? { id: pinnedB, pinned: still.pinned } + : `${pinnedB} not returned as pinned between the ask and the confirmed call`); + } + const r = asked && second ? second : first; + const j = r.json ?? {}; + const ok = check(step, + asked ? 'the same forget with the token is confirmed: deleted_count 1, not partial, no error' + : 'the forget is confirmed: deleted_count 1, not partial, no error (the server did not ask)', + r.ok && j.deleted_count === 1 && j.fact_ids?.[0] === pinnedB && j.partial !== true && j.error === undefined, r.ok ? j : r); + if (!ok) return EXIT_FAILED; + ctx.rememberedTx(j.tx_hash); + note(step, `${ctx.cur.B} forgotten tx ${j.tx_hash ?? '(none)'}${j.was_pinned ? ' (was_pinned)' : ''}`); + const gone = await waitGone(ctx.client, ctx.cur.B); + return check(step, 'recall no longer returns B', Boolean(gone), gone ? ctx.cur.B : `${ctx.cur.B} still returned`) ? EXIT_OK : EXIT_FAILED; +} + +async function s10Foreign(ctx) { + const step = 'S10 another account\'s id'; + const a = ctx.cur.A; + if (!a) return notRun(step, ctx.lost.A ?? `A was not stored`), EXIT_FAILED; + const before = await recall(ctx.client, 'totalreclaw vault'); + const beforeA = before.list?.find((m) => m.fact_id === a) ?? null; + const foreign = `${OTHER}:${a}`; + const refusedText = (j) => /another account/i.test(String(j?.error)) && /nothing was changed/i.test(String(j?.error)); + + const f = await callTool(ctx.client, 'totalreclaw_forget', { memory_id: foreign }); + check(step, 'forget refuses it: nothing deleted, the error names another account and says nothing was changed', + f.ok && f.json?.deleted_count === 0 && refusedText(f.json), f.ok ? refusalView(f) : f); + + const p = await callTool(ctx.client, 'totalreclaw_pin', { memory_id: foreign }); + check(step, 'pin refuses it: success false, the error names another account and says nothing was changed', + p.ok && p.json?.success === false && refusedText(p.json), p.ok ? refusalView(p) : p); + + const t = await callTool(ctx.client, 'totalreclaw_retype', { memory_id: foreign, new_type: 'preference' }); + check(step, 'retype refuses it: success false, the error names another account and says nothing was changed', + t.ok && t.json?.success === false && refusedText(t.json), t.ok ? refusalView(t) : t); + + // Give a tombstone or a rewrite the time to show, then compare. + await sleep(10_000); + const after = await recall(ctx.client, 'totalreclaw vault'); + const afterA = after.list?.find((m) => m.fact_id === a) ?? null; + const same = (x, y) => JSON.stringify(x) === JSON.stringify(y); + check(step, 'A is still active and unchanged afterwards', + Boolean(beforeA) && same(shapeOf(beforeA), shapeOf(afterA)) && beforeA?.pinned !== true && afterA?.pinned !== true, + { before: shapeOf(beforeA), after: shapeOf(afterA) }); + return afterA && same(shapeOf(beforeA), shapeOf(afterA)) ? EXIT_OK : EXIT_FAILED; +} + +async function s11Missing(ctx) { + const step = 'S11 a missing id'; + const before = await recall(ctx.client, 'totalreclaw vault'); + const f = await callTool(ctx.client, 'totalreclaw_forget', { memory_id: MISSING }); + check(step, 'forget of a missing id is a not-found result and deletes nothing', + f.ok && f.json?.deleted_count === 0 && f.json?.not_found === true && Array.isArray(f.json?.fact_ids) && + f.json.fact_ids.length === 0 && /not found/i.test(String(f.json?.error)), + f.ok ? refusalView(f) : f); + const p = await callTool(ctx.client, 'totalreclaw_pin', { memory_id: MISSING }); + check(step, 'pin of a missing id is a not-found result: success false, "not found" in the error', + p.ok && p.json?.success === false && /not found/i.test(String(p.json?.error)) && p.json?.tx_hash === undefined, p.ok ? p.json : p); + const after = await recall(ctx.client, 'totalreclaw vault'); + const same = Boolean(before.ids) && Boolean(after.ids) && JSON.stringify([...before.ids].sort()) === JSON.stringify([...after.ids].sort()); + return check(step, 'nothing changed: the active facts recall returns are the same before and after', same, + { before: before.ids ?? shown(before), after: after.ids ?? shown(after) }) ? EXIT_OK : EXIT_FAILED; +} + +async function s12Cleanup(ctx, report) { + const step = 'S12 cleanup'; + // Forget everything the vault still holds: what this run tracked and whatever recall lists. + // When recall answers, only what it still lists needs a forget. When it does not (unknown), try every id the + // run knows: the server answers "not found" for the ones already gone and writes nothing. + const seen = await recall(ctx.client, 'totalreclaw vault'); + const left = [...new Set([...ctx.ever, ...(seen.ids ?? [])])].filter((id) => !seen.ids || seen.ids.includes(id)); + const forgotten = []; + let problem = null; + for (const id of left) { + try { + const { first, second } = await withConfirm(ctx.client, 'totalreclaw_forget', { memory_id: ctx.colon(id) }, 'pinned_forget'); + const r = second ?? first; + if (r.ok && r.json?.deleted_count === 1) { + forgotten.push(id); + ctx.rememberedTx(r.json.tx_hash); + } else if (!(r.ok && r.json?.not_found === true)) { + // "not found" is the answer for an id that is already gone: nothing was left to forget. + problem = problem ?? { id, result: r.ok ? r.json : r }; + } + } catch (err) { + problem = problem ?? { id, error: String(err?.message ?? err) }; + } + } + note(step, `${forgotten.length} fact(s) forgotten in cleanup${left.length ? ` (${left.join(', ')})` : ''}`); + const empty = await waitFor(async () => { + const r = await recall(ctx.client, 'totalreclaw vault'); + return r.ids && r.ids.length === 0 ? r : false; + }, INDEX_TIMEOUT_MS, 5_000); + // The server answers null when it could not count: that is unknown, not a failure. Recall carries the check. + const acct = await callTool(ctx.client, 'totalreclaw_account'); + const count = acct.json?.total_facts_stored; + const countKnown = typeof count === 'number'; + const ok = check(step, 'every fact of the throwaway vault is forgotten: recall returns nothing, and the fact count is 0 when there is one', + Boolean(empty) && !problem && (!countKnown || count === 0), + { problem, recall: empty ? 'returns nothing' : 'did not return an empty answer', factCount: countKnown ? count : 'unknown' }); + report.forgotten_in_cleanup = forgotten; + return ok ? EXIT_OK : EXIT_FAILED; +} + +const STEPS = [ + ['S1 remember', s1Remember], + ['S2 recall', s2Recall], + ['S3 pin by bare id', s3Pin], + ['S4 retype by :', s4Retype], + ['S5 set_scope by upper-case sender', s5SetScope], + ['S6 unpin by :', s6Unpin], + ['S7 replaces', s7Replaces], + ['S8 forget by :', s8Forget], + ['S9 forget a pinned memory', s9ForgetPinned], + ['S10 another account\'s id', s10Foreign], + ['S11 a missing id', s11Missing], + ['S12 cleanup', s12Cleanup], +]; + +// ── the run ────────────────────────────────────────────────────────────────── + +/** Relative paths of the files under `root` (what the server wrote into its temp HOME). */ +function filesUnder(root, limit = 40) { + const out = []; + const walk = (dir) => { + for (const ent of fs.readdirSync(dir, { withFileTypes: true })) { + const file = path.join(dir, ent.name); + if (ent.isDirectory()) walk(file); + else out.push(path.relative(root, file)); + } + }; + try { + walk(root); + } catch { + /* listed what could be listed */ + } + return out.length > limit ? [...out.slice(0, limit), `... ${out.length - limit} more`] : out; +} + +/** + * A signal (Ctrl-C, a kill) must not leave the server process behind: it holds the phrase in its environment. And + * the temp directory goes too, after the same scan the run does at its end. + */ +const live = { client: null, transport: null, tmp: null }; +let interruptHandled = false; +async function onSignal(signal) { + if (interruptHandled) return; + interruptHandled = true; + say(`FAIL interrupted by ${signal}: closing the server and the temp directory`); + try { + const closing = live.client ? live.client.close() : live.transport ? live.transport.close() : Promise.resolve(); + await Promise.race([closing, sleep(15_000)]); + } catch { + /* best effort */ + } + if (live.tmp) { + const hits = scanForPhrase(live.tmp); + if (hits.length) say('FAIL phrase words found in files under the temp HOME: ', clean(hits.join(', '))); + fs.rmSync(live.tmp, { recursive: true, force: true }); + live.tmp = null; + } + process.exit(130); +} + +async function stagingRun(reportPath) { + const startedAt = Date.now(); + const stamp = new Date(startedAt).toISOString().slice(0, 16).replace('T', ' '); + const report = { relay: STAGING_URL, started_utc: new Date(startedAt).toISOString() }; + const facts = { + A: { text: `Rides an amber kayak on the Douro river every weekend (e2e ${stamp})`, query: 'kayak river weekend' }, + B: { text: `Grows basil and thyme on the kitchen windowsill (e2e ${stamp})`, query: 'basil thyme windowsill' }, + C: { text: `Collects vintage glass buttons from flea markets (e2e ${stamp})`, query: 'glass buttons flea markets' }, + D: { text: `Plays the cello in a neighbourhood string quartet (e2e ${stamp})`, query: 'cello string quartet' }, + D2: { text: `Plays the double bass in a neighbourhood string quartet (e2e ${stamp})`, query: 'double bass quartet' }, + }; + // 0 every check passed, 1 a check failed, 2 refused to write. + let code = EXIT_OK; + let tmp = null; + let client = null; + let transport = null; + let phrase = null; + + const serverFlags = { registerFailed: false, version: undefined, name: undefined, toolCount: undefined, closed: false }; + try { + if (!fs.existsSync(SERVER_ENTRY)) throw new Error(`the server is not built: ${path.relative(MCP_ROOT, SERVER_ENTRY)} (run: npm run build)`); + + phrase = generateMnemonic(wordlist, 128); + PHRASES.add(phrase); + // S0 reads billing with this account's auth key: the same derivation the server makes, in memory only. + const authKeyHex = deriveAuthKeyHex(phrase); + + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'tr-mcp-fact-ids-')); + live.tmp = tmp; + for (const d of ['state', 'tmp']) fs.mkdirSync(path.join(tmp, d)); + out(`relay ${STAGING_URL}; HOME of the server: a fresh temp directory`); + + // The child's stderr goes through out(): secret shapes masked, the phrase redacted, then printed. + const server = await connectServer({ + tmp, + phrase, + onLine: (piece) => { + if (/Registration with relay failed/i.test(piece)) serverFlags.registerFailed = true; + out(`[server] ${piece}`); + }, + onClosed: () => { + serverFlags.closed = true; + }, + }); + client = server.client; + transport = server.transport; + live.client = client; + live.transport = transport; + phrase = null; // the child has its copy; from here on only PHRASES (for redaction) holds it + + const info = client.getServerVersion?.() ?? null; + serverFlags.name = info?.name; + serverFlags.version = info?.version; + serverFlags.toolCount = (await client.listTools()).tools.length; + note('setup', `server process up (pid ${transport.pid}); handshake: ${client.getProtocolEra?.() ?? 'n/a'} era`); + + const ctx = runCtx({ client, authKeyHex, facts, serverFlags }); + code = await s0Preflight(ctx, report); + if (code === EXIT_REFUSED) { + note('S0 preflight', 'refused to write: no remember was sent'); + } + const stepSeconds = {}; + for (const [step, fn] of STEPS) { + if (interruptHandled) break; // onSignal() is closing the child and exits + say(`--- ${step}`); + const t0 = Date.now(); + if (code === EXIT_REFUSED) { + notRun(step, 'the preflight refused to write'); + continue; + } + if (fn !== s12Cleanup && recallOut() && !(await recallIsBack(ctx.client))) { + notRun(step, outageWhy()); + continue; + } + try { + await fn(ctx, report); + } catch (err) { + check(step, 'the step ran to the end', false, err); + } + stepSeconds[step] = Math.round((Date.now() - t0) / 1_000); + } + report.step_seconds = stepSeconds; + report.tx_hashes = ctx.tx; + if (serverFlags.closed) note('end', 'the server process closed before the run ended'); + if (serverFlags.registerFailed) report.server_registration_failed = true; + } catch (err) { + if (interruptHandled) return EXIT_FAILED; // onSignal() does the closing and exits + check('setup', 'the server started and the run was set up', false, err); + } + if (interruptHandled) return EXIT_FAILED; + + // The leak scan: once before the child is closed (the plan's order) and once after, which is the one that counts. + let hitsBefore = []; + let hitsAfter = []; + try { + if (tmp) hitsBefore = scanForPhrase(tmp); + if (client) { + await Promise.race([client.close(), sleep(15_000)]); + } else if (transport) { + await Promise.race([transport.close(), sleep(15_000)]); + } + if (tmp) hitsAfter = scanForPhrase(tmp); + } catch (err) { + check('S12 cleanup', 'the client, the child and the temp directory are closed and scanned', false, err); + } + const files = tmp ? filesUnder(tmp) : []; // listed before the directory goes + try { + if (tmp) fs.rmSync(tmp, { recursive: true, force: true }); + if (tmp && fs.existsSync(tmp)) check('S12 cleanup', 'the temp directory is deleted', false, 'still there after rm'); + } catch (err) { + check('S12 cleanup', 'the temp directory is deleted', false, err); + } + live.client = null; + live.transport = null; + live.tmp = null; + const hits = [...new Set([...hitsBefore, ...hitsAfter])]; + if (tmp) { + note('S12 cleanup', `files under the temp HOME: ${JSON.stringify(files)}`); + check('S12 cleanup', 'no 3 consecutive phrase words in any file under the temp HOME', hits.length === 0, hits); + } + if (hits.length) say('FAIL phrase words found in files under the temp HOME'); + + /** Passed and failed checks, and the exit code they mean (a refusal to write stays 2). */ + const tally = () => { + const passedCount = checks.filter((c) => c.pass).length; + const failedCount = checks.length - passedCount; + if (code !== EXIT_REFUSED) code = failedCount === 0 ? EXIT_OK : EXIT_FAILED; + return { passed: passedCount, failed: failedCount }; + }; + Object.assign(report, tally(), { + exit_code: code, + seconds: Math.round((Date.now() - startedAt) / 1_000), + phrase_scan_hits: hits, + confirm_token_min_age_ms: confirmMinAgeMs(), + checks, + notes, + }); + // The report redacts every string value (again, for any that was not redacted on its way in). Keys and the + // check names stay as they are: they are this script's own words, and "redact" works on parts of words. + const text = JSON.stringify(report, (key, value) => + typeof value === 'string' && key !== 'name' && key !== 'step' ? clean(value) : value, 2); + if (reportPath) { + try { + fs.writeFileSync(reportPath, `${text}\n`, { mode: 0o600 }); + out(`report written to ${reportPath}`); + } catch (err) { + // The run is over and its checks stand: say so, and still end with the final line. + check('end', 'the report file was written', false, err); + } + } else { + printReport(text); + } + // A report that could not be written is one failed check more: the final line counts it. + const final = tally(); + say(`== ${final.passed} passed, ${final.failed} failed, exit ${code}`); + return code; +} + +// ── main ───────────────────────────────────────────────────────────────────── + +async function main(argv) { + const { mode, reportPath } = parseArgs(argv); + if (mode === 'self-test') return await selfTest(); + if (mode === 'staging') return stagingRun(reportPath); + out('usage: fact-ids-staging-e2e.mjs --self-test | --report '); + return EXIT_FAILED; +} + +const isMain = Boolean(process.argv[1]) && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url; +if (isMain) { + process.on('unhandledRejection', (reason) => { + out(`FAIL unhandled rejection: ${short(reason)}`); + check('setup', 'no unhandled rejection', false, reason); + }); + for (const signal of ['SIGINT', 'SIGTERM']) { + process.on(signal, () => { + onSignal(signal).catch(() => process.exit(130)); + }); + } + let code = EXIT_FAILED; + try { + code = await main(process.argv.slice(2)); + } catch (err) { + out(`FAIL the script crashed: ${short(err)}`); + code = EXIT_FAILED; + } + if (!interruptHandled) { + // onSignal() closes the child and exits with 130: only it exits after a signal. + // Flush, then exit: the transport's timers must not keep the process alive. + process.stdout.write('', () => process.exit(code)); + } +} From e9d61ea9b14840a2063a92b1bbefed35914bdfe8 Mon Sep 17 00:00:00 2001 From: p-diogo Date: Fri, 4 Dec 2026 22:17:08 +0000 Subject: [PATCH 2/2] test(mcp): E2E waitGone needs a non-empty recall; S10 unchanged row ignores pin state Co-Authored-By: Claude Opus 5.5 --- mcp/tests/e2e/fact-ids-staging-e2e.mjs | 28 +++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/mcp/tests/e2e/fact-ids-staging-e2e.mjs b/mcp/tests/e2e/fact-ids-staging-e2e.mjs index 074b7e6b..af788359 100644 --- a/mcp/tests/e2e/fact-ids-staging-e2e.mjs +++ b/mcp/tests/e2e/fact-ids-staging-e2e.mjs @@ -583,6 +583,25 @@ async function selfTest() { stillPolling && outageCalls === RECALL_OUTAGE_CALLS && wasOut && inOutage === 'polled' && probeDown === false && probeUp === true && !recallOut() && recallState.failures === 0); + // waitGone(): "gone" is an answered recall that leaves the id out of what is still stored. An answered but empty + // recall is not "gone" (other facts are active mid-run, so that answer is anomalous), and neither is no answer or + // an id that is not a payload id. Each fake answers the same on every poll, and 40 ms is only the wait's timeout. + const goneId = '0190ab00-cdef-7000-8000-000000000002'; + const keptId = '0190ab00-cdef-7000-8000-000000000003'; + const answering = (payload) => ({ callTool: async () => ({ content: [{ type: 'text', text: JSON.stringify(payload) }] }) }); + const goneCases = [ + [answering({ memories: [{ fact_id: keptId }] }), goneId, true], + [answering({ memories: [] }), goneId, false], + [answering({ memories: [{ fact_id: goneId }, { fact_id: keptId }] }), goneId, false], + [answering({ memories: [], error: 'Failed to recall memories: boom' }), goneId, false], + [answering({ memories: [] }), 'not-a-payload-id', false], + ]; + const goneVerdicts = []; + for (const [fake, factId] of goneCases) goneVerdicts.push(await waitGone(fake, factId, 40)); + recallState.failures = 0; + that('waitGone(): gone only when an answered recall leaves the id out; an empty answer, no answer or a bad id is not gone', + goneVerdicts.every((got, i) => got === goneCases[i][2])); + // Arguments: --self-test is offline whatever else is on the command line. const plain = (o) => JSON.stringify(o); that('parseArgs(): --self-test is the offline self-test, with or without --report, in any order', @@ -830,13 +849,14 @@ const waitRecall = (client, id, pred = () => true) => /** * Poll until `id` is no longer returned by recall (a tombstone, indexed). Returns `true`, or `false`: `false` too - * when recall does not answer (unknown is not "gone") or `id` is not a payload id. + * when recall does not answer (unknown is not "gone"), when it answers with no memory at all (other facts are + * active mid-run, so that answer is anomalous, not "gone") or `id` is not a payload id. */ const waitGone = (client, id, timeoutMs = INDEX_TIMEOUT_MS) => isPayloadId(id) ? waitFor(async () => { const r = await recall(client, 'totalreclaw vault'); - return r.ids && !r.ids.includes(id) ? true : false; + return r.ids !== null && r.ids.length > 0 && !r.ids.includes(id) ? true : false; }, timeoutMs, 5_000) : Promise.resolve(false); @@ -1265,8 +1285,10 @@ async function s10Foreign(ctx) { const after = await recall(ctx.client, 'totalreclaw vault'); const afterA = after.list?.find((m) => m.fact_id === a) ?? null; const same = (x, y) => JSON.stringify(x) === JSON.stringify(y); + // A's pin state is whatever S6 left it (shapeOf compares it before and after): a still-pinned A would only + // repeat an S6 failure here. check(step, 'A is still active and unchanged afterwards', - Boolean(beforeA) && same(shapeOf(beforeA), shapeOf(afterA)) && beforeA?.pinned !== true && afterA?.pinned !== true, + Boolean(beforeA) && same(shapeOf(beforeA), shapeOf(afterA)), { before: shapeOf(beforeA), after: shapeOf(afterA) }); return afterA && same(shapeOf(beforeA), shapeOf(afterA)) ? EXIT_OK : EXIT_FAILED; }