{
  "description": "Shared coordinate construction batches printable ASCII spans, retaining complete glyph boundaries, native checkpoints and admission totals. Same image, CPU/memory caps and backend; separate before/after frontend asset mounts and fresh accounts/browsers. Both modes preserve complete source and actual near-1-MiB String styling after a verified beginning edit.",
  "baselineFrontend": "e3b2ee59, artifact hashes in before metadata",
  "currentSourceDiffSha256": "1fd281a6189abf26c412c10c05ed9b38c94b75c938eacdbe7b15e9c31ee32ead",
  "samples": [
    {
      "mode": "local",
      "case": "styled-long-line",
      "sourceBytes": 1048567,
      "inputViewportPaintMs": 126.19999998807907,
      "inputCompleteGeometryMs": 192.19999998807907,
      "coldCompleteGeometryMs": 1824.5999999940395,
      "peakChromePssKiB": 670472,
      "completeSourceAfterInputVerified": true,
      "verifiedSourceCaretBeforeInput": 0,
      "phase": "before",
      "nativeInputHandlerMs": 35.400000005960464
    },
    {
      "mode": "remote",
      "case": "styled-long-line",
      "sourceBytes": 1048567,
      "inputViewportPaintMs": 130.5,
      "inputCompleteGeometryMs": 189.19999998807907,
      "coldCompleteGeometryMs": 1818.2999999821186,
      "peakChromePssKiB": 715206,
      "completeSourceAfterInputVerified": true,
      "verifiedSourceCaretBeforeInput": 0,
      "phase": "before",
      "nativeInputHandlerMs": 34.69999998807907
    },
    {
      "mode": "local",
      "case": "styled-long-line",
      "sourceBytes": 1048567,
      "inputViewportPaintMs": 144.80000001192093,
      "inputCompleteGeometryMs": 210.30000001192093,
      "coldCompleteGeometryMs": 2384.300000011921,
      "peakChromePssKiB": 694601,
      "completeSourceAfterInputVerified": true,
      "verifiedSourceCaretBeforeInput": 0,
      "phase": "after",
      "nativeInputHandlerMs": 28.80000001192093
    },
    {
      "mode": "remote",
      "case": "styled-long-line",
      "sourceBytes": 1048567,
      "inputViewportPaintMs": 116.5,
      "inputCompleteGeometryMs": 172.40000000596046,
      "coldCompleteGeometryMs": 2029.300000011921,
      "peakChromePssKiB": 720318,
      "completeSourceAfterInputVerified": true,
      "verifiedSourceCaretBeforeInput": 0,
      "phase": "after",
      "nativeInputHandlerMs": 28.200000017881393
    }
  ],
  "artifactMetadata": {
    "before": {
      "host": "Linux-7.0.14-linuxkit-aarch64-with-glibc2.36",
      "measurement": "production editor; process-tree memory",
      "cpuCount": 14,
      "cgroupMemoryMax": "10737418240",
      "cgroupCpuMax": "400000 100000",
      "repetitions": 1,
      "fileName": "measure.rs",
      "measurementImage": "sha256:e1a372cac8e6c496251a7ea371631a8beb560d1c5c6cddd1b70a270da19bda8c",
      "inputTimingStart": "beforeinput",
      "inputPosition": "beginning",
      "cpuProfiling": false,
      "workerStartup": "default",
      "frontendWasmSha256": {
        "openwebide-frontend-d07383db1b4d71d9_bg.wasm": "cff58b2d98add6515eff2b6bbb38aec4e3d632cf1af53ce153b38be03fccd761"
      },
      "backendWasmSha256": "d99cc57814297987fc324b49be40566ebaab8e4ebbed8926a28c3df4aa513497",
      "measurementScriptSha256": "956baad44c8e52a559d4a8c2c425fed4f73617c18fab7d47681f720418106cfb",
      "checkoutHead": "17934e1ccf4c92d381e5757daae3f8cf0828b4fe",
      "browser": "Chromium 154.0.8037.92 built on Debian GNU/Linux 12 (bookworm)"
    },
    "after": {
      "host": "Linux-7.0.14-linuxkit-aarch64-with-glibc2.36",
      "measurement": "production editor; process-tree memory",
      "cpuCount": 14,
      "cgroupMemoryMax": "10737418240",
      "cgroupCpuMax": "400000 100000",
      "repetitions": 1,
      "fileName": "measure.rs",
      "measurementImage": "sha256:e1a372cac8e6c496251a7ea371631a8beb560d1c5c6cddd1b70a270da19bda8c",
      "inputTimingStart": "beforeinput",
      "inputPosition": "beginning",
      "cpuProfiling": false,
      "workerStartup": "default",
      "frontendWasmSha256": {
        "openwebide-frontend-f0528ea1b0099a0a_bg.wasm": "1044a2d2d0228279a6e152031cfcea5dd6ccb8d17f0e74466dcb4d6ba203f8ea"
      },
      "backendWasmSha256": "d99cc57814297987fc324b49be40566ebaab8e4ebbed8926a28c3df4aa513497",
      "measurementScriptSha256": "956baad44c8e52a559d4a8c2c425fed4f73617c18fab7d47681f720418106cfb",
      "checkoutHead": "17934e1ccf4c92d381e5757daae3f8cf0828b4fe",
      "browser": "Chromium 154.0.8037.92 built on Debian GNU/Linux 12 (bookworm)"
    }
  },
  "fixtureSource": "#!/usr/bin/env python3\n\"\"\"Measure the built Rust/WASM editor using disposable Spin/SQLite and Chrome.\n\nSet CHROMEDRIVER (and optionally CHROME) after spin build. Results are JSON lines;\neach case has a fresh account, runtime and browser process tree. Local cases use\nrecovery without an OS directory handle, so these are editor/view measurements,\nnot local filesystem permission checks. Summed RSS includes shared pages more\nthan once; Linux PSS, when readable, apportions those pages across processes.\n\"\"\"\nimport argparse\nimport base64\nimport hashlib\nimport json\nimport os\nfrom pathlib import Path\nimport platform\nimport runpy\nimport secrets\nimport subprocess\nimport tempfile\nimport threading\nimport time\n\nROOT = Path(\"/workspace/repos/openwebide\")\nSUPPORT = runpy.run_path(str(ROOT / \"tools/check-editor-recovery.py\"))\nBrowser, Runtime = SUPPORT[\"Browser\"], SUPPORT[\"Runtime\"]\n_original_popen = subprocess.Popen\n_phase = os.environ[\"EDITOR_BENCH_PHASE\"]\ndef _fixture_popen(command, *args, **kwargs):\n    if isinstance(command, list) and command[:2] == [\"spin\", \"up\"]:\n        command = command[:2] + [\"--from\", f\"/fixtures/{_phase}-spin.toml\"] + command[2:]\n    return _original_popen(command, *args, **kwargs)\nsubprocess.Popen = _fixture_popen\n\n\n\ndef host_constraints():\n    \"\"\"Record Linux resource limits so container samples keep their context.\"\"\"\n    constraints = {\"cpuCount\": os.cpu_count()}\n    for field, name in [(\"cgroupMemoryMax\", \"memory.max\"), (\"cgroupCpuMax\", \"cpu.max\")]:\n        try:\n            constraints[field] = Path(\"/sys/fs/cgroup\", name).read_text().strip()\n        except OSError:\n            constraints[field] = None\n    return constraints\n\n\ndef process_memory(driver):\n    # Chrome can create or retire a utility process between ps and smaps reads.\n    # Retry only the snapshot, retaining None when coverage stays incomplete.\n    for attempt in range(1, 4):\n        result = process_memory_snapshot(driver)\n        result[\"memorySnapshotAttempts\"] = attempt\n        if result[\"chrome_pss_kib\"] is not None or not Path(\"/proc\").is_dir():\n            return result\n        if attempt < 3:\n            time.sleep(.01)\n    return result\n\n\ndef chrome_process_role(pid):\n    \"\"\"Classify only owned processes; never publish command-line arguments.\"\"\"\n    try:\n        # Chromium can rewrite its process title into one space-separated argv.\n        args = Path(f\"/proc/{pid}/cmdline\").read_bytes().replace(b\"\\0\", b\" \").split()\n    except OSError:\n        return \"unknown\"\n    roles = {b\"renderer\": \"renderer\", b\"gpu-process\": \"gpu\", b\"utility\": \"utility\",\n             b\"zygote\": \"zygote\"}\n    for arg in args:\n        if arg.startswith(b\"--type=\"):\n            return roles.get(arg.removeprefix(b\"--type=\"), \"other\")\n    return \"browser\" if args and b\"chrome\" in args[0] else \"other\"\n\n\ndef process_memory_snapshot(driver):\n    records = {}\n    for line in subprocess.check_output([\"ps\", \"-axo\", \"pid=,ppid=,rss=\"], text=True).splitlines():\n        pid, parent, rss = map(int, line.split())\n        records[pid] = (parent, rss)\n    owned = {driver}\n    while True:\n        children = {pid for pid, (parent, _) in records.items() if parent in owned}\n        if children <= owned:\n            break\n        owned |= children\n    owned.discard(driver)\n    pss = []\n    by_role = {}\n    for pid in sorted(owned):\n        role = chrome_process_role(pid)\n        group = by_role.setdefault(role, {\"processes\": 0, \"rssKiB\": 0, \"pssKiB\": 0})\n        group[\"processes\"] += 1\n        group[\"rssKiB\"] += records[pid][1]\n        try:\n            fields = Path(f\"/proc/{pid}/smaps_rollup\").read_text().splitlines()\n            value = int(next(line for line in fields if line.startswith(\"Pss:\")).split()[1])\n            pss.append(value)\n            if group[\"pssKiB\"] is not None:\n                group[\"pssKiB\"] += value\n        except (OSError, StopIteration):\n            group[\"pssKiB\"] = None\n    return {\"chrome_processes\": len(owned),\n            \"chrome_summed_rss_kib\": sum(records[pid][1] for pid in owned),\n            \"chrome_pss_kib\": sum(pss) if len(pss) == len(owned) and owned else None,\n            \"chrome_memory_by_role\": by_role}\n\n\ndef source_for(case):\n    row = \"let value = call(\\\"\u6587\ud83d\ude00 caf\u00e9\\\"); // words for wrapping\\r\\n\"\n    if case == \"small\":\n        return row * 1_000\n    if case == \"medium\":\n        return row * (2 * 1024 * 1024 // len(row.encode()))\n    if case == \"byte-limit\":\n        row = \"let value = call(\\\"\u6587\ud83d\ude00 caf\u00e9\\\"); // \" + \"words \" * 64 + \"\\r\\n\"\n        return row * (8 * 1024 * 1024 // len(row.encode()))\n    if case == \"line-limit\":\n        return \"x\\n\" * 99_999\n    if case == \"long-line\":\n        return \"\u6587\ud83d\ude00 words \" * (1024 * 1024 // len(\"\u6587\ud83d\ude00 words \".encode()))\n    if case in {\"styled-long-line\", \"styled-long-line-following-row\"}:\n        prefix, suffix, unit = 'const VALUE: &str = \"', '\";', \"\u6587\ud83d\ude00 words \"\n        budget = 1024 * 1024 - len((prefix + suffix).encode())\n        source = prefix + unit * (budget // len(unit.encode())) + suffix\n        return source + \"\\nlet next = 0;\" if case == \"styled-long-line-following-row\" else source\n    if case == \"dense-rows\":\n        return \"\\n\" * 49_000\n    if case == \"cached-functions\":\n        return \"fn item() { call(1); }\\n\" * 2_500\n    if case == \"embedded-html\":\n        return \"<script>const word = '\u6587\ud83d\ude00'; function sample() { return word; }</script><style>.word { color: red; }</style>\\n\" * 250\n    if case == \"embedded-markdown\":\n        return \"# \u6587\ud83d\ude00\\n```rust\\nfn sample() { let word = \\\"\u6587\ud83d\ude00\\\"; }\\n```\\n\" * 250\n    raise ValueError(case)\n\n\nclass MemorySamples:\n    \"\"\"Observe owned Chrome processes; never collect unrelated process arguments.\"\"\"\n\n    def __init__(self, driver):\n        self.driver = driver\n        self.initial = process_memory(driver)\n        self.peak_rss = self.initial[\"chrome_summed_rss_kib\"]\n        self.peak_pss = self.initial[\"chrome_pss_kib\"]\n        self.peak_roles = self.initial[\"chrome_memory_by_role\"]\n        self.count = 1\n        self.error = None\n        self.stopped = threading.Event()\n        self.thread = threading.Thread(target=self.sample, daemon=True)\n        self.thread.start()\n\n    def sample(self):\n        while not self.stopped.wait(.2):\n            try:\n                value = process_memory(self.driver)\n                self.peak_rss = max(self.peak_rss, value[\"chrome_summed_rss_kib\"])\n                if value[\"chrome_pss_kib\"] is not None:\n                    if self.peak_pss is None or value[\"chrome_pss_kib\"] > self.peak_pss:\n                        self.peak_roles = value[\"chrome_memory_by_role\"]\n                    self.peak_pss = max(self.peak_pss or 0, value[\"chrome_pss_kib\"])\n                self.count += 1\n            except (OSError, ValueError) as error:\n                self.error = type(error).__name__\n                return\n\n    def finish(self):\n        self.stopped.set()\n        self.thread.join()\n        assert self.error is None, f\"Process memory sampling failed: {self.error}\"\n        final = process_memory(self.driver)\n        self.peak_rss = max(self.peak_rss, final[\"chrome_summed_rss_kib\"])\n        if final[\"chrome_pss_kib\"] is not None:\n            if self.peak_pss is None or final[\"chrome_pss_kib\"] > self.peak_pss:\n                self.peak_roles = final[\"chrome_memory_by_role\"]\n            self.peak_pss = max(self.peak_pss or 0, final[\"chrome_pss_kib\"])\n        self.count += 1\n        return {\"beforeLoadMemory\": self.initial, \"peakChromeSummedRssKiB\": self.peak_rss,\n                \"peakChromePssKiB\": self.peak_pss, \"memorySamples\": self.count,\n                \"peakChromeMemoryByRole\": self.peak_roles,\n                \"memorySampleIntervalMs\": 200}\n\n\nREADY = \"\"\"\n    window.editorViewObservePaint?.();\n    const input = document.querySelector('textarea[data-editor-path]');\n    const paint = document.querySelector('.editor-highlight:not(.editor-caret-measure) .editor-highlight-content');\n    const extent = input?.parentElement.querySelector('.editor-scroll-extent');\n    const bound = input?.dataset.editorNativeBound === 'true' &&\n        input.dataset.editorNativeGeneration && extent?.dataset.editorScope === input.dataset.editorScope;\n    return input && paint && (input.value.length === arguments[0] || bound) &&\n        paint.dataset.editorScope === input.dataset.editorScope &&\n        (getComputedStyle(input).whiteSpace !== 'pre-wrap' ||\n            (Number(extent?.dataset.sourceHeight) > 0 && extent.dataset.editorScope === input.dataset.editorScope)) &&\n        input.parentElement.classList.contains('highlight-ready') &&\n        (!arguments[1] || !!paint.querySelector('.tok-string')) &&\n        (!arguments[2] || document.querySelector('.status-preparation')?.getAttribute('title') === '');\n\"\"\"\n\n\ndef measure(case, mode, wrapped, trace=False, repetition=1, input_position=\"start\", profile=False, file_name=\"measure.rs\", wait_syntax=False, worker_startup=\"default\"):\n    source = source_for(case)\n    require_styled = case in {\"styled-long-line\", \"styled-long-line-following-row\"}\n    native = source.replace(\"\\r\\n\", \"\\n\")\n    # JS lengths are UTF-16, not Python's Unicode scalar count.\n    native_length = len(native.encode(\"utf-16-le\")) // 2\n    with tempfile.TemporaryDirectory(prefix=\"openwebide-view-\") as state, \\\n            tempfile.TemporaryDirectory(prefix=\"editor-view-probe-\", dir=ROOT) as folder:\n        runtime = Runtime(state, frontend=True)\n        browser = None\n        samples = None\n        phase = \"runtime\"\n        try:\n            runtime.start()\n            runtime.request(\"POST\", \"/api/auth/register\", {\n                \"username\": \"measure-\" + secrets.token_hex(8), \"password\": secrets.token_urlsafe(32),\n            }, expected=201)\n            runtime.acknowledge_release()\n            path = Path(folder).relative_to(ROOT.parent.parent).as_posix() if mode == \"remote\" else \"measure-folder\"\n            project = runtime.request(\"POST\", \"/api/projects\", {\n                \"name\": \"View measurement\", \"mode\": mode, \"path\": path,\n            }, expected=201)\n            (Path(folder) / file_name).write_bytes(source.encode())\n            encoded = base64.b64encode(source.encode()).decode()\n            recovery = {\"format\": 1, \"root\": {\"mode\": mode, \"path\": path if mode == \"remote\" else None},\n                        \"selected\": file_name, \"files\": [{\"path\": file_name,\n                        \"document\": {\"text\": encoded, \"saved\": encoded,\n                                     \"selections\": [{\"anchor\": 0, \"head\": 0}], \"collapsed\": []},\n                        \"scroll\": {\"top\": 0, \"left\": 0}, \"read_only\": False}]}\n            runtime.request(\"PUT\", f\"/api/projects/{project['id']}/editor-recovery\",\n                            {\"revision\": 0, \"state\": recovery})\n            for key, value in {\n                \"open_tabs\": json.dumps([project[\"id\"]]), \"active_project\": str(project[\"id\"]),\n                \"bridge_url\": \"http://127.0.0.1:1\",\n                \"editor_preferences\": json.dumps({\"indentation\": {\"style\": \"Spaces\", \"width\": 4, \"tab_width\": 4},\n                                                   \"word_wrap\": wrapped, \"show_whitespace\": False}),\n            }.items():\n                runtime.request(\"PUT\", \"/api/settings\", {\"key\": key, \"value\": value})\n            browser = Browser(state)\n            browser.call(\"POST\", \"/goog/cdp/execute\", {\"cmd\":\"Page.addScriptToEvaluateOnNewDocument\", \"params\":{\n                \"source\": \"\"\"\n                    window.editorWorkerStartup = {attempted:0, accepted:0, dropped:0};\n                    const post = Worker.prototype.postMessage;\n                    Worker.prototype.postMessage = function(message, ...args) {\n                        if (message?.kind === 'openwebide-editor-module:1') {\n                            editorWorkerStartup.attempted++;\n                            if (__URL__) { editorWorkerStartup.dropped++; return; }\n                            const result = post.call(this, message, ...args);\n                            editorWorkerStartup.accepted++;\n                            return result;\n                        }\n                        return post.call(this, message, ...args);\n                    };\n                \"\"\".replace('__URL__', json.dumps(worker_startup == 'url'))}})\n            browser.call(\"POST\", \"/url\", {\"url\": runtime.url + \"/offline.html\"})\n            for cookie in runtime.cookies:\n                browser.call(\"POST\", \"/cookie\", {\"cookie\": {\"name\": cookie.name, \"value\": cookie.value,\n                             \"domain\": \"127.0.0.1\", \"path\": cookie.path, \"httpOnly\": True}})\n            samples = MemorySamples(browser.process.pid)\n            if profile:\n                for command, params in [(\"Performance.enable\", {}), (\"Profiler.enable\", {}),\n                                        (\"Profiler.setSamplingInterval\", {\"interval\": 2000}), (\"Profiler.start\", {})]:\n                    browser.call(\"POST\", \"/goog/cdp/execute\", {\"cmd\": command, \"params\": params})\n            browser.call(\"POST\", \"/goog/cdp/execute\", {\"cmd\": \"Page.addScriptToEvaluateOnNewDocument\", \"params\": {\n                \"source\": \"\"\"\n                    window.editorViewScroll = input => {\n                        const scroll = input.parentElement?.querySelector('.editor-scroll-surface');\n                        return scroll && getComputedStyle(scroll).position === 'absolute' ? scroll : input;\n                    };\n                    window.editorViewMeasurement = {maxFrameMs: 0, inputAt: 0,\n                        coldViewportPaintMs: null, coldCompleteGeometryMs: null, coldSyntaxReadyMs: null,\n                        inputViewportPaintMs: null, inputCompleteGeometryMs: null, inputSyntaxReadyMs: null,\n                        coldViewportHadCompleteExtent: null, inputViewportHadCompleteExtent: null,\n                        inputPreviousScope: null, inputScrollTop: null, inputScrollLeft: null,\n                        longTasks: 0, longTaskMs: 0, maxLongTaskMs: 0, longTaskEvents: [], phase: \"cold\", probes: [], batches: [], workers: [], fonts: [], nativeEvents: [], traceTruncated: false};\n                    if (__TRACE__) {\n                        editorViewMeasurement.runtimeErrors = [];\n                        const recordError = text => {\n                            if (editorViewMeasurement.runtimeErrors.length < 16)\n                                editorViewMeasurement.runtimeErrors.push(String(text).slice(0,1024));\n                            else editorViewMeasurement.traceTruncated = true;\n                        };\n                        window.addEventListener('error', event => recordError(event.message));\n                        const originalError = console.error.bind(console);\n                        console.error = (...args) => { recordError(args.map(String).join(' ')); originalError(...args); };\n                        const batches = new WeakMap();\n                        window.__openwebideEditorProbeTiming = (paint, phase, elapsedMs, units) => {\n                            let record = batches.get(paint);\n                            if (phase === \"render\" || phase === \"paragraph-render\") {\n                                record = null;\n                                if (editorViewMeasurement.batches.length < 256) {\n                                    record = {at: performance.now(), phase: editorViewMeasurement.phase,\n                                        fontFaces: Array.from(document.fonts).slice(0, 16)\n                                            .map(face => ({family: face.family, status: face.status})),\n                                        scope: Object.fromEntries(Array.from(paint.closest(\".editor-row-measure\").attributes)\n                                            .filter(attribute => attribute.name.startsWith(\"data-measure-\"))\n                                            .map(attribute => [attribute.name, attribute.value]))};\n                                    editorViewMeasurement.batches.push(record);\n                                } else editorViewMeasurement.traceTruncated = true;\n                                batches.set(paint, record);\n                            }\n                            if (record) record[phase] = {elapsedMs, units};\n                        };\n                        const rows = new WeakMap();\n                        function recordFor(element) {\n                            const row = element?.closest(\".editor-row-measure .editor-source-line\");\n                            let record = row && rows.get(row);\n                            if (row && !record && editorViewMeasurement.probes.length < 256) {\n                                record = {at: performance.now(), phase: editorViewMeasurement.phase,\n                                    cold: !!row.closest(\".editor-height-measure\"),\n                                    sliced: row.hasAttribute(\"data-source-start\"),\n                                    sourceNative: row.textContent.length,\n                                    probeStyle: row.closest(\".editor-row-measure\").getAttribute(\"style\"),\n                                    rowStyle: row.getAttribute(\"style\"),\n                                    scope: Object.fromEntries(Array.from(row.closest(\".editor-row-measure\").attributes)\n                                        .filter(attribute => attribute.name.startsWith(\"data-measure-\"))\n                                        .map(attribute => [attribute.name, attribute.value])),\n                                    calls: 0, layoutMs: 0,\n                                    boundsCalls: 0, boundsMs: 0};\n                                rows.set(row, record); editorViewMeasurement.probes.push(record);\n                            }\n                            if (row && !record) editorViewMeasurement.traceTruncated = true;\n                            return record;\n                        }\n                        const original = Range.prototype.getClientRects;\n                        Range.prototype.getClientRects = function(...args) {\n                            const node = this.startContainer;\n                            const record = recordFor(node.nodeType === 1 ? node : node.parentElement);\n                            const started = performance.now();\n                            try { return original.apply(this, args); }\n                            finally { if (record) { record.calls++; record.layoutMs += performance.now()-started; } }\n                        };\n                        const originalBounds = Element.prototype.getBoundingClientRect;\n                        Element.prototype.getBoundingClientRect = function(...args) {\n                            const record = recordFor(this);\n                            const started = performance.now();\n                            try { return originalBounds.apply(this, args); }\n                            finally { if (record) { record.boundsCalls++; record.boundsMs += performance.now()-started; } }\n                        };\n                        function recordEvent(events, kind) {\n                            if (events.length >= 256) {\n                                editorViewMeasurement.traceTruncated = true;\n                                return null;\n                            }\n                            const record = {at: performance.now(), phase: editorViewMeasurement.phase, kind};\n                            events.push(record);\n                            return record;\n                        }\n                        // Native extent reads can force whole-source layout before\n                        // a bounded window is installed. Keep this separate from\n                        // the styled row probes, and never read value just to log it.\n                        function nativeRecord(input, kind) {\n                            if (!(input instanceof HTMLTextAreaElement) ||\n                                !input.matches('.editor-textarea, [data-editor-path]')) return null;\n                            const record = recordEvent(editorViewMeasurement.nativeEvents, kind);\n                            if (record) record.bound = input.dataset.editorNativeBound === 'true';\n                            return record;\n                        }\n                        const inputEvents = new WeakMap();\n                        for (const kind of ['beforeinput', 'input']) {\n                            document.addEventListener(kind, event => {\n                                const record = nativeRecord(event.target, kind);\n                                if (record) inputEvents.set(event, {record, started: performance.now()});\n                            }, true);\n                            document.addEventListener(kind, event => {\n                                const measured = inputEvents.get(event);\n                                if (measured) measured.record.elapsedMs = performance.now() - measured.started;\n                            });\n                        }\n                        for (const property of ['scrollWidth', 'scrollHeight']) {\n                            const descriptor = Object.getOwnPropertyDescriptor(Element.prototype, property);\n                            if (!descriptor?.get) continue;\n                            Object.defineProperty(Element.prototype, property, {\n                                ...descriptor,\n                                get() {\n                                    const record = nativeRecord(this, property), started = performance.now();\n                                    try { return descriptor.get.call(this); }\n                                    finally { if (record) record.elapsedMs = performance.now() - started; }\n                                }\n                            });\n                        }\n                        const nativeValue = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value');\n                        if (nativeValue?.set) Object.defineProperty(HTMLTextAreaElement.prototype, 'value', {\n                            ...nativeValue,\n                            set(value) {\n                                const record = nativeRecord(this, 'value'), started = performance.now();\n                                if (record) record.nativeLength = typeof value === 'string' ? value.length : null;\n                                try { return nativeValue.set.call(this, value); }\n                                finally { if (record) record.elapsedMs = performance.now() - started; }\n                            }\n                        });\n                        for (const kind of [\"loading\", \"loadingdone\", \"loadingerror\"])\n                            document.fonts.addEventListener(kind, event => {\n                                const record = recordEvent(editorViewMeasurement.fonts, kind);\n                                if (record) record.faces = Array.from(event.fontfaces || []).slice(0, 16)\n                                    .map(face => ({family: face.family, status: face.status}));\n                            });\n                        const OriginalWorker = Worker;\n                        Worker = class extends OriginalWorker {\n                            constructor(...args) {\n                                super(...args);\n                                this.addEventListener(\"message\", event => {\n                                    const record = recordEvent(editorViewMeasurement.workers, \"reply\");\n                                    if (!record) return;\n                                    record.messageUtf16Units = typeof event.data === \"string\" ? event.data.length : null;\n                                    try {\n                                        const reply = typeof event.data === \"string\" ? JSON.parse(event.data) : event.data;\n                                        const begin = reply?.part?.Begin;\n                                        record.framing = reply?.framing ?? null;\n                                        record.sequence = reply?.sequence ?? null;\n                                        record.part = typeof reply?.part === \"string\" ? reply.part\n                                            : reply?.part ? Object.keys(reply.part)[0] : null;\n                                        record.status = begin?.status ?? reply?.status ?? null;\n                                        record.hasAnalysis = !!(begin?.analysis ?? reply?.analysis);\n                                        record.highlightRows = begin?.analysis?.rows ??\n                                            (Array.isArray(reply?.analysis?.highlights) ? reply.analysis.highlights.length : null);\n                                    } catch { record.status = \"non-JSON control message\"; }\n                                });\n                            }\n                            postMessage(...args) {\n                                recordEvent(editorViewMeasurement.workers, \"request\");\n                                return super.postMessage(...args);\n                            }\n                        };\n                    }\n                    new PerformanceObserver(list => {\n                        for (const entry of list.getEntries()) {\n                            if (__TRACE__ && editorViewMeasurement.longTaskEvents.length < 256) {\n                                editorViewMeasurement.longTaskEvents.push({at: entry.startTime,\n                                    durationMs: entry.duration, observedAt: performance.now(),\n                                    phase: editorViewMeasurement.phase,\n                                    scope: document.querySelector('textarea[data-editor-path]')?.dataset.editorScope ?? null});\n                            } else if (__TRACE__) editorViewMeasurement.traceTruncated = true;\n                            editorViewMeasurement.longTasks++;\n                            editorViewMeasurement.longTaskMs += entry.duration;\n                            editorViewMeasurement.maxLongTaskMs = Math.max(editorViewMeasurement.maxLongTaskMs, entry.duration);\n                        }\n                    }).observe({type: 'longtask', buffered: true});\n                    window.editorViewObservePaint = () => {\n                        const input = document.querySelector('textarea[data-editor-path]');\n                        const paint = input?.parentElement.querySelector('.editor-highlight-content');\n                        const scope = input?.dataset.editorScope;\n                        if (scope && paint?.dataset.editorScope === scope &&\n                            input.parentElement.classList.contains('highlight-ready') &&\n                            (!__REQUIRE_STYLED__ || paint.querySelector('.tok-string'))) {\n                            const extent = input.parentElement.querySelector('.editor-scroll-extent');\n                            const complete = extent?.dataset.editorScope === scope &&\n                                Number(extent.dataset.sourceHeight) > 0;\n                            const measurement = editorViewMeasurement;\n                            const syntaxReady = document.querySelector('.status-preparation')?.getAttribute('title') === '';\n                            if (measurement.phase === 'cold') {\n                                if (measurement.coldViewportPaintMs === null) {\n                                    measurement.coldViewportPaintMs = performance.now();\n                                    measurement.coldViewportHadCompleteExtent = complete;\n                                }\n                                if (complete && measurement.coldCompleteGeometryMs === null)\n                                    measurement.coldCompleteGeometryMs = performance.now();\n                                if (syntaxReady && measurement.coldSyntaxReadyMs === null)\n                                    measurement.coldSyntaxReadyMs = performance.now();\n                            } else if (measurement.phase === 'input' && measurement.inputAt &&\n                                scope !== measurement.inputPreviousScope) {\n                                if (measurement.inputViewportPaintMs === null) {\n                                    measurement.inputViewportPaintMs = performance.now() - measurement.inputAt;\n                                    measurement.inputViewportHadCompleteExtent = complete;\n                                }\n                                if (complete && measurement.inputCompleteGeometryMs === null)\n                                    measurement.inputCompleteGeometryMs = performance.now() - measurement.inputAt;\n                            }\n                            if (['input', 'deferred'].includes(measurement.phase) && measurement.inputAt &&\n                                scope !== measurement.inputPreviousScope && syntaxReady && measurement.inputSyntaxReadyMs === null)\n                                measurement.inputSyntaxReadyMs = performance.now() - measurement.inputAt;\n                        }\n                    };\n                    let last;\n                    function tick(at) {\n                        if (last !== undefined) editorViewMeasurement.maxFrameMs = Math.max(editorViewMeasurement.maxFrameMs, at-last);\n                        editorViewObservePaint();\n                        last = at; requestAnimationFrame(tick);\n                    }\n                    requestAnimationFrame(tick);\n                    document.addEventListener('beforeinput', event => {\n                        if (event.target.matches('textarea[data-editor-path]')) {\n                            editorViewMeasurement.inputAt = performance.now();\n                            editorViewMeasurement.inputPreviousScope = event.target.dataset.editorScope;\n                            const scroll = editorViewScroll(event.target);\n                            editorViewMeasurement.inputScrollTop = scroll?.scrollTop ?? null;\n                            editorViewMeasurement.inputScrollLeft = scroll?.scrollLeft ?? null;\n                        }\n                    }, true);\n                \"\"\".replace(\"__TRACE__\", json.dumps(trace)).replace(\"__REQUIRE_STYLED__\", json.dumps(require_styled))}})\n            started = time.monotonic()\n            phase = \"cold paint\"\n            browser.call(\"POST\", \"/url\", {\"url\": runtime.url + \"/\"})\n            deadline = time.monotonic() + 60\n            while not browser.call(\"POST\", \"/execute/sync\", {\"script\": READY, \"args\": [native_length, require_styled, wait_syntax]}):\n                assert time.monotonic() < deadline, \"Editor view readiness timed out\"\n                time.sleep(0.05)\n            load_ms = (time.monotonic() - started) * 1000\n            snapshot = browser.call(\"POST\", \"/execute/async\", {\"script\": r\"\"\"\n                const done = arguments[0];\n                (async () => {\n                    const link = [...document.querySelectorAll('link[rel=modulepreload]')]\n                        .find(link => /\\/openwebide-frontend-[^/]+\\.js$/.test(link.href));\n                    const module = await import(link.href); const wasm = await module.default();\n                    window.editorViewWasmMemory = wasm.memory;\n                    const input = document.querySelector('textarea[data-editor-path]');\n                    const scroll = editorViewScroll(input);\n                    done({styledString: !!document.querySelector('.editor-highlight-content .tok-string'), nativeInputLength: input.value.length, nativeBound: input.dataset.editorNativeBound === 'true', appModule: new URL(link.href).pathname, wasmCommittedBytes: wasm.memory.buffer.byteLength,\n                        domNodes: document.getElementsByTagName('*').length,\n                        paintRows: document.querySelectorAll('.editor-source-line').length,\n                        scrollHeight: scroll.scrollHeight, scrollWidth: scroll.scrollWidth, clientWidth: scroll.clientWidth,\n                        maxFrameMs: editorViewMeasurement.maxFrameMs,\n                        wrapped: getComputedStyle(input).whiteSpace === 'pre-wrap'});\n                })().catch(error => done({error: String(error)}));\n            \"\"\", \"args\": []})\n            assert \"error\" not in snapshot, snapshot\n            assert not require_styled or snapshot[\"styledString\"], \"Prepared string style was unavailable\"\n            if case == \"cached-functions\":\n                assert browser.script(\"return !!document.querySelector('.editor-highlight-content .tok-keyword');\"), \"Function workload must prepare grammar colors\"\n            assert snapshot[\"wrapped\"] == wrapped, \"Editor preference was not applied\"\n            memory = process_memory(browser.process.pid)\n            phase = \"scroll paint\"\n            scroll = browser.call(\"POST\", \"/execute/async\", {\"script\": \"\"\"\n                const done = arguments[arguments.length - 1], input = document.querySelector('textarea[data-editor-path]');\n                const singleRow = arguments[0], requireStyled = arguments[1];\n                const scroll = editorViewScroll(input);\n                const horizontal = singleRow && getComputedStyle(input).whiteSpace !== 'pre-wrap';\n                editorViewMeasurement.phase = \"scroll\";\n                const started = performance.now(); const old = document.querySelector('.editor-source-line')?.dataset.line;\n                if (horizontal) scroll.scrollLeft = (scroll.scrollWidth - scroll.clientWidth) * .7;\n                else scroll.scrollTop = scroll.scrollHeight * .7;\n                scroll.dispatchEvent(new Event('scroll'));\n                const deadline = started + 10000;\n                function check() {\n                    const row = document.querySelector('.editor-source-line');\n                    const first = row?.dataset.line;\n                    const paint = document.querySelector('.editor-highlight-content');\n                    if (performance.now() > deadline) return done({error: 'Scroll paint timed out'});\n                    const offset = Number(horizontal ? row?.dataset.paintLeft : row?.dataset.paintTop);\n                    const target = horizontal ? scroll.scrollLeft : scroll.scrollTop;\n                    const margin = horizontal ? scroll.clientWidth * 2 + 30 : scroll.clientHeight + 8 * parseFloat(getComputedStyle(input).lineHeight) + 32;\n                    // A wrapped long row can occupy many screens even when the\n                    // file has other rows. Prove its crop moved using geometry;\n                    // ordinary multiline windows can also change the first row.\n                    const cropped = Number.isFinite(offset) && offset <= target + 30 && target - offset <= margin;\n                    const moved = cropped || (!singleRow && first !== old);\n                    if (moved && paint?.dataset.editorScope === input.dataset.editorScope && input.parentElement.classList.contains('highlight-ready') && (!requireStyled || paint.querySelector('.tok-string')))\n                        return done({scrollToPaintMs: performance.now()-started, scrollAxis: horizontal ? 'horizontal' : 'vertical', scrollOffset: target});\n                    requestAnimationFrame(check);\n                }\n                requestAnimationFrame(check);\n            \"\"\", \"args\": [\"\\n\" not in native, require_styled]})\n            assert \"error\" not in scroll, scroll\n            verified_source_caret = None\n            if input_position == \"start\":\n                browser.script(\"const input=document.querySelector('textarea[data-editor-path]'); input.focus(); input.setSelectionRange(0,0);\")\n            else:\n                phase = \"input navigation\"\n                browser.script(\"editorViewMeasurement.phase = 'navigate'; document.querySelector('textarea[data-editor-path]').focus();\")\n                key = \"Home\" if input_position == \"beginning\" else \"End\"\n                key_code = 36 if input_position == \"beginning\" else 35\n                verified_source_caret = 0 if input_position == \"beginning\" else len(source.encode())\n                for kind in [\"keyDown\", \"keyUp\"]:\n                    browser.call(\"POST\", \"/goog/cdp/execute\", {\"cmd\": \"Input.dispatchKeyEvent\", \"params\": {\n                        \"type\": kind, \"key\": key, \"code\": key, \"modifiers\": 2,\n                        \"windowsVirtualKeyCode\": key_code, \"nativeVirtualKeyCode\": key_code,\n                    }})\n                deadline = time.monotonic() + 10\n                while True:\n                    recovered = runtime.request(\"GET\", f\"/api/projects/{project['id']}/editor-recovery\")\n                    document = recovered[\"state\"][\"files\"][0][\"document\"]\n                    if document[\"selections\"][0][\"head\"] == verified_source_caret:\n                        assert document[\"selections\"][0][\"anchor\"] == verified_source_caret, \"Navigation retained a selection\"\n                        assert document[\"text\"] == encoded, \"Document navigation changed source\"\n                        break\n                    assert time.monotonic() < deadline, \"Source caret did not reach the requested document boundary\"\n                    time.sleep(0.1)\n            phase = \"input paint\"\n            browser.script(\"editorViewMeasurement.phase = 'input';\")\n            browser.call(\"POST\", \"/goog/cdp/execute\", {\"cmd\": \"Input.insertText\", \"params\": {\"text\": \"z\"}})\n            edited = browser.call(\"POST\", \"/execute/async\", {\"script\": \"\"\"\n                const done=arguments[arguments.length-1], inputPosition=arguments[0], requireStyled=arguments[1], deadline=performance.now()+10000;\n                function check() {\n                    editorViewObservePaint();\n                    const input=document.querySelector('textarea[data-editor-path]');\n                    const paint=document.querySelector('.editor-highlight-content');\n                    if (performance.now()>deadline) return done({error:'Input paint timed out'});\n                    if ((inputPosition === 'end' ? input.value.endsWith('z') : input.value.startsWith('z')) && paint.dataset.editorScope===input.dataset.editorScope &&\n                        (getComputedStyle(input).whiteSpace !== 'pre-wrap' ||\n                            (Number(input.parentElement.querySelector('.editor-scroll-extent')?.dataset.sourceHeight)>0 &&\n                             input.parentElement.querySelector('.editor-scroll-extent')?.dataset.editorScope===input.dataset.editorScope)) &&\n                        input.parentElement.classList.contains('highlight-ready') && (!requireStyled || paint.querySelector('.tok-string')))\n                        return done({inputToPaintMs:performance.now()-editorViewMeasurement.inputAt});\n                    requestAnimationFrame(check);\n                }\n                requestAnimationFrame(check);\n            \"\"\", \"args\": [input_position, require_styled]})\n            assert \"error\" not in edited, edited\n            browser.script(\"editorViewMeasurement.phase = 'deferred';\")\n            # Include deferred syntax preparation and queued recovery saves.\n            browser.call(\"POST\", \"/execute/async\", {\"script\": \"setTimeout(arguments[0], 1200);\", \"args\": []})\n            if input_position in {\"beginning\", \"end\"}:\n                expected_source = \"z\" + source if input_position == \"beginning\" else source + \"z\"\n                deadline = time.monotonic() + 10\n                while True:\n                    recovered = runtime.request(\"GET\", f\"/api/projects/{project['id']}/editor-recovery\")\n                    actual = base64.b64decode(recovered[\"state\"][\"files\"][0][\"document\"][\"text\"]).decode()\n                    if actual == expected_source:\n                        break\n                    assert time.monotonic() < deadline, \"Boundary input did not preserve complete source\"\n                    time.sleep(.1)\n            if wait_syntax:\n                phase = \"input syntax readiness\"\n                deadline = time.monotonic() + 60\n                while not browser.call(\"POST\", \"/execute/sync\", {\"script\": READY, \"args\": [native_length + 1, require_styled, True]}):\n                    assert time.monotonic() < deadline, \"Input syntax readiness timed out\"\n                    time.sleep(.05)\n            sampled = samples.finish()\n            samples = None\n            tasks = browser.script(\"return {...window.editorViewMeasurement, wasmBytes: window.editorViewWasmMemory.buffer.byteLength};\")\n            profiling = {}\n            if profile:\n                metrics = browser.call(\"POST\", \"/goog/cdp/execute\", {\"cmd\": \"Performance.getMetrics\", \"params\": {}})\n                cpu = browser.call(\"POST\", \"/goog/cdp/execute\", {\"cmd\": \"Profiler.stop\", \"params\": {}})\n                profiling = {\"cpuProfile\": cpu[\"profile\"], \"cpuProfileMetrics\": metrics[\"metrics\"]}\n            startup = browser.script('return window.editorWorkerStartup')\n            if worker_startup != 'default':\n                assert startup['attempted'] > 0, 'No production worker module handoff was attempted'\n                assert startup['dropped' if worker_startup == 'url' else 'accepted'] > 0, startup\n            return {**profiling, \"workerStartup\":worker_startup, \"workerStartupEvidence\":startup, \"cpuProfiling\": profile, \"waitedForSyntax\": wait_syntax, \"case\": case, \"fileName\": file_name, \"mode\": mode, \"wrap\": wrapped, \"repetition\": repetition, \"sourceBytes\": len(source.encode()),\n                    \"inputPosition\": input_position, \"verifiedSourceCaretBeforeInput\": verified_source_caret,\n                    \"completeSourceAfterInputVerified\": input_position in {\"beginning\", \"end\"}, \"loadToPaintMs\": load_ms, **snapshot, **scroll, **edited, **memory,\n                    \"afterInputMemory\": process_memory(browser.process.pid), **sampled,\n                    **{key: tasks[key] for key in [\"coldViewportPaintMs\", \"coldCompleteGeometryMs\",\n                        \"coldViewportHadCompleteExtent\", \"coldSyntaxReadyMs\", \"inputViewportPaintMs\", \"inputCompleteGeometryMs\", \"inputSyntaxReadyMs\",\n                        \"inputViewportHadCompleteExtent\", \"inputScrollTop\", \"inputScrollLeft\"]},\n                    \"afterInputWasmCommittedBytes\": tasks[\"wasmBytes\"],\n                    \"longTasks\": tasks[\"longTasks\"], \"longTaskMs\": tasks[\"longTaskMs\"],\n                    \"maxLongTaskMs\": tasks[\"maxLongTaskMs\"], \"maxFrameIncludingInputMs\": tasks[\"maxFrameMs\"],\n                    **({\"layoutProbes\": tasks[\"probes\"], \"preparationBatches\": tasks[\"batches\"], \"workerEvents\": tasks[\"workers\"], \"fontEvents\": tasks[\"fonts\"], \"nativeEvents\": tasks[\"nativeEvents\"], \"longTaskEvents\": tasks[\"longTaskEvents\"], \"traceTruncated\": tasks[\"traceTruncated\"]} if trace else {})}\n        except (AssertionError, TimeoutError, RuntimeError) as error:\n            observed = samples.finish() if samples else {}\n            samples = None\n            diagnostics = {}\n            if trace and browser:\n                try:\n                    diagnostics = browser.call(\"POST\", \"/execute/sync\", {\"script\": \"\"\"\n                        const state=globalThis.editorViewMeasurement ?? {};\n                        const input=document.querySelector('textarea[data-editor-path]');\n                        const paint=document.querySelector('.editor-highlight-content');\n                        const extent=input?.parentElement.querySelector('.editor-scroll-extent');\n                        return {failureState:{nativeLength:input?.value.length,\n                            nativeStartsWithMarker:input?.value.startsWith('z'),\n                            inputScope:input?.dataset.editorScope,paintScope:paint?.dataset.editorScope,\n                            extentScope:extent?.dataset.editorScope,sourceHeight:extent?.dataset.sourceHeight,\n                            highlightReady:input?.parentElement.classList.contains('highlight-ready'),\n                            alerts:[...document.querySelectorAll('[role=\"alert\"],.notice.error')].map(node=>node.textContent.slice(0,512))},\n                            layoutProbes:state.probes,preparationBatches:state.batches,workerEvents:state.workers,\n                            nativeEvents:state.nativeEvents,fontEvents:state.fonts,runtimeErrors:state.runtimeErrors,traceTruncated:state.traceTruncated};\n                    \"\"\", \"args\": []}, timeout=5)\n                except (OSError, ValueError, RuntimeError) as diagnostic_error:\n                    diagnostics = {\"failureDiagnosticError\": type(diagnostic_error).__name__}\n                try:\n                    recovered = runtime.request(\"GET\", f\"/api/projects/{project['id']}/editor-recovery\")\n                    actual = base64.b64decode(recovered[\"state\"][\"files\"][0][\"document\"][\"text\"]).decode()\n                    diagnostics[\"failureRecovery\"] = {\"sourceBytes\": len(actual.encode()),\n                        \"unchanged\": actual == source, \"markerDelta\": actual.count(\"z\") - source.count(\"z\")}\n                except (OSError, ValueError, RuntimeError, KeyError, IndexError) as diagnostic_error:\n                    diagnostics[\"failureRecoveryError\"] = type(diagnostic_error).__name__\n            print(json.dumps({\"case\": case, \"fileName\": file_name, \"mode\": mode, \"wrap\": wrapped, \"repetition\": repetition, \"sourceBytes\": len(source.encode()),\n                              \"failedPhase\": phase, \"failure\": type(error).__name__, **observed, **diagnostics}), flush=True)\n            raise\n        finally:\n            try:\n                if samples:\n                    samples.finish()\n            finally:\n                try:\n                    if browser:\n                        browser.stop()\n                finally:\n                    runtime.stop()\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(description=__doc__)\n    parser.add_argument(\"--cases\", nargs=\"+\", choices=[\"small\", \"medium\", \"byte-limit\", \"line-limit\", \"long-line\", \"styled-long-line\", \"styled-long-line-following-row\", \"dense-rows\", \"cached-functions\", \"embedded-html\", \"embedded-markdown\"], default=[\"small\"])\n    parser.add_argument(\"--modes\", nargs=\"+\", choices=[\"local\", \"remote\"], default=[\"local\", \"remote\"])\n    parser.add_argument(\"--wrap\", action=\"store_true\")\n    parser.add_argument(\"--trace\", action=\"store_true\", help=\"Record bounded probe/worker diagnostics; timings include instrumentation overhead\")\n    parser.add_argument(\"--wait-syntax\", action=\"store_true\", help=\"Wait for current-file syntax progress to clear before input and final memory sampling; retain the existing readiness deadline\")\n    parser.add_argument(\"--profile\", action=\"store_true\", help=\"Capture a diagnostic main-thread CPU profile; timings and memory include profiler overhead\")\n    parser.add_argument(\"--input-position\", choices=[\"start\", \"beginning\", \"end\"], default=\"start\", help=\"Use native-window start or verified complete-source Home/End navigation before typing\")\n    parser.add_argument(\"--file-name\", default=\"measure.rs\", help=\"Fixture filename selects the production language policy\")\n    parser.add_argument(\"--repeat\", type=int, default=1, help=\"Fresh browser/runtime runs for each case and mode\")\n    parser.add_argument(\"--require-pss\", action=\"store_true\", help=\"Fail if apportioned Chrome process memory cannot be measured\")\n    parser.add_argument('--worker-startup', choices=['default','compiled','url'], default='default', help='Compare the same production artifact with module handoff or its URL fallback')\n    args = parser.parse_args()\n    if args.repeat < 1:\n        parser.error(\"--repeat must be positive\")\n    if Path(args.file_name).name != args.file_name or args.file_name in {\"\", \".\", \"..\"}:\n        parser.error(\"--file-name must be a single filename\")\n    assert os.environ.get(\"CHROMEDRIVER\"), \"Set CHROMEDRIVER to a compatible driver\"\n    print(json.dumps({\"host\": platform.platform(), \"measurement\": \"production editor; process-tree memory\",\n                      **host_constraints(),\n                      \"repetitions\": args.repeat, \"fileName\": args.file_name,\n                      \"measurementImage\": os.environ.get(\"EDITOR_VIEW_IMAGE\"),\n                      \"inputTimingStart\": \"beforeinput\", \"inputPosition\": args.input_position, \"cpuProfiling\": args.profile, \"workerStartup\":args.worker_startup,\n                      \"frontendWasmSha256\": {\n                          path.name: hashlib.sha256(path.read_bytes()).hexdigest()\n                          for path in sorted((Path(\"/baseline-dist\") if _phase == \"before\" else ROOT / \"frontend/dist\").glob(\"*.wasm\"))\n                      },\n                      \"backendWasmSha256\": hashlib.sha256(\n                          (ROOT / \"target/wasm32-wasip2/release/openwebide_backend.wasm\").read_bytes()\n                      ).hexdigest(),\n                      \"measurementScriptSha256\": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),\n                      \"checkoutHead\": subprocess.check_output([\"git\", \"rev-parse\", \"HEAD\"], cwd=ROOT, text=True).strip(),\n                      \"browser\": subprocess.check_output([os.environ[\"CHROME\"], \"--version\"], text=True).strip() if os.environ.get(\"CHROME\") else \"WebDriver default\"}), flush=True)\n    for case in args.cases:\n        for mode in args.modes:\n            for repetition in range(1, args.repeat + 1):\n                result = measure(case, mode, args.wrap, args.trace, repetition, args.input_position, args.profile, args.file_name, args.wait_syntax, args.worker_startup)\n                print(json.dumps(result), flush=True)\n                if args.require_pss:\n                    assert result[\"peakChromePssKiB\"] is not None, \"Chrome peak PSS was unavailable\"\n                    assert result[\"afterInputMemory\"][\"chrome_pss_kib\"] is not None, \"Chrome final PSS was unavailable\"\n",
  "limits": "One instrumented sample per mode/phase. Native-handler observations fall from ~35 to ~28\u201329 ms, while viewport paint is mixed. No general UI latency or PSS improvement is established; full traversal and performance gates remain open."
}
