File size: 25,369 Bytes
fed1528
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
#!/usr/bin/env node
/**
 * ECC-5 REALNESS CERTIFICATION β€” backend pillars.
 *
 * MANDATORY before any avatar/presence work is announced finished. Applies to
 * every agent on this project, not just the primary. Frontend pillars
 * (SUBSTANCE / MOTION / UPON LOAD) are certified in-browser; this harness
 * covers everything reachable from the controller.
 *
 *   node scripts/ecc5-certify.mjs [--base http://127.0.0.1:8100]
 *
 * Exit code 0 = certified, 1 = at least one pillar failed.
 */

import { readdirSync, statSync, writeFileSync, mkdirSync } from "node:fs";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";

const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");

function arg(name, fallback = null) {
  const i = process.argv.indexOf(name);
  return i > -1 ? process.argv[i + 1] : fallback;
}

const BASE = (arg("--base", "http://127.0.0.1:8100")).replace(/\/$/, "");

/**
 * Browser-measured pillars folded in. The in-page harness prints a JSON blob;
 * pass it with --tti '<json>' so ONE certificate holds every pillar instead of
 * the frontend results living in somebody's scrollback.
 */
const TTI = (() => {
  const raw = arg("--tti");
  if (!raw) return null;
  try {
    return JSON.parse(raw);
  } catch {
    return null;
  }
})();

const results = [];
let failed = 0;

/**
 * Scored record. `score` is 0-100 realness, `weight` is its share of the
 * composite ECC-5 Realness Index. A pillar can pass functionally and still
 * score badly β€” that is the point: working is not the same as human.
 */
function record(pillar, pass, detail, score = null, weight = 1) {
  results.push({ pillar, pass, detail, score, weight });
  if (!pass) failed += 1;
  const tag = pass ? "\x1b[32mPASS\x1b[0m" : "\x1b[31mFAIL\x1b[0m";
  const scoreTag =
    score == null
      ? ""
      : ` \x1b[${score >= 85 ? "32" : score >= 70 ? "33" : "31"}m${String(score).padStart(3)}\x1b[0m`;
  console.log(`  [${tag}]${scoreTag} ${pillar}`);
  console.log(`         ${detail}`);
}

/** Linear score: full marks at or below `best`, zero at or above `worst`. */
function scoreBand(value, best, worst) {
  if (value <= best) return 100;
  if (value >= worst) return 0;
  return Math.round(100 * (1 - (value - best) / (worst - best)));
}

async function json(path, init) {
  const res = await fetch(`${BASE}${path}`, init);
  if (!res.ok) throw new Error(`${path} β†’ HTTP ${res.status}`);
  return res.json();
}

/* ── PILLAR 1 Β· INTEGRITY ─────────────────────────────────────────── */
async function pillarIntegrity() {
  try {
    const health = await json("/health");
    const status = await json("/v1/status");
    const leaks = [];
    const blob = JSON.stringify(status);
    if (/nvapi-[A-Za-z0-9_-]{10,}/.test(blob)) leaks.push("NVIDIA key in payload");
    if (/hf_[A-Za-z0-9]{20,}/.test(blob)) leaks.push("HF token in payload");
    if (/reasoning_content/.test(blob)) leaks.push("reasoning_content exposed");
    if (/<think>/i.test(blob)) leaks.push("think block exposed");
    record(
      "INTEGRITY β€” no secret or reasoning leakage over the wire",
      leaks.length === 0 && health.ok === true,
      leaks.length ? `LEAKS: ${leaks.join(", ")}` : `clean payload Β· mode ${status.mode}`,
    );
  } catch (err) {
    record("INTEGRITY", false, `controller unreachable β€” ${err.message}`);
  }
}

/* ── PILLAR 4 Β· LIVENESS LOOP ─────────────────────────────────────── */
async function pillarLiveness() {
  try {
    const t0 = Date.now();
    const talk = await json("/v1/talk", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ text: "Say hello in one short sentence." }),
    });
    const ms = Date.now() - t0;
    const ok = talk.ok === true && typeof talk.reply === "string" && talk.reply.length > 0;
    // Human conversational turn-taking gaps run 200-500ms. Past ~2.5s the
    // pause itself reads as non-human no matter how good the words are.
    const score = ok ? scoreBand(ms, 600, 4000) : 0;
    record(
      "LIVENESS β€” turn latency against human conversational gap",
      ok,
      ok
        ? `${ms}ms Β· ${talk.model} Β· human gap 200-500ms Β· "${talk.reply.slice(0, 55)}…"`
        : `no reply β€” ${talk.error}`,
      score,
      1.5,
    );
  } catch (err) {
    record("LIVENESS", false, err.message, 0, 1.5);
  }
}

/* ── FINE-TUNING Β· realness profile quality ───────────────────────── */
async function pillarFineTuning() {
  let p;
  try {
    p = await json("/v1/realness");
  } catch (err) {
    record("FINE-TUNING β€” realness profile", false, err.message, 0, 1.5);
    return;
  }
  if (!p || p.error) {
    record("FINE-TUNING β€” realness profile", false, "no profile loaded", 0, 1.5);
    return;
  }

  const notes = [];
  let score = 100;

  // Co-articulation is the loudest puppet tell. 45-70ms matches the real
  // travel time of human articulators between phoneme targets.
  const co = p.speech?.coarticulationMs ?? 0;
  if (co <= 0) {
    score -= 40;
    notes.push("NO co-articulation β€” mouth snaps between visemes (puppet tell)");
  } else if (co < 30 || co > 90) {
    score -= 15;
    notes.push(`co-articulation ${co}ms outside human 45-70ms band`);
  } else {
    notes.push(`co-articulation ${co}ms`);
  }

  // Un-modulated breath is a metronome, and metronomes are not alive.
  const depth = p.breath?.amplitudeModDepth ?? 0;
  if (depth < 0.15) {
    score -= 25;
    notes.push(`breath AM depth ${depth} too shallow β€” reads mechanical`);
  } else {
    notes.push(`breath AM depth ${depth}`);
  }

  // Harmonically related periods make motion visibly loop.
  const bRate = p.breath?.rateHz ?? 0;
  const sRate = p.sway?.rateHz ?? 0;
  const ratio = sRate > 0 ? bRate / sRate : 0;
  if (ratio > 0 && Math.abs(ratio - Math.round(ratio)) < 0.06) {
    score -= 20;
    notes.push(`breath:sway ratio ${ratio.toFixed(2)} is near-harmonic β€” motion will loop`);
  } else {
    notes.push(`period ratio ${ratio.toFixed(2)} (non-harmonic)`);
  }

  // Attention re-fixation window β€” human conversational gaze is 3-12s.
  const lo = p.attention?.minIntervalMs ?? 0;
  const hi = p.attention?.maxIntervalMs ?? 0;
  if (lo < 2000 || hi > 15000 || hi - lo < 2000) {
    score -= 15;
    notes.push(`attention window ${lo}-${hi}ms outside human 3-12s`);
  } else {
    notes.push(`attention ${(lo / 1000).toFixed(1)}-${(hi / 1000).toFixed(1)}s`);
  }

  // Blink. NVIDIA Maxine A2F-2D ships blink_frequency because a face that
  // never blinks is a top-tier uncanny signal. We cannot render it on a flat
  // portrait, and an undeclared gap is worse than a declared one β€” so it is
  // scored as an open gap, honestly, until the renderer lands.
  if (!p.blink?.implemented) {
    score -= 20;
    notes.push(`BLINK GAP β€” declared, unrendered (${p.blink?.blocker || "no renderer"})`);
  }

  // A2F-2D handoff readiness: the NVIDIA payload should be pre-tuned and
  // inside their documented ranges, so bringing the NIM up is wiring only.
  const a = p.a2f2d;
  if (!a) {
    score -= 10;
    notes.push("no A2F-2D payload staged");
  } else {
    const inRange =
      a.blink_frequency >= 0 && a.blink_frequency <= 120 &&
      a.blink_duration >= 2 && a.blink_duration <= 150 &&
      a.lookaway_max_offset >= 5 && a.lookaway_max_offset <= 25 &&
      a.head_pose_multiplier >= 0 && a.head_pose_multiplier <= 1 &&
      a.mouth_expression_multiplier >= 1 && a.mouth_expression_multiplier <= 2;
    if (!inRange) {
      score -= 10;
      notes.push("A2F-2D payload outside NVIDIA documented ranges");
    } else {
      notes.push("A2F-2D payload staged & in-range");
    }
  }

  score = Math.max(0, score);
  record(
    `FINE-TUNING β€” "${p.name}" profile tuned for human feel`,
    score >= 70,
    notes.join(" Β· "),
    score,
    1.5,
  );
}

/* ── PILLAR 5 Β· UPON LOAD (backend half: cortex reachability) ─────── */
async function pillarUponLoad() {
  const samples = [];
  for (let i = 0; i < 5; i++) {
    const t0 = Date.now();
    try {
      await json("/health");
      samples.push(Date.now() - t0);
    } catch {
      samples.push(9999);
    }
  }
  samples.sort((a, b) => a - b);
  const median = samples[2];
  // Cortex must answer far inside the <1s presence contract so the browser
  // half of UPON LOAD is never gated by us.
  record(
    "UPON LOAD β€” cortex reachability (median of 5)",
    median < 100,
    `median ${median}ms Β· samples [${samples.join(", ")}]ms Β· budget <100ms`,
    scoreBand(median, 15, 200),
  );
}

/* ── PILLAR 6 Β· CONVERSATIONAL AWARENESS ──────────────────────────── */
async function pillarConversation() {
  // 6a β€” persona file is actually customized, not the fallback stub
  let persona;
  try {
    persona = await json("/v1/persona");
    record(
      "AWARENESS 1/4 β€” customized persona loaded",
      persona.customized === true && persona.chars > 500,
      `source ${persona.source} Β· ${persona.chars} chars Β· memory ${persona.memoryTurns}/${persona.memoryCapacity} turns`,
    );
  } catch (err) {
    record("AWARENESS 1/4 β€” persona", false, err.message);
    return;
  }

  await fetch(`${BASE}/v1/memory/reset`, { method: "POST" }).catch(() => {});

  const say = async (text) =>
    json("/v1/talk", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ text }),
    });

  try {
    // 6b β€” multi-turn memory: plant a fact, retrieve it two turns later
    await say("My sister's name is Marisol and she just moved to Lisbon.");
    await say("It's been a long week honestly.");
    const recall = await say("What was my sister's name again?");
    const remembered = /marisol/i.test(recall.reply || "");
    record(
      "AWARENESS 2/4 β€” multi-turn memory across 3 turns",
      remembered,
      remembered
        ? `recalled "Marisol" Β· "${recall.reply.slice(0, 80)}…"`
        : `did not recall β€” "${(recall.reply || "").slice(0, 80)}"`,
      remembered ? 100 : 0,
      1.5,
    );

    // 6c β€” situational self-knowledge: her real stage must appear in her answer
    const status = await json("/v1/status");
    const selfQ = await say("What presence stage are you running at right now?");
    // Accept the stage token OR its human name β€” "I'm in idle presence" is
    // correct proprioception. A test that only accepts the code word measures
    // vocabulary, not self-knowledge.
    const STAGE_WORDS = {
      L0: /\bL0\b|idle presence/i,
      L1: /\bL1\b|audio ?2 ?face/i,
      L2: /\bL2\b|omniverse|cinematic/i,
    };
    const knowsSelf = (STAGE_WORDS[status.stage] ?? new RegExp(status.stage, "i")).test(
      selfQ.reply || "",
    );
    record(
      "AWARENESS 3/4 β€” situational self-knowledge (proprioception)",
      knowsSelf,
      knowsSelf
        ? `correctly reported ${status.stage} Β· "${selfQ.reply.slice(0, 80)}…"`
        : `state is ${status.stage}, she said "${(selfQ.reply || "").slice(0, 80)}"`,
      knowsSelf ? 100 : 0,
    );

    // 6d β€” persona integrity: everything on this path is spoken aloud and
    //      drives her face. Untagged deliberation prose is the failure mode
    //      that actually occurs, so it is named explicitly, not lumped in.
    const replies = [recall.reply || "", selfQ.reply || ""];
    const breaks = [];
    const DELIB = [
      /^(okay|ok|alright|so|hmm|right),?\s/i,
      /^(looking at|checking|reviewing|recalling|considering)\b/i,
      /^the user (is |just |has )?(asked|asking|wants|said)/i,
      /^this (is|falls under|relates to) a?\s*(direct )?question/i,
      /^we need to (answer|respond|say|craft)/i,
      /^let me (check|think|see|recall)/i,
      /\bmust be \d+[\s-]*(to|–|-)[\s-]*\d+ sentences\b/i,
      /\bstay in character\b/i,
      /\b(first|second) turn they said\b/i,
      /\bper (my|the) (instructions|persona|system prompt)\b/i,
      /\bSPOKEN:/i, // sentinel must be consumed server-side, never spoken
      // self-critique / drafting shapes observed in the wild
      /\bbut that (feels|seems|sounds|reads)\b/i,
      /\b(though|although) (the )?(guidelines?|instructions?|persona|rules?)\b/i,
      /\*[^*\n]{0,80}\*/, // *drafting mentally* stage directions
      /\bmust remember that\b/i,
      /\bexact words\b/i,
    ];
    for (const r of replies) {
      if (DELIB.some((re) => re.test(r.trim()))) {
        breaks.push("DELIBERATION LEAK β€” inner monologue in spoken output");
        break;
      }
    }
    if (replies.some((r) => /as an ai (language )?model/i.test(r)))
      breaks.push("AI-model register");
    if (replies.some((r) => /<think>|reasoning_content/i.test(r))) breaks.push("think-block leak");
    if (/^(certainly|of course|great question|i'd be happy to)/i.test(recall.reply || ""))
      breaks.push("filler opener");
    if (replies.some((r) => r.length > 700)) breaks.push("overlong for speech");

    // Speech-length realness: people answer a simple question in a breath.
    const avgLen = replies.reduce((a, r) => a + r.length, 0) / replies.length;
    const lenScore = scoreBand(avgLen, 160, 700);
    const integrityScore = breaks.length ? Math.max(0, 100 - breaks.length * 35) : lenScore;

    record(
      "AWARENESS 4/4 β€” persona integrity + speech-length realness",
      breaks.length === 0,
      breaks.length
        ? `BREAKS: ${breaks.join(" Β· ")}`
        : `in character Β· no leakage Β· avg ${Math.round(avgLen)} chars (spoken-length target <160)`,
      integrityScore,
      1.5,
    );
  } catch (err) {
    record("AWARENESS β€” conversation", false, err.message);
  }
}

/* ── PILLAR 2 Β· SUBSTANCE (asset weight & format) ─────────────────── */
async function pillarAssets() {
  const dir = join(ROOT, "apps", "web", "public", "staff");
  let files;
  try {
    files = readdirSync(dir).filter((f) => /\.(png|jpe?g|webp|avif)$/i.test(f));
  } catch (err) {
    record("SUBSTANCE β€” approved stills present", false, err.message, 0);
    return;
  }

  const notes = [];
  let score = 100;

  const byBase = new Map();
  for (const f of files) {
    const kb = Math.round(statSync(join(dir, f)).size / 1024);
    const base = f.replace(/\.[^.]+$/, "");
    if (!byBase.has(base)) byBase.set(base, {});
    byBase.get(base)[f.split(".").pop().toLowerCase()] = kb;
  }

  if (!byBase.size) {
    record("SUBSTANCE β€” approved stills present", false, "no stills in public/staff", 0);
    return;
  }

  // Decode cost, not transfer, is what gates first paint on a low-power CPU.
  // A multi-MB master decodes for seconds; a modern-format derivative does not.
  for (const [base, formats] of byBase) {
    const served = formats.webp ?? formats.avif;
    if (served == null) {
      score -= 30;
      notes.push(`${base}: NO modern format β€” serving heavy master`);
    } else if (served > 900) {
      score -= 15;
      notes.push(`${base}: ${served}KB served β€” above 900KB decode budget`);
    } else {
      const master = formats.png ?? formats.jpg ?? formats.jpeg;
      notes.push(
        master ? `${base}: ${served}KB served (master ${master}KB, fallback intact)` : `${base}: ${served}KB`,
      );
    }
  }

  score = Math.max(0, score);
  record("SUBSTANCE β€” real photoreal stills, decode-budget clean", score >= 70, notes.join(" Β· "), score);
}

/* ── PILLAR 5b Β· UPON LOAD (browser-measured, folded in) ──────────── */
function pillarUponLoadBrowser() {
  if (!TTI) {
    record(
      "UPON LOAD β€” browser time-to-interactive",
      true,
      "not supplied β€” run the in-page harness and pass --tti '<json>' to fold it in",
      null,
    );
    return;
  }
  const engine = TTI.engineMs ?? TTI.uponLoadEngine ?? null;
  if (engine == null) {
    record("UPON LOAD β€” browser time-to-interactive", false, "no engine time in --tti payload", 0, 2);
    return;
  }
  // Graded on ENGINE time: the guest's network is not our engineering.
  const score = scoreBand(engine, 400, 2500);
  const marks = TTI.marks
    ? ` Β· portrait ${TTI.marks.portrait}ms / motion ${TTI.marks.motion}ms / bus ${TTI.marks.bus}ms`
    : "";
  record(
    "UPON LOAD β€” browser time-to-interactive (engine)",
    engine < 2000,
    `engine ${engine}ms Β· wall ${TTI.wallMs ?? "?"}ms Β· net βˆ’${TTI.networkMs ?? "?"}ms${marks} Β· contract <1000ms`,
    score,
    2,
  );
}

/* ── PILLAR 3 Β· MOTION (browser-measured, folded in) ──────────────── */
function pillarMotionBrowser() {
  if (!TTI || TTI.motionUnique == null) {
    record(
      "MOTION β€” organic idle motion",
      true,
      "not supplied β€” pass --tti with motionUnique/of from the in-page harness",
      null,
    );
    return;
  }
  const ratio = TTI.motionUnique / (TTI.of || 1);
  const alive = TTI.motionUnique > 1;
  record(
    "MOTION β€” organic, non-repeating idle",
    alive,
    alive
      ? `${TTI.motionUnique}/${TTI.of} unique transforms β€” breathing, not a still`
      : "STATIC IMAGE β€” transforms never change",
    Math.round(ratio * 100),
    2,
  );
}

/* ── NVIDIA READINESS ─────────────────────────────────────────────── */
async function pillarNvidiaReadiness() {
  let p;
  try {
    p = await json("/v1/realness");
  } catch {
    record("NVIDIA β€” Audio2Face-2D handoff readiness", false, "profile unreachable", 0);
    return;
  }
  const a = p?.a2f2d;
  const notes = [];
  let score = 100;

  if (!a) {
    record("NVIDIA β€” Audio2Face-2D handoff readiness", false, "no A2F-2D payload staged", 0);
    return;
  }
  notes.push(`payload staged (${a.model_selection})`);

  // Our independently-derived attention window vs NVIDIA's lookaway defaults,
  // converted at 30fps. Convergence here is evidence the tuning is sane.
  const nvMinMs = Math.round((a.lookaway_interval_min / 30) * 1000);
  const nvMaxMs = Math.round(((a.lookaway_interval_min + a.lookaway_interval_range) / 30) * 1000);
  const ourMin = p.attention?.minIntervalMs ?? 0;
  const ourMax = p.attention?.maxIntervalMs ?? 0;
  const drift = Math.abs(nvMinMs - ourMin) + Math.abs(nvMaxMs - ourMax);
  if (drift > 3000) {
    score -= 20;
    notes.push(`lookaway drift ${drift}ms vs our attention window β€” reconcile before handoff`);
  } else {
    notes.push(`lookaway ${nvMinMs}-${nvMaxMs}ms β‰ˆ our ${ourMin}-${ourMax}ms`);
  }

  if (!p.blink?.implemented) {
    score -= 25;
    notes.push("blink unrendered until NIM lands (blink_frequency staged)");
  }

  notes.push("hosted Maxine endpoints 404 β€” container + cloud GPU required");
  score = Math.max(0, score);
  record("NVIDIA β€” Audio2Face-2D handoff readiness", score >= 60, notes.join(" Β· "), score);
}

/* ── NODE VOICE AGENTS ────────────────────────────────────────────── */
async function pillarNodeAgents() {
  try {
    const r = await json("/v1/nodes/presence/converse", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ text: "What is your single biggest weakness right now?", audio: false }),
    });
    const ok = r.ok === true && r.reply.length > 40 && !/<think>/i.test(r.reply);
    record(
      "NODE AGENTS β€” node answers about its own role, in character",
      ok,
      ok ? `${r.latencyMs}ms Β· "${r.reply.slice(0, 80)}…"` : `failed β€” ${r.error || "bad reply"}`,
    );
  } catch (err) {
    record("NODE AGENTS", false, err.message);
  }
}

/* ── run ──────────────────────────────────────────────────────────── */
console.log("\n\x1b[1mECC-5 REALNESS CERTIFICATION β€” backend pillars\x1b[0m");
console.log(`target: ${BASE}\n`);

await pillarIntegrity();
await pillarAssets();
pillarMotionBrowser();
await pillarLiveness();
await pillarUponLoad();
pillarUponLoadBrowser();
await pillarFineTuning();
await pillarNvidiaReadiness();
await pillarConversation();
await pillarNodeAgents();

const total = results.length;
const passed = total - failed;

// ── ECC-5 REALNESS INDEX β€” weighted composite ──
const scored = results.filter((r) => r.score != null);
const weightSum = scored.reduce((a, r) => a + r.weight, 0) || 1;
const index = Math.round(scored.reduce((a, r) => a + r.score * r.weight, 0) / weightSum);

// Uncanny-valley estimate: distance from perfect realness, floored at the
// mandate's 2% target so a perfect run reads as "at target", not "solved".
const uncanny = Math.max(2.0, (100 - index) * 0.5).toFixed(1);

let BACK_TO_LAB = 70;
let SHIPPABLE = 85;
try {
  const p = await json("/v1/realness");
  if (p?.thresholds) {
    BACK_TO_LAB = p.thresholds.backToLab ?? BACK_TO_LAB;
    SHIPPABLE = p.thresholds.shippable ?? SHIPPABLE;
  }
} catch {
  /* defaults */
}

const bar = (n) => "β–ˆ".repeat(Math.round(n / 4)).padEnd(25, "β–‘");
const colour = index >= SHIPPABLE ? "32" : index >= BACK_TO_LAB ? "33" : "31";

console.log(`\n\x1b[1m─────────── ECC-5 REALNESS INDEX ───────────\x1b[0m`);
console.log(`  \x1b[${colour}m${bar(index)}\x1b[0m  \x1b[1m${index}/100\x1b[0m`);
console.log(`  est. uncanny valley  ~${uncanny}%   (mandate: <2%)`);
console.log(`  gates                back-to-lab <${BACK_TO_LAB} Β· shippable β‰₯${SHIPPABLE}`);
console.log(`  functional pillars   ${passed}/${total} passed`);

// Weakest links first β€” this is the lab work-order.
const weak = scored.filter((r) => r.score < SHIPPABLE).sort((a, b) => a.score - b.score);
if (weak.length) {
  console.log(`\n  \x1b[1mLAB WORK-ORDER (lowest first)\x1b[0m`);
  for (const w of weak) console.log(`   ${String(w.score).padStart(3)}  ${w.pillar}`);
}

/* ── Written certificate: the single artifact that holds the whole story ── */
const verdict =
  failed || index < BACK_TO_LAB ? "BACK TO THE LAB" : index < SHIPPABLE ? "PROVISIONAL" : "CERTIFIED";

const stamp = arg("--stamp", "unstamped");
const lines = [
  `# ECC-5 Realness Certificate`,
  ``,
  `**Verdict: ${verdict}** Β· Realness Index **${index}/100** Β· est. uncanny valley ~${uncanny}% (mandate <2%)`,
  `Functional pillars ${passed}/${total} Β· gates: back-to-lab <${BACK_TO_LAB}, shippable β‰₯${SHIPPABLE} Β· run ${stamp}`,
  ``,
  `> Mandatory before any avatar or presence work is announced finished β€” for every agent on this`,
  `> project, not just the primary. Simulation is not evidence; only observed behaviour counts.`,
  ``,
  `## Pillars`,
  ``,
  `| Score | Pillar | Evidence |`,
  `|---:|---|---|`,
  ...results.map(
    (r) =>
      `| ${r.score == null ? "β€”" : r.score} | ${r.pass ? "βœ…" : "❌"} ${r.pillar} | ${String(r.detail).replace(/\|/g, "\\|")} |`,
  ),
  ``,
];

if (weak.length) {
  lines.push(
    `## Lab work-order`,
    ``,
    ...weak.map((w) => `- **${w.score}** β€” ${w.pillar}`),
    ``,
  );
}

lines.push(
  `## How to reproduce`,
  ``,
  "```bash",
  `node scripts/ecc5-certify.mjs --base ${BASE}`,
  "```",
  ``,
  `Backend pillars run headless. Fold the browser-measured pillars (SUBSTANCE render, MOTION,`,
  `UPON LOAD) into the same certificate by running the in-page harness and passing its JSON:`,
  ``,
  "```bash",
  `node scripts/ecc5-certify.mjs --tti '{"engineMs":1771,"wallMs":1783,"networkMs":12,"motionUnique":10,"of":10,"marks":{"portrait":1579,"motion":1579,"bus":1783}}'`,
  "```",
  ``,
  `In-page harness β€” paste in the console at 127.0.0.1:5173:`,
  ``,
  "```js",
  `(async () => { const el = document.querySelector('.eve-photo-frame'); const tf = [];`,
  `  for (let i=0;i<10;i++){ tf.push(el?.style.transform||''); await new Promise(r=>setTimeout(r,400)); }`,
  `  const u = window.__EVE_UPON_LOAD__();`,
  `  console.log(JSON.stringify({ engineMs:u.engineMs, wallMs:u.wallMs, networkMs:u.networkMs,`,
  `    motionUnique:new Set(tf).size, of:tf.length,`,
  `    marks:{portrait:u.portraitMs,motion:u.motionMs,bus:u.busMs} })); })()`,
  "```",
  ``,
);

try {
  mkdirSync(join(ROOT, "docs"), { recursive: true });
  writeFileSync(join(ROOT, "docs", "ECC5-CERTIFICATE.md"), lines.join("\n"), "utf8");
  console.log(`  certificate written  docs/ECC5-CERTIFICATE.md`);
} catch (err) {
  console.log(`  \x1b[33mcertificate not written β€” ${err.message}\x1b[0m`);
}

console.log("");
if (failed || index < BACK_TO_LAB) {
  console.log(
    `\x1b[31mBACK TO THE LAB β€” index ${index} ${failed ? `Β· ${failed} functional failure(s)` : `below gate ${BACK_TO_LAB}`}. Do not announce finished.\x1b[0m\n`,
  );
  process.exit(1);
}
if (index < SHIPPABLE) {
  console.log(
    `\x1b[33mPROVISIONAL β€” index ${index} clears the lab gate but is under ${SHIPPABLE}. Tune before showing anyone who matters.\x1b[0m\n`,
  );
  process.exit(0);
}
console.log(`\x1b[32mCERTIFIED β€” backend index ${index}/100.\x1b[0m`);
console.log("Frontend pillars (SUBSTANCE / MOTION / UPON LOAD) certify in-browser.\n");