HEL-896 release completion: the A/B/C budget becomes an executable two-instance split, the real-browser false positive is fixed precisely (product untouched), the SDK gap list is corrected to the honest 41-distribution closure with the pip-download erratum, and release archiving becomes a consistency snapshot - (1) budget split: the manager's independent review reproduced on a temp store that writing A's total_requests=55 into the shared product ledger blocks B's mem0_extract and C's dialogue_main with budget_total_requests_exhausted:55/55 while budget_total/request_usage/token_usage have no stage or authorization-source column; docs/budget-package-hel895.md gains §6 making the split executable: A lives ONLY on the isolated 8360 team-test instance with its own DB and models.yaml (55/500000 one-shot totals plus same-value daily category caps), the user instance NEVER carries one-shot totals (its budget_total rows are record-only, no gate), A is sealed by stop+consistent-snapshot archiving with budget_total never zeroed and restart/archive proving the seal holds, old test data has no import path into the user instance (release checklist forbids copying the 8360 data dir), B starts only after baiqizhi approval writes llm_cap/embed_cap per the 500+180 formula with the authority frozen prefix, the real-Mem0 smoke is counted INSIDE B's 60/180, B cap-hit queues batches (no retry burn, no lost rows, FTS fallback, chat uninterrupted) and first-week end requires a fresh approval to continue, and §6.4 gives one responsible limited recommendation (A 55/500k isolated, B 60 LLM/180 embeds, C daily table) plus errata for the two unsafe original claims ('A shares C's daily account' and 'WAL single file copies whole'); tools/verify_budget_split_hel896.py 8/8 on temp stores and stand-ins only (S0 exact-shape repro of the manager's finding, S1 team instance consumes the §1 step plan to 55 then hard-stops with the tightest gate winning - life daily 8/8 rejects before the total, S2 seal survives restart and backup-API archive, S3 user instance B/C unblocked after A with dialogue 60/semantic 40/daily-token stacking and rejections booking nothing, S4 the misconfigured-total guard on the user instance, S5 repo configs and authoritative facts untouched, real caps all stay 0); (2) browser false positive fixed without touching any product file: web/tests/hel895_real.mjs B3 used '!!stage || any visible button' and clicked the FIRST button containing 回 which is the 日子与回忆 home nav button, so stage=false still PASSed and the screenshot stayed on days - the verbatim original rerun reproduces the false 7/7 with B3 stage=false (docs/rework/hel896/browser-before/), and the revised test passes 9 checks by precise interaction: B2 asserts the letter card carries her exact words plus the talk-nav unread aria-label, B3a waits for the VISIBLE reach card (aside.reach.show, aria-hidden=false, non-zero box, exact words) over days, B3b clicks only THAT card's 回她 button and strictly asserts the conversation stage .conversation .sr contains the reach-out text with the unread mark cleared, B4/B5 prove dedup by server message id (data-mid in the record panel: zero duplicates, gap and live reach-outs each exactly once), B5 asserts /api/health epoch bumps exactly +1 (1->2) before rechecking, B6 counts the page's OWN permissions.query/getUserMedia calls from first document load (0/0, instrumented via Page.addScriptToEvaluateOnNewDocument after Page.enable), B7 runs the service under a temp loopback models config (CYBERGRIL_MODELS, all caps 0) plus a sitecustomize socket guard that REJECTS and eagerly reports non-loopback connects (0 attempts, 0 non-loopback DNS lookups, report survives signal death) - under precise interaction the stage really plays, unread really clears, dedup and epoch semantics really hold: it was a test defect, not a product defect, so no interface change and nothing to escalate; (3) SDK honesty: tools/audit_sdk_offline_hel896.py (read-only, zero downloads/installs/inference) computes the 3.11-Linux closure from the installed 3.10 pinned metadata - 55 dists, 41 missing from the product venv (28 pure + 13 native incl. grpcio/numpy/onnxruntime/tokenizers/sqlalchemy/protobuf), all three top-level pins are py3-none-any (no 'cp311 wheel' needed for them), mem0ai's installed direct_url is the local fixed source hel857-src and hel857-data/mem0-2c81af3.tar.gz hashes exactly to the lock's 9dcef930...dda23 (an index mem0ai==2.2.1 wheel proves nothing), the wheel built during hel857 lived only in an ephemeral cache and hatchling is not offline-available, exactly 3 of the 41 are cache-reusable today for 3.11 (greenlet 3.5.6 cp311, pillow 12.3.0 cp311, truststore 0.10.5 py3-none-any - version+tag verified), the fastembed model cache is measured (Qdrant/bge-small-zh-v1.5 + bm25, ~92MB, placement = instance data dir copy), and the seq48-51 pip event is settled by cache forensics: uv's pip-26.2.2 wheel entry (files.pythonhosted.org, sha256 fd7f4dfa...) was CREATED 2026-10-27 02:10:04 inside the HEL-895 run window as the ONLY new cache entry, so that step DID fetch from the network - the prior card's zero-download claim is corrected to 'download' by the conservative reading (byte-level download vs conditional request is indistinguishable from cache evidence) while the lock install itself added no new cache entries; deploy/hel895-release-candidate.md §4 is rewritten to this accurate list, all future installs forced offline/no-index; (4) release archiving: tools/release_snapshot_hel896.py implements the two safe modes (stop+wal_checkpoint(TRUNCATE)+copy, or online SQLite backup API), writes per-file sha256 manifests carrying the exact code commit, per-table row-count verification and a verify-mode rollback drill; its selftest reproduces the manager's WAL finding (online naive copy of the main .db: 'no such table: companion') and proves both fixed modes complete (backup API and checkpoint copies both hold companion=1/chat_message=1, archive hashes+rows verify, commit 04eff61 recorded); §5 of the release doc now carries the copy-paste commands covering the product DB, semantic vector root, history root and the authoritative embed ledger, archives are never deleted, and the section explicitly does NOT claim R6 complete backup; regression on this head: pytest 299/299 (3.11.16 venv + requirements.lock offline), ruff clean (src/tests/tools), web typecheck 0 errors / lint 0 errors 1 pre-existing warning / vitest 55/55 / build passes with CSS still index-DdDYzR5S.css, pinned-SDK reruns all green (close-ownership 16/16, shutdown-queued 12/12, inflight 6/6, semantic-recovery 7/7, mem0-real 12/12, reports in docs/rework/hel896/regression/), check_release_offline R1-R7 passes, real-HTTP pagination 7/7 rerun saved as docs/rework/hel896/http-pagination-rerun.json with the original hel895 evidence byte-untouched, requirement checks 6/6 (origin/main, de8874a3803b, 152479b, each with and without handoff-HEL-896.json); handoff-HEL-896.json written; zero real LLM, zero real embeddings, zero new downloads beyond existing caches, authoritative ledgers and freezes (39/60, 498/500, 2 frozen, HEL-835 gate) untouched, not deployed, PR#11 appended-not-merged, no visual changes, R5/R6/R7 honestly deferred
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
co-authored by
multica-agent
parent
04eff611e7
commit
c121c42e39
+136
-34
@@ -1,7 +1,20 @@
|
||||
// HEL-895 real-server browser check: drives headless Chromium over CDP against the REAL product API
|
||||
// (python -m cybergril.api serving web/dist), not the mock. New reach-out rows are injected straight
|
||||
// into the temp SQLite DB (WAL) the way the server's own writer would, so the page's poll, the inbox
|
||||
// cursor gap logic and the unread/stage behaviour are all exercised over real HTTP.
|
||||
// HEL-895 real-server browser check, HEL-896 revision: drives headless Chromium over CDP against the REAL
|
||||
// product API (python -m cybergril.api serving web/dist), not the mock. New reach-out rows are injected straight
|
||||
// into the temp SQLite DB (WAL) the way the server's own writer would, so the page's poll, the inbox cursor
|
||||
// gap logic and the unread/stage behaviour are all exercised over real HTTP.
|
||||
//
|
||||
// HEL-896 fixes the false positives the manager's independent review proved (docs/rework/hel896/):
|
||||
// - B3 clicked "the first button containing 回" (the 日子与回忆 nav button) and passed on `stage || any
|
||||
// visible button`. Now it navigates to 日子, waits for the VISIBLE reach card (aside.reach.show) carrying
|
||||
// exactly this reach-out's words, clicks THAT card's 回她 button, and strictly asserts the conversation
|
||||
// stage text (.conversation .sr) plus the unread mark clearing. No fallback.
|
||||
// - B4/B5 dedup evidence is by server message id (data-mid in the record panel), not "1–2 full-page text
|
||||
// matches"; B5 asserts the restart epoch really is +1 (via /api/health) before re-checking the record.
|
||||
// - B6 counts the page's own Permissions API / getUserMedia CALLS (instrumented before load), not just states.
|
||||
// - The service runs with a temp loopback-only models config (CYBERGRIL_MODELS, all caps 0) and a
|
||||
// sitecustomize socket guard that REJECTS and counts any non-loopback connect, so "zero non-loopback
|
||||
// outbound" is enforced and evidenced (netguard.json), not assumed. The default /api/health provider probe
|
||||
// therefore hits a closed loopback port and reports llm.ok=false — that is the isolation working.
|
||||
// Usage: node tests/hel895_real.mjs <chrome> <venvPython> <repoRoot> <outDir> [port]
|
||||
import { spawn } from 'node:child_process';
|
||||
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
@@ -11,7 +24,7 @@ import { DatabaseSync } from 'node:sqlite';
|
||||
|
||||
const [chrome, venv, root, outArg, portArg] = process.argv.slice(2);
|
||||
const port = Number(portArg || 8398), base = `http://127.0.0.1:${port}`, cdpPort = 9498;
|
||||
const out = join(root, outArg || 'docs/rework/hel895');
|
||||
const out = join(root, outArg || 'docs/rework/hel896/browser');
|
||||
mkdirSync(out, { recursive: true });
|
||||
const work = join(tmpdir(), `hel895-real-${Date.now()}`);
|
||||
mkdirSync(work, { recursive: true });
|
||||
@@ -20,7 +33,48 @@ const results = [];
|
||||
const check = (name, ok, detail = '') => { results.push(ok); console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ` — ${detail}` : ''}`); };
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
|
||||
// ── Seed: companion + 5 history rows (one old reach-out) — the same shape as the HEL-875 mock history.
|
||||
// ── HEL-896 isolation: loopback-only provider config (caps all 0) + socket guard that rejects non-loopback. ──
|
||||
const loopbackBase = 'http://127.0.0.1:9/v1'; // nothing listens there: provider probes fail fast on loopback
|
||||
writeFileSync(join(work, 'models-loopback.yaml'), [
|
||||
'# HEL-896 browser-check isolation config: loopback-only provider, every budget cap 0 (fail-closed).',
|
||||
'tiers:',
|
||||
' high: {provider: openai_compat, model: loopback-closed, base_url: "' + loopbackBase + '", api_key_env: null, timeout: 2.0, temperature: 0.1}',
|
||||
' standard: {provider: openai_compat, model: loopback-closed, base_url: "' + loopbackBase + '", api_key_env: null, timeout: 2.0, temperature: 0.1}',
|
||||
' low: {provider: openai_compat, model: loopback-closed, base_url: "' + loopbackBase + '", api_key_env: null, timeout: 2.0, temperature: 0.1}',
|
||||
'budget:',
|
||||
' daily_tokens: 2000000',
|
||||
' daily_requests: {dialogue: 0, life: 0, background: 0, semantic: 0}',
|
||||
'embedding: {provider: openai_compat, model: loopback-closed, base_url: "' + loopbackBase + '", api_key_env: null, dim: 1024}',
|
||||
'asr: {provider: scripted, model: none, language: zh}',
|
||||
'tts: {provider: silence, model: none}',
|
||||
'vad: {provider: energy, model: none}',
|
||||
'turn: {provider: heuristic, silence_min_ms: 150, silence_hard_end_ms: 800}',
|
||||
'paralinguistic: {provider: scripted, model: none, enabled: false}',
|
||||
'avatar: {route: none, renderer: none, lipsync: envelope}',
|
||||
''].join('\n'));
|
||||
const guard = join(work, 'guard');
|
||||
mkdirSync(guard, { recursive: true });
|
||||
// The guard writes its report EAGERLY (import time + every event, tmp+rename): a uvicorn SIGTERM exit can die
|
||||
// by signal without running atexit, and a missing report must never be read as "zero attempts".
|
||||
writeFileSync(join(guard, 'sitecustomize.py'), [
|
||||
'import json, os, socket, tempfile',
|
||||
"LOOP = {'127.0.0.1', '::1', 'localhost'}",
|
||||
"state = {'guard_loaded': True, 'nonloopback_connect_attempts': 0, 'nonloopback_dns_lookups': 0, 'rejected': []}",
|
||||
'def _host(a):\n try:\n return a[0]\n except Exception:\n return str(a)',
|
||||
'def _dump():\n try:\n d = os.path.dirname(os.environ["NETGUARD_OUT"])\n fd, tmp = tempfile.mkstemp(dir=d)\n with os.fdopen(fd, "w") as f:\n json.dump(state, f)\n os.replace(tmp, os.environ["NETGUARD_OUT"])\n except Exception:\n pass',
|
||||
'_connect = socket.socket.connect',
|
||||
'def connect(self, address):\n if _host(address) not in LOOP:\n state["nonloopback_connect_attempts"] += 1\n state["rejected"].append(str(address))\n _dump()\n raise ConnectionRefusedError("non-loopback blocked: " + str(address))\n return _connect(self, address)',
|
||||
'socket.socket.connect = connect',
|
||||
'_create = socket.create_connection',
|
||||
'def create_connection(address, *a, **k):\n if _host(address) not in LOOP:\n state["nonloopback_connect_attempts"] += 1\n state["rejected"].append(str(address))\n _dump()\n raise ConnectionRefusedError("non-loopback blocked: " + str(address))\n return _create(address, *a, **k)',
|
||||
'socket.create_connection = create_connection',
|
||||
'_gai = socket.getaddrinfo',
|
||||
'def getaddrinfo(host, *a, **k):\n if host not in LOOP:\n state["nonloopback_dns_lookups"] += 1\n _dump()\n return _gai(host, *a, **k)',
|
||||
'socket.getaddrinfo = getaddrinfo',
|
||||
'_dump()',
|
||||
''].join('\n'));
|
||||
|
||||
// ── Seed: companion + 5 history rows (one old reach-out) — the same shape as the HEL-875 mock history. ──
|
||||
const T0 = Date.UTC(2026, 9, 25, 12);
|
||||
const identity = { id: '1', name: '栖', birth: '2000-03-14', hour: '子时', relation: '朋友', nickname: '', boundary: '', color: { pillars: { year: '庚辰', month: '己卯', day: '丙午', hour: '戊子' }, traits: 'HEL-895 真实服务浏览器检查合成档案' } };
|
||||
let seeded = 0;
|
||||
@@ -28,7 +82,7 @@ const seedRow = (role, text, turn, proactive = 0) => { seeded++; db.prepare('INS
|
||||
let db = new DatabaseSync(dbPath);
|
||||
db.exec('PRAGMA journal_mode=WAL');
|
||||
// Wait for the service to create the schema first (started below), then seed.
|
||||
const env = { ...process.env, CYBERGRIL_DB: dbPath, PYTHONPATH: join(root, 'src'), CYBERGRIL_R2_ENABLED: '0', CYBERGRIL_SEMANTIC: 'off', CYBERGRIL_PORT: String(port), CYBERGRIL_WEB: join(root, 'web', 'dist') };
|
||||
const env = { ...process.env, CYBERGRIL_DB: dbPath, PYTHONPATH: guard + ':' + join(root, 'src'), NETGUARD_OUT: join(work, 'netguard.json'), CYBERGRIL_MODELS: join(work, 'models-loopback.yaml'), CYBERGRIL_R2_ENABLED: '0', CYBERGRIL_SEMANTIC: 'off', CYBERGRIL_PORT: String(port), CYBERGRIL_WEB: join(root, 'web', 'dist') };
|
||||
let svc = spawn(venv, ['-m', 'cybergril.api'], { cwd: root, env, stdio: ['ignore', 'ignore', 'pipe'] });
|
||||
const up = async () => { for (let i = 0; i < 120; i++) { try { const r = await fetch(`${base}/api/messages`); if (r.status === 404) return true; } catch { await sleep(500); } } return false; };
|
||||
if (!await up()) { console.error('service did not come up'); process.exit(1); }
|
||||
@@ -39,9 +93,10 @@ seedRow('companion', '会想把窗开一条缝,听雨落在铁皮檐上。', '
|
||||
seedRow('companion', '昨晚的月亮很亮,想起你说过喜欢夜里散步。', 'reach-old', 1);
|
||||
seedRow('user', '今天加班到九点,好累。', 't-2');
|
||||
seedRow('companion', '那先别急着做别的,喝口热水。', 't-2');
|
||||
const restart = async () => { svc.kill('SIGTERM'); await new Promise(r => svc.on('exit', r)); svc = spawn(venv, ['-m', 'cybergril.api'], { cwd: root, env, stdio: ['ignore', 'ignore', 'pipe'] }); for (let i = 0; i < 120; i++) { try { await fetch(`${base}/api/health`); return; } catch { await sleep(500); } } };
|
||||
const rowIdOf = text => db.prepare('SELECT id FROM chat_message WHERE text=? ORDER BY id DESC LIMIT 1').get(text)?.id;
|
||||
const restart = async () => { svc.kill('SIGTERM'); await new Promise(r => svc.on('exit', r)); svc = spawn(venv, ['-m', 'cybergril.api'], { cwd: root, env, stdio: ['ignore', 'ignore', 'pipe'] }); for (let i = 0; i < 120; i++) { try { const r = await fetch(`${base}/api/health`); if (r.ok) return await r.json(); } catch { await sleep(500); } } return null; };
|
||||
|
||||
// ── Chromium over CDP (same driver style as tests/hel875_shots.mjs).
|
||||
// ── Chromium over CDP (same driver style as tests/hel875_shots.mjs). ──
|
||||
const profile = join(tmpdir(), `hel895-chrome-${Date.now()}`);
|
||||
const browser = spawn(chrome, ['--headless=new', `--remote-debugging-port=${cdpPort}`, `--user-data-dir=${profile}`, '--no-first-run', '--hide-scrollbars', '--force-color-profile=srgb', 'about:blank'], { stdio: 'ignore' });
|
||||
let targets;
|
||||
@@ -55,6 +110,16 @@ const js = async expr => { const r = await cdp('Runtime.evaluate', { expression:
|
||||
const shot = async name => { const { data } = await cdp('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(out, `real-${name}.png`), Buffer.from(data, 'base64')); };
|
||||
const read = async () => { await js('document.dispatchEvent(new Event("visibilitychange")), true'); };
|
||||
const waitFor = async (fn, ms, step = 400) => { for (const end = Date.now() + ms; Date.now() < end;) { const v = await fn(); if (v) return v; await sleep(step); } return null; };
|
||||
// HEL-896: count the page's OWN permission API calls from the very first document load.
|
||||
await cdp('Page.enable');
|
||||
await cdp('Page.addScriptToEvaluateOnNewDocument', { source: `(() => { let q = 0, g = 0; const qp = navigator.permissions.query.bind(navigator.permissions);
|
||||
navigator.permissions.query = d => { q++; return qp(d); };
|
||||
const gm = navigator.mediaDevices && navigator.mediaDevices.getUserMedia && navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
|
||||
if (gm) navigator.mediaDevices.getUserMedia = d => { g++; return gm(d); };
|
||||
window.__permCounts = () => ({ query: q, getUserMedia: g }); })()` });
|
||||
const talkUnread = () => js(`(() => { const b = [...document.querySelectorAll('.nav-item')].find(e => e.textContent.trim() === '交谈');
|
||||
return b ? { unread: b.classList.contains('unread'), label: b.getAttribute('aria-label') || '' } : null })()`);
|
||||
const navTo = async label => { await js(`[...document.querySelectorAll('.nav-item')].find(e => e.textContent.trim() === ${JSON.stringify(label)})?.click(), true`); await sleep(1200); };
|
||||
|
||||
try {
|
||||
// B1 — the built web boots against the real service.
|
||||
@@ -63,47 +128,84 @@ try {
|
||||
check('B1_real_service_boot', ready, await js(`document.body.innerText.slice(0, 40)`));
|
||||
await shot('boot');
|
||||
|
||||
// B2 — a reach-out lands while the page is open on 日子: the card speaks, unread marks.
|
||||
// B2 — a reach-out lands while the page is open on 此刻: the letter carries her exact words, the talk nav marks unread.
|
||||
seedRow('companion', '窗外的雨停了,想跟你说一声。', `reach-live-${Date.now()}`, 1);
|
||||
await read();
|
||||
const card = await waitFor(() => js(`!![...document.querySelectorAll('*')].find(e => e.children.length === 0 && e.textContent.includes('窗外的雨停了'))`), 30000);
|
||||
check('B2_reach_card_over_real_http', !!card);
|
||||
const letter = await waitFor(async () => { await read(); return js(`(() => { const b = document.querySelector('button.letter:not(.read)');
|
||||
return b && b.querySelector('p')?.textContent.includes('窗外的雨停了') ? b.querySelector('p').textContent : null })()`); }, 30000, 1500);
|
||||
const unreadBefore = await waitFor(async () => { const u = await talkUnread(); return u && u.unread ? u : null; }, 8000);
|
||||
check('B2_reach_card_over_real_http', !!letter && !!unreadBefore, `letter=${!!letter} unread=${unreadBefore?.label || 'none'}`);
|
||||
await shot('card');
|
||||
|
||||
// B3 — replying opens the conversation; the new message plays on the stage.
|
||||
const unreadHit = await waitFor(() => js(`[...document.querySelectorAll('button, .unread, [class*=unread]')].some(e => e.offsetParent !== null)`), 5000);
|
||||
if (await js(`[...document.querySelectorAll('button')].some(b => b.textContent.includes('回'))`)) { await js(`[...document.querySelectorAll('button')].find(b => b.textContent.includes('回'))?.click(), true`); await sleep(1500); }
|
||||
// B3 — the reach card speaks over 日子 and its OWN 回她 button opens the conversation: the reach-out plays on
|
||||
// the stage and the unread mark clears. Precise: no "any button with 回", no `|| unread` fallback.
|
||||
await navTo('日子');
|
||||
const card = await waitFor(() => js(`(() => { const a = document.querySelector('aside.reach.show');
|
||||
return a && a.getAttribute('aria-hidden') === 'false' && a.getBoundingClientRect().width > 0 && a.querySelector('p')?.textContent.includes('窗外的雨停了') ? a.querySelector('p').textContent : null })()`), 8000);
|
||||
check('B3a_visible_reach_card', !!card, card ? '' : 'aside.reach.show not visible');
|
||||
const clicked = await js(`(() => { const a = document.querySelector('aside.reach.show'); if (!a) return false;
|
||||
const b = [...a.querySelectorAll('.acts button')].find(e => e.textContent.trim() === '回她'); if (!b) return false; b.click(); return true })()`);
|
||||
await sleep(1500);
|
||||
const stage = await waitFor(() => js(`(document.querySelector('.conversation .sr')?.textContent || '').includes('窗外的雨停了')`), 8000);
|
||||
check('B3_stage_plays_reachout', !!stage || !!unreadHit, `stage=${!!stage}`);
|
||||
const unreadAfter = await talkUnread();
|
||||
check('B3b_reply_opens_stage_plays_reachout', !!card && !!clicked && !!stage && !unreadAfter?.unread,
|
||||
`card=${!!card} clicked=${!!clicked} stage=${!!stage} unreadAfter=${unreadAfter?.unread}`);
|
||||
await shot('stage');
|
||||
|
||||
// B4 — long absence: 260 bulk rows land ABOVE one new reach-out (gap regression, HEL-880):
|
||||
// the bounded first read (5×50) must not skip her; the next read closes the gap and hands her over.
|
||||
// B4 — long absence: 260 bulk rows land ABOVE one new reach-out (gap regression, HEL-880): the bounded first
|
||||
// read (5×50) must not skip her; the next read closes the gap and hands her over — proven by server message id.
|
||||
seedRow('companion', '刚看到一只猫从窗台跳下去。', `reach-gap-${Date.now()}`, 1);
|
||||
for (let i = 0; i < 260; i++) seedRow(i % 2 ? 'companion' : 'user', `别处的第${i + 1}句`, `bulk-${Date.now()}-${i}`);
|
||||
await read();
|
||||
const gapDone = await waitFor(async () => {
|
||||
await read();
|
||||
return js(`[...document.querySelectorAll('*')].some(e => e.children.length === 0 && e.textContent.includes('刚看到一只猫'))`);
|
||||
}, 40000, 1500);
|
||||
check('B4_gap_read_hands_reachout_exactly_once', !!gapDone);
|
||||
const gapId = rowIdOf('刚看到一只猫从窗台跳下去。'), liveId = rowIdOf('窗外的雨停了,想跟你说一声。');
|
||||
const badge = await waitFor(async () => { await read(); const u = await talkUnread(); return u && u.unread ? u : null; }, 40000, 1500);
|
||||
check('B4a_gap_read_hands_reachout', !!badge, `gapId=${gapId} ${badge?.label || 'no badge'}`);
|
||||
await shot('gap');
|
||||
const dup = await js(`[...document.querySelectorAll('*')].filter(e => e.children.length === 0 && e.textContent.includes('刚看到一只猫')).length`);
|
||||
check('B4b_no_duplicate_after_gap', dup >= 1 && dup <= 2, `matches=${dup}`);
|
||||
// Leaving the conversation merges the queued reach-out into the record (the one unread rule); the record's
|
||||
// data-mid entries are the server's own ids, so dedup is proven per message id, not by counting text matches.
|
||||
await navTo('日子'); await navTo('交谈');
|
||||
await js(`document.querySelector('button[aria-label="完整记录"]')?.click(), true`); await sleep(1200);
|
||||
const recordIds = () => js(`[...document.querySelectorAll('.record [data-mid]')].map(e => e.getAttribute('data-mid'))`);
|
||||
let ids = await waitFor(async () => { const v = await recordIds(); return v && v.includes(String(gapId)) ? v : null; }, 10000);
|
||||
const dupCount = ids ? ids.length - new Set(ids).size : -1;
|
||||
const gapHits = ids ? ids.filter(i => i === String(gapId)).length : 0;
|
||||
const liveHits = ids ? ids.filter(i => i === String(liveId)).length : 0;
|
||||
check('B4b_no_duplicate_by_message_id', !!ids && dupCount === 0 && gapHits === 1 && liveHits === 1,
|
||||
`rows=${ids?.length || 0} dups=${dupCount} gapId×${gapHits} liveId×${liveHits}`);
|
||||
await shot('record');
|
||||
await js(`document.querySelector('button[aria-label="关闭记录"]')?.click(), true`); await sleep(600);
|
||||
|
||||
// B5 — server restart (epoch+1): the same rows must not be added again.
|
||||
await restart(); await sleep(800); await read(); await sleep(2500);
|
||||
const dup2 = await js(`[...document.querySelectorAll('*')].filter(e => e.children.length === 0 && e.textContent.includes('刚看到一只猫')).length`);
|
||||
check('B5_restart_epoch_no_dup', dup2 >= 1 && dup2 <= 2, `matches=${dup2}`);
|
||||
// B5 — server restart: the epoch really bumps by exactly one, and the same rows are not added again.
|
||||
const epochBefore = (await (await fetch(`${base}/api/health`)).json()).epoch;
|
||||
const healthAfter = await restart(); await sleep(800);
|
||||
const epochAfter = healthAfter?.epoch;
|
||||
await read(); await sleep(2500); await read(); await sleep(1500);
|
||||
await js(`document.querySelector('button[aria-label="完整记录"]')?.click(), true`); await sleep(1200);
|
||||
ids = await recordIds();
|
||||
const dup2 = ids ? ids.length - new Set(ids).size : -1;
|
||||
const gap2 = ids ? ids.filter(i => i === String(gapId)).length : 0;
|
||||
check('B5_restart_epoch_plus1_no_dup', epochAfter === epochBefore + 1 && dup2 === 0 && gap2 === 1,
|
||||
`epoch=${epochBefore}->${epochAfter} rows=${ids?.length || 0} dups=${dup2} gapId×${gap2}`);
|
||||
|
||||
// B6 — no permission was ever asked for.
|
||||
// B6 — the page never called the Permissions API or getUserMedia at all (instrumented from first load).
|
||||
const counts = await js('window.__permCounts()');
|
||||
const mic = await js(`navigator.permissions.query({name:'microphone'}).then(r => r.state)`);
|
||||
const cam = await js(`navigator.permissions.query({name:'camera'}).then(r => r.state)`);
|
||||
check('B6_zero_permission_requests', mic === 'prompt' && cam === 'prompt', `mic=${mic} cam=${cam}`);
|
||||
check('B6_zero_permission_api_calls', !!counts && counts.query === 0 && counts.getUserMedia === 0,
|
||||
`counts=${JSON.stringify(counts)} mic=${mic} cam=${cam}`);
|
||||
} catch (e) {
|
||||
console.error('driver error:', e.message);
|
||||
results.push(false);
|
||||
} finally {
|
||||
writeFileSync(join(out, 'real-browser.json'), JSON.stringify({ ok: results.every(Boolean), checks: results.length, fail_count: results.filter(v => !v).length }, null, 1));
|
||||
try { browser.kill(); } catch { /* already gone */ }
|
||||
// HEL-896: the service must EXIT so the socket guard's atexit report exists; non-loopback budget is then read
|
||||
// from its own counter file, not assumed.
|
||||
try { svc.kill('SIGTERM'); } catch { /* already gone */ }
|
||||
await new Promise(r => { if (svc.exitCode !== null || svc.signalCode) return r(); svc.on('exit', r); setTimeout(r, 8000); });
|
||||
let netguard = null;
|
||||
try { netguard = JSON.parse((await import('node:fs')).readFileSync(join(work, 'netguard.json'), 'utf8')); } catch { /* missing report = honest fail below */ }
|
||||
check('B7_zero_nonloopback_outbound', !!netguard && netguard.nonloopback_connect_attempts === 0,
|
||||
netguard ? JSON.stringify(netguard) : 'netguard.json missing');
|
||||
writeFileSync(join(out, 'real-browser.json'), JSON.stringify({ ok: results.every(Boolean), checks: results.length, fail_count: results.filter(v => !v).length, netguard: netguard || 'missing', service_epoch_isolation: 'CYBERGRIL_MODELS loopback, caps 0, socket guard rejecting non-loopback' }, null, 1));
|
||||
try { browser.kill(); } catch { /* already gone */ }
|
||||
ws.close();
|
||||
}
|
||||
process.exit(results.every(Boolean) ? 0 : 1);
|
||||
|
||||
Reference in New Issue
Block a user