#!/usr/bin/env node // mgate.mjs v0.3 — 服装交付 manifest 死指针四闸 + 活读径 + 读不出三分类(zero-dep, ESM) // 判词三值:PASS / FAIL / UNCONFIRMED(fail-closed:看不见 ≠ 通过) // 退出码:0 PASS · 1 FAIL · 2 用法/清单错 · 3 UNCONFIRMED // // v0.1 → v0.2 只做加法: // 1) --live:逐项走两条读径(正文读径 ≈ read_metaweb_pin;索引读径 ≈ omni_read pin), // 自动物化 body / sha256 / bytes 与 index{genesisHeight,headPinId,asOf},再跑 G1–G4。 // 2) 双径分裂(正文到手 × 索引缺失 / contentLength 与正文字节不等)一律落 UNCONFIRMED, // 写 asOf 与复检点,绝不折算成 PASS 或 FAIL。 // 3) 四闸语义、判词优先级、退出码、v0.1 的 10 格自检全部冻结不改。 // // v0.2 → v0.3 也只做加法(一处判定、不加新闸): // 0) 先更正一个前提:v0.2 并不把「正文读不出」判 FAIL——它落在 G3 UNCONFIRMED // (G3_NO_BODY_TO_RECOMPUTE)。v0.2 的真问题是:三类完全不同的「看不见」共用 // 一个 reason,且没有换径动作: // (a) 这条读径读不出这种协议(如 /protocols/deliveryreceipt 在通用读工具里一律 unreadable); // (b) 对象在所有读径上都明确缺失(真的不在); // (c) 仪器故障(HTTP_5xx / 超时),对端可能完全正常。 // 1) 新增 unreadClass 三分类;无分类时沿用旧 reason,v0.2 的 16 格因此一行不变。 // 只有 (b) 判 FAIL(G3_OBJECT_ABSENT_ON_ALL_ROUTES);(a)(c) 一律 UNCONFIRMED。 // 2) 新增 altRoutes 与 opts.altReaders:允许换径(默认清单 metaprotocol_registry | pin_content) // 再判一次。换径读到了 → UNCONFIRMED + G3_ALT_ROUTE_ONLY(那条径给的不一定是被声明摘要的那份 // 字节,所以只升到「看见了」,不升到 PASS);换径也缺且主读径是明确 404/缺失 → FAIL; // 换径也缺但主读径是 5xx/异常 → 仍是 UNCONFIRMED(不许因仪器故障冤枉对象)。 // 3) v0.2 的 16 格自检一行未改,另加 U1/U2/U3 三格(共 19 格)。 // // 用法: // node mgate.mjs manifest.json [--json out.json] // node mgate.mjs manifest.json --live [--json out.json] [--seal sealed.json] // node mgate.mjs manifest.json --live --index-file omni.json # 索引改走本地读数 // node mgate.mjs manifest.json --live --body-field content # 对 payload 的某字段取摘要 // node mgate.mjs --selftest // // 环境变量(可选): // MGATE_CONTENT_BASE 正文读径基址,默认 https://manapi.metaid.io/content // MGATE_PIN_BASE 索引读径基址,默认 https://manapi.metaid.io/pin // MGATE_TIMEOUT_MS 单次读超时,默认 20000 import fs from 'node:fs'; import crypto from 'node:crypto'; const SHAPE = /^[0-9a-f]{64}i(0|[1-9][0-9]*)$/; const H64 = /^[0-9a-f]{64}$/; // v0.3:通用读工具读不出时的换径清单(顺序即建议顺序) const DEFAULT_ALT = ['metaprotocol_registry', 'pin_content']; const sha256 = (b) => crypto.createHash('sha256').update(b).digest('hex'); // 时点锚必须带时区偏移:同一句 asOf,第三方要能算出对应的 UTC 瞬间 function asOfNow(d = new Date()) { const pad = (n) => String(n).padStart(2, '0'); const off = -d.getTimezoneOffset(); const sign = off >= 0 ? '+' : '-'; return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T` + `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}` + `${sign}${pad(Math.floor(Math.abs(off) / 60))}:${pad(Math.abs(off) % 60)}`; } // ───────────────────────────────────────────────────────────── // 四闸:v0.1 语义逐字保留。v0.2 只加三处「看不见」的显式出口: // declaredDigest===false → G3 不许因活读物化而自证(防同义反复) // pathsSplit → G3 两径互斥,落 UNCONFIRMED // index.miss → G4 具名记缺失,落 UNCONFIRMED // protocolUnknown → G2 无法判载体,落 UNCONFIRMED(仅活读径未取得时) // ───────────────────────────────────────────────────────────── // 每项:{id,kind:'text'|'file',protocol,pinId,sha256,bytes,body?,index:{genesisHeight,headPinId,asOf,recheckAt?}} export function checkItem(it) { const fails = [], unconf = []; const g = { G1: 'PASS', G2: 'PASS', G3: 'PASS', G4: 'PASS' }; // G1 形状闸:整串 66 字符;前缀/大写/缺 i0 都在这一层红 if (typeof it.pinId !== 'string' || !SHAPE.test(it.pinId)) { g.G1 = 'FAIL'; fails.push(it.pinId === undefined ? 'G1_NO_PINID' : /^[0-9a-f]{8}$/i.test(it.pinId) ? 'G1_PREFIX_ONLY' : /^[0-9a-f]{64}$/i.test(it.pinId) ? 'G1_NO_OUTPUT_INDEX' : /[A-F]/.test(it.pinId) ? 'G1_NOT_LOWERCASE' : 'G1_MALFORMED'); } // G2 载体闸:text 不许挂 metafile://,file 必须 /file 协议 const isFile = it.kind === 'file'; const proto = String(it.protocol || ''); if (it.protocolUnknown) { // 活读径连索引都没拿到:载体未知是「看不见」,不是「挂了错协议」 g.G2 = 'UNCONFIRMED'; unconf.push('G2_PROTOCOL_UNKNOWN'); } else if (isFile ? !proto.startsWith('/file') : (proto === '' || proto.startsWith('/file'))) { g.G2 = 'FAIL'; fails.push(isFile ? 'G2_FILE_PROTOCOL_MISMATCH' : 'G2_TEXT_ON_FILE_PROTOCOL'); } // G3 摘要闸:必须声明 sha256(只声明 bytes 的清单会漏改内容);有正文则逐字节复算 if (it.declaredDigest === false) { // 活读径把 sha256/bytes 物化了,但清单里没有任何声明 —— 自己填的期望值不能自证 if (typeof it.body === 'string' && H64.test(String(it.sha256 || ''))) { g.G3 = 'UNCONFIRMED'; unconf.push(`G3_DERIVED_ONLY_NO_DECLARATION(sha:${String(it.sha256).slice(0, 8)};bytes:${it.bytes})`); } else { g.G3 = 'UNCONFIRMED'; unconf.push('G3_NO_BODY_TO_RECOMPUTE'); } } else if (!H64.test(String(it.sha256 || ''))) { g.G3 = 'FAIL'; fails.push(/[A-F]/.test(String(it.sha256 || '')) ? 'G3_SHA_UPPERCASE' : 'G3_SHA256_MISSING_OR_BAD'); } else if (!Number.isInteger(it.bytes) || it.bytes < 0) { g.G3 = 'FAIL'; fails.push('G3_BYTES_BAD'); } else if (typeof it.body === 'string') { const b = Buffer.from(it.body, 'utf8'); const h = sha256(b); if (h !== it.sha256 || b.length !== it.bytes) { g.G3 = 'FAIL'; fails.push(`G3_DIGEST_MISMATCH(sha:${h.slice(0, 8)}!=${it.sha256.slice(0, 8)};bytes:${b.length}!=${it.bytes})`); } } else if (it.unreadClass === 'ABSENT_ALL_ROUTES') { // 所有读径都明确缺:这才是「对象不在」,允许红 g.G3 = 'FAIL'; fails.push('G3_OBJECT_ABSENT_ON_ALL_ROUTES'); } else if (it.unreadClass === 'UNREADABLE_OPAQUE') { const alt = (Array.isArray(it.altRoutes) && it.altRoutes.length ? it.altRoutes : DEFAULT_ALT).join('|'); g.G3 = 'UNCONFIRMED'; unconf.push(it.altHit ? `G3_ALT_ROUTE_ONLY(route:${it.altHit.route};sha:${String(it.altHit.sha256).slice(0, 8)};bytes:${it.altHit.bytes};verify:${alt})` : `G3_BODY_UNREADABLE_OPAQUE(try:${alt})`); } else { g.G3 = 'UNCONFIRMED'; unconf.push('G3_NO_BODY_TO_RECOMPUTE'); } // 两径分裂:正文自洽但索引记的 contentLength 不同 —— 不知道哪一侧是旧的 if (g.G3 !== 'FAIL' && it.pathsSplit) { g.G3 = 'UNCONFIRMED'; unconf.push(it.pathsSplit); } // G4 索引/时效闸:-1/null 是 UNCONFIRMED 不是失败;head 不是本枚就是 FAIL const ix = it.index || {}; const gh = ix.genesisHeight; if (!ix.asOf) { g.G4 = 'FAIL'; fails.push('G4_NO_ASOF'); } else if (ix.miss) { g.G4 = 'UNCONFIRMED'; unconf.push(`G4_INDEX_MISS(${ix.miss};asOf=${ix.asOf})`); } else if (gh === undefined || gh === null || gh === -1 || String(gh) === '-1') { g.G4 = 'UNCONFIRMED'; unconf.push(`G4_INDEX_UNCONFIRMED(asOf=${ix.asOf})`); } else if (!Number.isInteger(gh) || gh < 0) { g.G4 = 'FAIL'; fails.push('G4_HEIGHT_NOT_INTEGER'); } if (g.G4 !== 'FAIL' && ix.headPinId !== undefined && ix.headPinId !== it.pinId) { g.G4 = 'FAIL'; fails.push('G4_NOT_MODIFY_HEAD'); } const verdict = fails.length ? 'FAIL' : unconf.length ? 'UNCONFIRMED' : 'PASS'; const reason = (fails.length ? fails : unconf).join(';') || '-'; return { id: it.id, gates: g, verdict, reason }; } export function run(man) { const items = (man && Array.isArray(man.items)) ? man.items : null; if (!items) return { error: 'manifest.items must be an array' }; const rows = items.map(checkItem); const n = (v) => rows.filter(r => r.verdict === v).length; const counts = { PASS: n('PASS'), FAIL: n('FAIL'), UNCONFIRMED: n('UNCONFIRMED') }; const exit = counts.FAIL ? 1 : counts.UNCONFIRMED ? 3 : 0; return { manifestId: man.manifestId || '(unnamed)', counts, exit, rows }; } // ───────────────────────────────────────────────────────────── // 活读径 // ───────────────────────────────────────────────────────────── // readers.body(pinId) → {ok, text, buf, bytesLen, sha256, status} // readers.index(pinId) → {ok, genesisHeight, modifyHistory, contentLength, path, status} export function httpReaders(env = process.env) { const bodyBase = (env.MGATE_CONTENT_BASE || 'https://manapi.metaid.io/content').replace(/\/+$/, ''); const pinBase = (env.MGATE_PIN_BASE || 'https://manapi.metaid.io/pin').replace(/\/+$/, ''); const timeout = Number(env.MGATE_TIMEOUT_MS || 20000); const get = async (url) => { const r = await fetch(url, { signal: AbortSignal.timeout(timeout), headers: { accept: '*/*' } }); const buf = Buffer.from(await r.arrayBuffer()); return { status: r.status, buf }; }; return { // 正文读径:与 read_metaweb_pin 同侧 —— 拿回的是被读的那份字节,不是回执 async body(pinId) { const { status, buf } = await get(`${bodyBase}/${pinId}`); if (status !== 200) return { ok: false, status: `HTTP_${status}`, bytesLen: buf.length }; if (!buf.length) return { ok: false, status: 'EMPTY_BODY', bytesLen: 0 }; return { ok: true, status: 'OK', buf, text: buf.toString('utf8'), bytesLen: buf.length, sha256: sha256(buf) }; }, // 索引读径:与 omni_read pin 同侧 —— 拿回的是高度 / modify 链 / 声明长度 async index(pinId) { const { status, buf } = await get(`${pinBase}/${pinId}`); if (status !== 200) return { ok: false, status: `HTTP_${status}` }; let j; try { j = JSON.parse(buf.toString('utf8')); } catch { return { ok: false, status: 'BAD_JSON' }; } const d = j && j.data; if (!d || j.code !== 1) return { ok: false, status: 'MISS', detail: (j && j.message) || 'no pin found' }; // 索引若回的是别的 pin,宁可记缺失也不能拿错对象的读数顶上 if (d.id !== pinId) return { ok: false, status: 'PIN_ID_MISMATCH', detail: `index returned ${d.id}` }; return { ok: true, status: 'OK', genesisHeight: d.genesisHeight, modifyHistory: d.modify_history, contentLength: d.contentLength, path: d.path, timestamp: d.timestamp, }; }, }; } // 索引读数改走本地文件(omni_read pin 的落盘结果)。支持三种形状: // {code,data:{...}} / {data:[{...}]} / [{...}] export function fileReaders(file, bodyReader) { const raw = JSON.parse(fs.readFileSync(file, 'utf8')); const rows = Array.isArray(raw) ? raw : Array.isArray(raw.data) ? raw.data : raw.data && typeof raw.data === 'object' ? [raw.data] : []; const byId = new Map(); for (const r of rows) if (r && typeof r.id === 'string') byId.set(r.id, r); return { body: bodyReader, async index(pinId) { const d = byId.get(pinId); if (!d) return { ok: false, status: 'MISS_LOCAL', detail: 'not in index file' }; return { ok: true, status: 'OK', genesisHeight: d.genesisHeight, modifyHistory: d.modify_history, contentLength: d.contentLength, path: d.path, timestamp: d.timestamp, }; }, }; } function headFromIndex(ix, pinId) { const mh = ix.modifyHistory; if (!Array.isArray(mh) || mh.length === 0) return pinId; // 没改过 → 本枚即链头 const last = mh[mh.length - 1]; if (typeof last === 'string') return last; return last && (last.pinId || last.id || last.txid || last.newPinId) || undefined; } // 把一条清单项物化成「四闸可判」的形态,并把读数原样留在 live 上 export async function enrichItem(it, readers, opts = {}) { const out = { ...it }; const live = { asOf: asOfNow(), body: null, index: null, paths: {}, bodyField: opts.bodyField || 'raw' }; const pinId = it.pinId; // 形状不合法就不去读:没有合法地址可读,读数只会把错形状洗成「缺索引」 const shapeOk = typeof pinId === 'string' && SHAPE.test(pinId); live.paths.shape = shapeOk ? 'OK' : 'SKIP_BAD_SHAPE'; if (!shapeOk) { out.live = live; return out; } let body = null, ix = null; try { body = await readers.body(pinId, opts); } catch (e) { body = { ok: false, status: 'READ_THROW', detail: String((e && e.message) || e) }; } try { ix = await readers.index(pinId); } catch (e) { ix = { ok: false, status: 'INDEX_THROW', detail: String((e && e.message) || e) }; } const declaredSha = H64.test(String(it.sha256 || '')); const declaredBytes = Number.isInteger(it.bytes); // ── 正文读径 if (body && body.ok) { let text = body.text, bufForDigest = body.buf; if (live.bodyField !== 'raw') { // 读 note 的「正文」而不是整条 payload:显式选字段,长度/摘要都按该字段算 try { const j = JSON.parse(body.text); const v = j[live.bodyField]; if (typeof v !== 'string') throw new Error(`field ${live.bodyField} is not a string`); text = v; bufForDigest = Buffer.from(v, 'utf8'); } catch (e) { text = undefined; bufForDigest = undefined; live.body = { path: 'read', status: 'FIELD_ERROR', detail: String(e.message || e) }; } } if (text !== undefined) { out.body = text; live.body = { path: 'read', status: 'OK', sha256: sha256(bufForDigest), bytes: bufForDigest.length, payloadBytes: body.bytesLen, }; if (!declaredSha) { out.sha256 = live.body.sha256; out.bytes = live.body.bytes; out.declaredDigest = false; // 物化了,但清单没声明 —— G3 不许据此放行 } else if (!declaredBytes) { out.bytes = live.body.bytes; } } } else if (body) { live.body = { path: 'read', status: body.status || 'MISS', detail: body.detail, bytes: body.bytesLen }; // v0.3:读不出不是一种状态,是三类。只有「所有读径都明确缺」才允许判红。 // 没给换径读器时保持 v0.2 原行为(reason 仍为 G3_NO_BODY_TO_RECOMPUTE)——后向兼容,L6 一格不改。 if (typeof opts.altReaders === 'function') { const alt = Array.isArray(it.altRoutes) && it.altRoutes.length ? it.altRoutes : DEFAULT_ALT; out.altRoutes = alt; const primaryAbsent = /^(HTTP_404|MISS|MISS_LOCAL|EMPTY_BODY)$/.test(String(body.status || '')); let altRes = null; try { altRes = await opts.altReaders(pinId, alt); } catch (e) { altRes = { ok: false, status: 'ALT_THROW', detail: String((e && e.message) || e) }; } if (altRes && altRes.ok) { // 换径读到了:对象在,但那条径给的不一定是被声明摘要的那份字节 → 只升到「看见了」 const altText = String(altRes.text ?? ''); out.unreadClass = 'UNREADABLE_OPAQUE'; out.altHit = { route: altRes.route || 'alt', sha256: sha256(Buffer.from(altText, 'utf8')), bytes: Buffer.byteLength(altText) }; live.body.alt = out.altHit; } else if (altRes && primaryAbsent) { // 主读径明确缺 + 换径也缺 → 这才是对象不在 out.unreadClass = 'ABSENT_ALL_ROUTES'; live.body.alt = altRes; } else { // 主读径是仪器故障 → 不许冤枉对象 out.unreadClass = 'UNREADABLE_OPAQUE'; live.body.alt = altRes; } } } // ── 索引读径 if (ix && ix.ok) { const head = headFromIndex(ix, pinId); out.index = { genesisHeight: ix.genesisHeight, headPinId: head, asOf: live.asOf, path: ix.path, contentLength: ix.contentLength, }; live.index = { path: 'index', status: 'OK', genesisHeight: ix.genesisHeight, headPinId: head, contentLength: ix.contentLength, modifyHistory: ix.modifyHistory ?? null, }; if (!String(it.protocol || '')) out.protocol = ix.path; // 载体由索引补,不靠猜 // 两径互斥:只在摘要basis=raw 时可把 contentLength 当正文长度比 if (live.bodyField === 'raw' && body && body.ok && Number.isInteger(ix.contentLength) && ix.contentLength !== body.bytesLen) { out.pathsSplit = `G3_PATHS_SPLIT(index.contentLength:${ix.contentLength}!=body.bytes:${body.bytesLen})`; live.paths.split = out.pathsSplit; } } else { // 正文读得到、索引 404:这是 2026-11-20 06:3x 实测过的双径分裂态(间隔约 3 分钟) // 必须记 UNCONFIRMED + asOf,不得折算成 PASS 或 FAIL out.index = { genesisHeight: null, headPinId: undefined, asOf: live.asOf, miss: (ix && ix.status) || 'MISS' }; live.index = { path: 'index', status: (ix && ix.status) || 'MISS', detail: ix && ix.detail }; if (!String(it.protocol || '')) out.protocolUnknown = true; } out.live = live; return out; } export async function runLive(man, opts = {}) { const items = (man && Array.isArray(man.items)) ? man.items : null; if (!items) return { error: 'manifest.items must be an array' }; if (!opts.readers) return { error: 'runLive requires readers' }; const enriched = []; for (const it of items) enriched.push(await enrichItem(it, opts.readers, opts)); const rows = enriched.map((e) => { const r = checkItem(e); // 判决行保留原值,封存/表格都要从这里取,不能回头去猜 r.pinId = e.pinId; r.kind = e.kind; r.protocol = e.protocol; r.sha256 = e.sha256; r.bytes = e.bytes; r.live = e.live; return r; }); const n = (v) => rows.filter(r => r.verdict === v).length; const counts = { PASS: n('PASS'), FAIL: n('FAIL'), UNCONFIRMED: n('UNCONFIRMED') }; const exit = counts.FAIL ? 1 : counts.UNCONFIRMED ? 3 : 0; return { manifestId: man.manifestId || '(unnamed)', counts, exit, rows, live: true, bodyField: opts.bodyField || 'raw', asOf: rows[0] && rows[0].live ? rows[0].live.asOf : asOfNow(), }; } // 封存:把本次活读的摘要写成「声明」,此后可离线复跑(Phase A 观察 → Phase B 复验) export function seal(result) { const sealedAt = asOfNow(); return { manifestId: `${result.manifestId}#sealed@${sealedAt}`, sealedAt, sealedFrom: result.manifestId, bodyField: result.bodyField || 'raw', items: result.rows.map((r) => ({ id: r.id, pinId: r.pinId, kind: r.kind || undefined, protocol: r.protocol || undefined, // 封存的是「本次观测到的字节指纹」,不是清单里可能写错的那条声明 sha256: r.live && r.live.body && r.live.body.status === 'OK' ? r.live.body.sha256 : r.sha256, bytes: r.live && r.live.body && r.live.body.status === 'OK' ? r.live.body.bytes : r.bytes, index: { genesisHeight: r.live && r.live.index ? r.live.index.genesisHeight : null, headPinId: r.live && r.live.index ? r.live.index.headPinId : undefined, asOf: sealedAt, }, })), }; } // ───────────────────────────────────────────────────────────── // 自检:v0.1 的 10 格原样保留,另加 6 格活读径夹具(mock 读径,不联网) // ───────────────────────────────────────────────────────────── const V = (ok) => ok ? 'PASS' : 'FAIL'; function mockReaders({ body, index }) { const pick = (r) => async () => typeof r === 'function' ? r() : r; return { body: pick(body), index: pick(index) }; } const okBody = (text) => { const b = Buffer.from(text, 'utf8'); return { ok: true, status: 'OK', text, buf: b, bytesLen: b.length, sha256: sha256(b) }; }; const okIndex = (gh, head, len, mh = null) => ({ ok: true, status: 'OK', genesisHeight: gh, headPinId: head, modifyHistory: mh, contentLength: len, path: '/protocols/simplenote', }); const missIndex = { ok: false, status: 'MISS', detail: 'no pin found.' }; async function selftest() { const good = sha256(Buffer.from('版型 A/38,工艺单 v3', 'utf8')); const P = 'a'.repeat(64) + 'i0'; const fixtures = [ { name: 'V1 全绿', man: { manifestId: 'V1', items: [{ id: 'pat-1', kind: 'text', protocol: '/protocols/simplenote', pinId: P, sha256: good, bytes: Buffer.byteLength('版型 A/38,工艺单 v3'), body: '版型 A/38,工艺单 v3', index: { genesisHeight: 199094, headPinId: P, asOf: '2026-11-20T06:00:00+08:00' } }] }, want: ['PASS'], exit: 0 }, { name: 'V2 8位前缀', man: { manifestId: 'V2', items: [{ id: 'pat-2', kind: 'text', protocol: '/protocols/simplenote', pinId: 'a1b2c3d4', sha256: good, bytes: 1, body: 'x', index: { genesisHeight: 1, asOf: 'x' } }] }, want: ['FAIL'], exit: 1 }, { name: 'V3 64hex缺i0', man: { manifestId: 'V3', items: [{ id: 'pat-3', kind: 'text', protocol: '/protocols/simplenote', pinId: 'a'.repeat(64), sha256: good, bytes: 1, body: 'x', index: { genesisHeight: 1, asOf: 'x' } }] }, want: ['FAIL'], exit: 1 }, { name: 'V4 摘要不符', man: { manifestId: 'V4', items: [{ id: 'pat-4', kind: 'text', protocol: '/protocols/simplenote', pinId: P, sha256: 'b'.repeat(64), bytes: 3, body: 'abc', index: { genesisHeight: 1, asOf: 'x' } }] }, want: ['FAIL'], exit: 1 }, { name: 'V5 genesisHeight=-1', man: { manifestId: 'V5', items: [{ id: 'pat-5', kind: 'text', protocol: '/protocols/simplenote', pinId: P, sha256: sha256(Buffer.from('abc')), bytes: 3, body: 'abc', index: { genesisHeight: -1, headPinId: P, asOf: '2026-11-20T06:00:00+08:00' } }] }, want: ['UNCONFIRMED'], exit: 3 }, { name: 'V10 摘要红×索引未确认 优先级', man: { manifestId: 'V10', items: [{ id: 'pat-10', kind: 'text', protocol: '/protocols/simplenote', pinId: P, sha256: good, bytes: 3, body: 'abc', index: { genesisHeight: -1, asOf: 'x' } }] }, want: ['FAIL'], exit: 1 }, { name: 'V6 非链头', man: { manifestId: 'V6', items: [{ id: 'pat-6', kind: 'text', protocol: '/protocols/simplenote', pinId: P, sha256: good, bytes: 3, body: 'abc', index: { genesisHeight: 5, headPinId: 'c'.repeat(64) + 'i0', asOf: 'x' } }] }, want: ['FAIL'], exit: 1 }, { name: 'V7 只声明bytes', man: { manifestId: 'V7', items: [{ id: 'pat-7', kind: 'text', protocol: '/protocols/simplenote', pinId: P, bytes: 3, body: 'abc', index: { genesisHeight: 5, asOf: 'x' } }] }, want: ['FAIL'], exit: 1 }, { name: 'V8 文本挂file协议', man: { manifestId: 'V8', items: [{ id: 'pat-8', kind: 'text', protocol: '/file', pinId: P, sha256: good, bytes: 3, body: 'abc', index: { genesisHeight: 5, asOf: 'x' } }] }, want: ['FAIL'], exit: 1 }, { name: 'V9 混批:绿×1+未确认×1+红×1', man: { manifestId: 'V9', items: [ { id: 'a', kind: 'text', protocol: '/protocols/simplenote', pinId: P, sha256: sha256(Buffer.from('abc')), bytes: 3, body: 'abc', index: { genesisHeight: 9, headPinId: P, asOf: 'x' } }, { id: 'b', kind: 'text', protocol: '/protocols/simplenote', pinId: P, sha256: sha256(Buffer.from('abc')), bytes: 3, body: 'abc', index: { genesisHeight: -1, asOf: 'x' } }, { id: 'c', kind: 'text', protocol: '/protocols/simplenote', pinId: 'a'.repeat(64), sha256: sha256(Buffer.from('abc')), bytes: 3, body: 'abc', index: { genesisHeight: 9, asOf: 'x' } }] }, want: ['PASS', 'UNCONFIRMED', 'FAIL'], exit: 1 }, ]; let ok = 0; for (const f of fixtures) { const r = run(f.man); const got = r.rows.map(x => x.verdict); const pass = JSON.stringify(got) === JSON.stringify(f.want) && r.exit === f.exit && !r.error; if (pass) ok++; console.log(`${pass ? 'OK ' : 'BAD '} ${f.name.padEnd(26)} → ${got.join(',')} exit=${r.exit} (want ${f.want.join(',')} exit=${f.exit})`); } // ── 活读径夹具(全部 mock,不依赖网络) const T = '版型 A/38,工艺单 v3'; const B = Buffer.byteLength(T); const live = [ { name: 'L1 双径一致+声明摘要', man: { manifestId: 'L1', items: [{ id: 'l1', kind: 'text', protocol: '/protocols/simplenote', pinId: P, sha256: sha256(Buffer.from(T, 'utf8')), bytes: B }] }, readers: mockReaders({ body: okBody(T), index: okIndex(199094, P, B) }), want: ['PASS'], exit: 0, check: (r) => r.rows[0].reason !== '-' ? `reason should be '-', got ${r.rows[0].reason}` : null, }, { name: 'L2 正文到手×索引404', man: { manifestId: 'L2', items: [{ id: 'l2', kind: 'text', protocol: '/protocols/simplenote', pinId: P, sha256: sha256(Buffer.from(T, 'utf8')), bytes: B }] }, readers: mockReaders({ body: okBody(T), index: missIndex }), want: ['UNCONFIRMED'], exit: 3, check: (r) => { const x = r.rows[0]; if (x.gates.G1 !== 'PASS' || x.gates.G2 !== 'PASS' || x.gates.G3 !== 'PASS') return `G1/G2/G3 should stay PASS, got ${JSON.stringify(x.gates)}`; if (!/G4_INDEX_MISS/.test(x.reason)) return `reason should name G4_INDEX_MISS, got ${x.reason}`; if (!/[+-]\d{2}:\d{2}$/.test(String(x.live.asOf || ''))) return 'asOf must carry a tz offset'; return null; }, }, { name: 'L3 双径分裂(contentLength)', man: { manifestId: 'L3', items: [{ id: 'l3', kind: 'text', protocol: '/protocols/simplenote', pinId: P, sha256: sha256(Buffer.from(T, 'utf8')), bytes: B }] }, readers: mockReaders({ body: okBody(T), index: okIndex(199094, P, B + 1) }), want: ['UNCONFIRMED'], exit: 3, check: (r) => /G3_PATHS_SPLIT/.test(r.rows[0].reason) ? null : `reason should name G3_PATHS_SPLIT, got ${r.rows[0].reason}`, }, { name: 'L4 无声明→物化不自证', man: { manifestId: 'L4', items: [{ id: 'l4', kind: 'text', protocol: '/protocols/simplenote', pinId: P }] }, readers: mockReaders({ body: okBody(T), index: okIndex(199094, P, B) }), want: ['UNCONFIRMED'], exit: 3, check: (r) => { const x = r.rows[0]; const it = r.sealed && r.sealed.items[0]; if (!/G3_DERIVED_ONLY/.test(x.reason)) return `reason should name G3_DERIVED_ONLY, got ${x.reason}`; if (!it || it.sha256 !== sha256(Buffer.from(T, 'utf8')) || it.bytes !== B) return 'live should materialize sha256/bytes into the seal'; return null; }, }, { name: 'L5 modify链头非本枚', man: { manifestId: 'L5', items: [{ id: 'l5', kind: 'text', protocol: '/protocols/simplenote', pinId: P, sha256: sha256(Buffer.from(T, 'utf8')), bytes: B }] }, readers: mockReaders({ body: okBody(T), index: okIndex(199094, P, B, [{ pinId: 'c'.repeat(64) + 'i0' }]) }), want: ['FAIL'], exit: 1, check: (r) => /G4_NOT_MODIFY_HEAD/.test(r.rows[0].reason) ? null : `reason should name G4_NOT_MODIFY_HEAD, got ${r.rows[0].reason}`, }, { name: 'L6 混批活读:绿×1+未确认×1+红×1', man: { manifestId: 'L6', items: [ { id: 'a', kind: 'text', protocol: '/protocols/simplenote', pinId: P, sha256: sha256(Buffer.from(T, 'utf8')), bytes: B }, { id: 'b', kind: 'text', protocol: '/protocols/simplenote', pinId: 'b'.repeat(64) + 'i0', sha256: sha256(Buffer.from(T, 'utf8')), bytes: B }, { id: 'c', kind: 'text', protocol: '/protocols/simplenote', pinId: 'c'.repeat(64) + 'i0', sha256: 'd'.repeat(64), bytes: B }, ] }, readers: { // b 的正文读径缺席,c 的正文在但声明摘要不符 body: async (pinId) => pinId === 'b'.repeat(64) + 'i0' ? { ok: false, status: 'HTTP_404' } : okBody(T), index: async (pinId) => okIndex(199094, pinId, B), }, want: ['PASS', 'UNCONFIRMED', 'FAIL'], exit: 1, check: (r) => { const b = r.rows[1]; if (!/G3_NO_BODY_TO_RECOMPUTE/.test(b.reason)) return `b should be UNCONFIRMED for missing body, got ${b.reason}`; if (!/G3_DIGEST_MISMATCH/.test(r.rows[2].reason)) return `c should FAIL on digest, got ${r.rows[2].reason}`; return null; }, }, { name: 'U1 主读径读不出×换径可读', man: { manifestId: 'U1', items: [{ id: 'u1', kind: 'text', protocol: '/protocols/deliveryreceipt', pinId: P, sha256: sha256(Buffer.from(T, 'utf8')), bytes: B }] }, readers: mockReaders({ body: { ok: false, status: 'HTTP_404', bytesLen: 0 }, index: okIndex(199523, P, B) }), altReaders: async () => ({ ok: true, route: 'pin_content', text: T }), want: ['UNCONFIRMED'], exit: 3, check: (r) => { const x = r.rows[0]; if (x.gates.G1 !== 'PASS' || x.gates.G2 !== 'PASS') return `G1/G2 should stay PASS, got ${JSON.stringify(x.gates)}`; if (!/G3_ALT_ROUTE_ONLY/.test(x.reason)) return `reason should name G3_ALT_ROUTE_ONLY, got ${x.reason}`; if (!/metaprotocol_registry/.test(x.reason)) return 'reason should carry the alternate-route list'; return null; }, }, { name: 'U2 两条读径都明确缺', man: { manifestId: 'U2', items: [{ id: 'u2', kind: 'text', protocol: '/protocols/deliveryreceipt', pinId: P, sha256: sha256(Buffer.from(T, 'utf8')), bytes: B }] }, readers: mockReaders({ body: { ok: false, status: 'HTTP_404', bytesLen: 0 }, index: okIndex(199523, P, B) }), altReaders: async () => ({ ok: false, status: 'MISS' }), want: ['FAIL'], exit: 1, check: (r) => /G3_OBJECT_ABSENT_ON_ALL_ROUTES/.test(r.rows[0].reason) ? null : `reason should name G3_OBJECT_ABSENT_ON_ALL_ROUTES, got ${r.rows[0].reason}`, }, { name: 'U3 仪器故障×换径也缺(不许判红)', man: { manifestId: 'U3', items: [{ id: 'u3', kind: 'text', protocol: '/protocols/deliveryreceipt', pinId: P, sha256: sha256(Buffer.from(T, 'utf8')), bytes: B }] }, readers: mockReaders({ body: { ok: false, status: 'HTTP_500', bytesLen: 0 }, index: okIndex(199523, P, B) }), altReaders: async () => ({ ok: false, status: 'HTTP_502' }), want: ['UNCONFIRMED'], exit: 3, check: (r) => /G3_BODY_UNREADABLE_OPAQUE/.test(r.rows[0].reason) ? null : `instrument error must not blame the object, got ${r.rows[0].reason}`, }, ]; for (const f of live) { let r, err = null; try { r = await runLive(f.man, { readers: f.readers, altReaders: f.altReaders }); r.sealed = seal(r); } catch (e) { err = e; } if (err) { console.log(`BAD ${f.name.padEnd(26)} → threw ${err.message}`); continue; } const got = r.rows.map(x => x.verdict); const base = JSON.stringify(got) === JSON.stringify(f.want) && r.exit === f.exit && !r.error; const extra = base && f.check ? f.check(r) : (base ? null : `verdict/exit mismatch`); const pass = base && !extra; if (pass) ok++; console.log(`${pass ? 'OK ' : 'BAD '} ${f.name.padEnd(26)} → ${got.join(',')} exit=${r.exit} (want ${f.want.join(',')} exit=${f.exit})${extra ? ` ⟂ ${extra}` : ''}`); } const total = fixtures.length + live.length; console.log(`SELFTEST ${ok}/${total} (v0.1 core ${fixtures.length} + live ${live.length})`); process.exitCode = ok === total ? 0 : 1; } // ───────────────────────────────────────────────────────────── // CLI // ───────────────────────────────────────────────────────────── function printRow(x) { const base = [x.id, `G1=${x.gates.G1}`, `G2=${x.gates.G2}`, `G3=${x.gates.G3}`, `G4=${x.gates.G4}`, x.verdict, x.reason]; console.log(base.join(' | ')); if (x.live) { const b = x.live.body || {}, i = x.live.index || {}; console.log(` LIVE | body=${b.status || '-'} sha256=${b.sha256 || '-'} bytes=${b.bytes ?? '-'} | index=${i.status || '-'} gh=${i.genesisHeight ?? '-'} head=${i.headPinId || '-'} asOf=${x.live.asOf}`); } } function printManifest(r) { for (const x of r.rows) printRow(x); console.log(`MANIFEST ${r.manifestId} | PASS=${r.counts.PASS} FAIL=${r.counts.FAIL} UNCONFIRMED=${r.counts.UNCONFIRMED} | EXIT=${r.exit}`); } const argv = process.argv.slice(2); if (argv.includes('--selftest')) await selftest(); else { const file = argv.find(a => !a.startsWith('--')); if (!file) { console.error('usage: node mgate.mjs [--json out.json] [--live] [--seal out.json] | --selftest'); process.exit(2); } const flag = (name) => argv.includes(name); const optVal = (name) => { const i = argv.indexOf(name); return i >= 0 ? argv[i + 1] : undefined; }; const wantLive = flag('--live') || !!optVal('--seal'); let man; try { man = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) { console.error(`E_MANIFEST ${e.code || 'BAD_JSON'}: ${e.message}`); process.exit(2); } let r; if (wantLive) { const base = httpReaders(process.env); const indexFile = optVal('--index-file'); const readers = indexFile ? fileReaders(indexFile, base.body) : base; r = await runLive(man, { readers, bodyField: optVal('--body-field') || 'raw' }); } else { r = run(man); } if (r.error) { console.error(`E_SCHEMA ${r.error}`); process.exit(2); } printManifest(r); const ji = argv.indexOf('--json'); if (ji >= 0 && argv[ji + 1]) fs.writeFileSync(argv[ji + 1], JSON.stringify(r, null, 2)); const sealTo = optVal('--seal'); if (sealTo) { const s = seal(r); fs.writeFileSync(sealTo, JSON.stringify(s, null, 2)); console.log(`SEALED ${sealTo} | items=${s.items.length} | sealedAt=${s.sealedAt}`); } // 不用 process.exit():Windows + undici 会在关闭中的 socket handle 上触发 libuv 断言, // 把退出码冲成 127。交回事件循环,让 exitCode 自己生效。 process.exitCode = r.exit; }