@elurjs/universal 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/commands.mjs CHANGED
@@ -12,7 +12,7 @@
12
12
  */
13
13
  export const CLI_COMMANDS = [
14
14
  {
15
- cmd: "`elur build --target web|android|linux [--apk --aab --release --engine hermes --splits --minify]`",
15
+ cmd: "`elur build --target web|android|linux|windows [--apk --aab --release --engine hermes --splits --minify]`",
16
16
  fn: "Build completo: bundling, lowering, assets, integración de host, Gradle",
17
17
  estado: "Implementado", sub: ["build"],
18
18
  },
@@ -27,7 +27,7 @@ export const CLI_COMMANDS = [
27
27
  estado: "Implementado (ADR-0137)", sub: ["build"], scripts: ["build-ssg.mjs"],
28
28
  },
29
29
  {
30
- cmd: "`elur dev --target web|android|linux [--json] [--ssr] [--dev-fast] [--no-serve]`",
30
+ cmd: "`elur dev --target web|android|linux|windows [--json] [--ssr] [--dev-fast] [--no-serve]`",
31
31
  fn: "Watch → rebuild → push/relaunch (web SSE reload, Android `/data/local/tmp`, Linux GTK4); `--ssr` reinicia el server generado; `--dev-fast` omite HBC/QJSC y regenera `routes.gen.ts`; eventos NDJSON",
32
32
  estado: "Implementado (ADR-0111/0141/0213/0214)", sub: ["dev"],
33
33
  },
@@ -279,6 +279,60 @@ if (template === "sdui") {
279
279
  ) + "\n",
280
280
  );
281
281
 
282
+ writeFileSync(join(dest, "AGENTS.md"), `# AGENTS — Elur SDUI/A2UI project
283
+
284
+ Este proyecto publica UI en vivo por MCP. Regla principal: los cambios de
285
+ UI en caliente SOLO se hacen con las tools MCP \`sdui_*\`/\`a2ui_*\` (el
286
+ cliente de IA las lanza solo desde \`opencode.json\`, \`.mcp.json\` o
287
+ \`.gemini/settings.json\` — nunca se corre \`elur sdui mcp\` a mano).
288
+
289
+ ## Prohibido para cambiar la UI en vivo
290
+
291
+ - Editar \`docs/*.envelope.json\`: el gateway sirve el último documento
292
+ **publicado**, no el archivo del disco — editarlo no cambia nada.
293
+ - \`elur sdui sign\` + \`curl /publish\` ni envelopes firmados a mano:
294
+ \`sdui_publish\`/\`a2ui_publish\` ya firman Ed25519 con \`keys/app.key\`
295
+ y gestionan rev/seq. Es solo fallback si no hay MCP disponible.
296
+ - Inventar vocabulario: las props/nodos exactos los da \`sdui_catalog\`.
297
+
298
+ ## Flujo obligatorio
299
+
300
+ 1. \`sdui_catalog\` si no conoces el vocabulario de esta versión.
301
+ 2. Construir el envelope SDUI o los mensajes A2UI.
302
+ 3. \`sdui_inspect\` / \`a2ui_inspect\` — oráculo Yoga C++ + reglas
303
+ layout/a11y; corrige lo que reporte ANTES de publicar.
304
+ 4. \`sdui_publish\` / \`a2ui_publish\` — verás \`rev=N+1\` y
305
+ \`Ed25519 OK\` en la barra de estado de la app.
306
+ 5. \`sdui_actions\` — polléala para leer las acciones que el usuario
307
+ envía desde la app (\`a2ui.action\`, formularios, taps).
308
+
309
+ ## A2UI
310
+
311
+ - \`createSurface\` una vez; \`updateComponents\` remonta;
312
+ \`updateDataModel\` con \`append:true\` = parche O(1) sin remount —
313
+ úsalo para cambios solo de datos.
314
+ - Refs de evento: \`{ref:"event"}.data.text\` / \`.data.checked\` /
315
+ \`.data.progress\` (es un EventEnvelope, no un valor plano).
316
+
317
+ ## Fronteras
318
+
319
+ - MCP = la superficie server-driven. El shell (\`src/entry.ts\`,
320
+ \`src/app.ts\`, barra de estado) es TypeScript compilado: cambiarlo =
321
+ editar código + \`elur dev\` reconstruye. No se publica por MCP.
322
+ - Nunca tocar \`keys/app.key\` (privada), \`generated/\` ni el gateway.
323
+ - Cada proyecto firma con sus llaves: documentos de otro proyecto se
324
+ rechazan (\`Ed25519 FAIL\`).
325
+ - Prerequisitos: \`bun run gateway\` corriendo + un cliente abierto
326
+ (\`bun run dev\`, \`dev:android\` con APK instalado, o \`dev:linux\`
327
+ con el binario en \`targets/linux/build/elur-linux\`).
328
+ - Guía detallada del flujo y anti-patrones:
329
+ \`docs/skills/elur-sdui-mcp/SKILL.md\`
330
+ `);
331
+
332
+ cpSync(join(root, "docs/skills"), join(dest, "docs/skills"), {
333
+ recursive: true,
334
+ });
335
+
282
336
  writeFileSync(join(dest, "src/verify.ts"), `import { ElurTextEncoder } from "@elurjs/universal";
283
337
  import { resolveModule } from "@elurjs/universal/native";
284
338
  import { CRYPTO_MODULE, moduleVerifier, type SduiSig, type VerifyFn } from "@elurjs/universal/sdui";
@@ -436,12 +490,15 @@ function swapBody(mounted: MountedSdui): void {
436
490
  });
437
491
  }
438
492
 
493
+ /** HUD de desarrollo (rev · firma · mounts): true muestra la barra de diagnóstico. */
494
+ const SHOW_HUD = false;
495
+
439
496
  function renderShell(): UIResult {
440
497
  const header = computed(() =>
441
498
  \`[\${Platform.OS}] \${modeBadge.value} · rev=\${revNum.value} · O(1)=\${dataPatches.value} · mounts=\${structuralMounts.value}\`,
442
499
  );
443
- return ui\`
444
- <column style=\${{ flex: 1, backgroundColor: "#071626" }}>
500
+ const hud = SHOW_HUD
501
+ ? ui\`
445
502
  <column style=\${{
446
503
  padding: 10, gap: 4, backgroundColor: "#0F2942",
447
504
  borderBottomWidth: 1, borderColor: "#1E4976",
@@ -453,6 +510,11 @@ function renderShell(): UIResult {
453
510
  \${statusText}
454
511
  </text>
455
512
  </column>
513
+ \`
514
+ : null;
515
+ return ui\`
516
+ <column style=\${{ flex: 1, backgroundColor: "#071626" }}>
517
+ \${hud}
456
518
  <column style=\${{ flex: 1 }}>
457
519
  \${currentBody}
458
520
  </column>
@@ -463,8 +525,9 @@ function renderShell(): UIResult {
463
525
  async function applySduiDoc(docName: string, rev: number): Promise<void> {
464
526
  const base = gatewayUrl.value;
465
527
  const transport = makeTransport(base);
466
- const plat = (Platform.OS === "android" || Platform.OS === "linux" ? Platform.OS : "web") as
467
- "web" | "android" | "linux";
528
+ const plat = (Platform.OS === "android" || Platform.OS === "linux" ||
529
+ Platform.OS === "windows" ? Platform.OS : "web") as
530
+ "web" | "android" | "linux" | "windows";
468
531
  const policy = {
469
532
  requireSig: true,
470
533
  trustedSigners: TRUSTED_SIGNERS,
package/cli/dev.mjs CHANGED
@@ -93,6 +93,42 @@ function restartLinuxHost() {
93
93
  linuxProc.on("exit", () => { /* el próximo rebuild relanza */ });
94
94
  return true;
95
95
  }
96
+ // ADR-0220: el host Windows corre fuera (VM/otra máquina) — se alcanza
97
+ // por SSH. ELUR_WIN_SSH=user@host[:port] habilita el relanzado; el
98
+ // bundle viaja por scp a ELUR_WIN_DIR y la app se levanta en la sesión
99
+ // interactiva con la scheduled task ELUR_WIN_TASK (debe existir en el
100
+ // host y ejecutar elur-windows.exe sin --shot).
101
+ function winSshTarget() {
102
+ const raw = process.env.ELUR_WIN_SSH;
103
+ if (!raw) return null;
104
+ const at = raw.lastIndexOf(":");
105
+ if (at > 0 && /^\d+$/.test(raw.slice(at + 1))) {
106
+ return { dest: raw.slice(0, at), port: raw.slice(at + 1) };
107
+ }
108
+ return { dest: raw, port: "22" };
109
+ }
110
+ function restartWindowsHost() {
111
+ const sshT = winSshTarget();
112
+ if (!sshT || noServe) return false;
113
+ const winDir = process.env.ELUR_WIN_DIR ?? "C:/elur/generated";
114
+ const task = process.env.ELUR_WIN_TASK ?? "elur-app-dev";
115
+ const genDir = join(process.cwd(), "generated");
116
+ const appName = !devFast && existsSync(join(genDir, "elurApp.es5.qjsc"))
117
+ ? "elurApp.es5.qjsc"
118
+ : "elurApp.js";
119
+ const scpArgs = ["-P", sshT.port];
120
+ try {
121
+ run("scp", ...scpArgs, join(genDir, "elurSignals.js"),
122
+ `${sshT.dest}:${winDir}/`);
123
+ run("scp", ...scpArgs, join(genDir, appName),
124
+ `${sshT.dest}:${winDir}/`);
125
+ run("ssh", "-p", sshT.port, sshT.dest,
126
+ `taskkill /f /im elur-windows.exe 2>nul & schtasks /run /tn ${task}`);
127
+ return true;
128
+ } catch {
129
+ return false;
130
+ }
131
+ }
96
132
  const killSsr = () => { try { ssrProc?.kill("SIGKILL"); } catch { } };
97
133
  const killLinux = () => { try { linuxProc?.kill("SIGTERM"); } catch { } };
98
134
  const stopWeb = () => {
@@ -366,6 +402,20 @@ function rebuild() {
366
402
  });
367
403
  return;
368
404
  }
405
+ if (target === "windows") {
406
+ run("bun", join(__dirname, "elur.mjs"), "build", "--target", "windows",
407
+ "--app", appEntry,
408
+ ...(devFast ? ["--dev-fast"] : []));
409
+ const launched = restartWindowsHost();
410
+ log("dev.build.end", {
411
+ ok: true, ms: Date.now() - t0,
412
+ launch: launched,
413
+ msg: launched
414
+ ? "bundle Windows copiado + app relanzada (SSH)"
415
+ : "bundle Windows en generated/ (ELUR_WIN_SSH no definido)",
416
+ });
417
+ return;
418
+ }
369
419
  if (full) {
370
420
  run("bun", join(__dirname, "elur.mjs"), "build", "--target", "android",
371
421
  "--app", appEntry, "--apk",
@@ -0,0 +1,450 @@
1
+ #!/usr/bin/env bun
2
+ // cli/tck-platform-windows.mjs — TCK de plataforma del host Windows
3
+ // (ADR-0220). Corre tests/tck/platform-entry.ts en targets/windows
4
+ // dentro de una VM VirtualBox y verifica por las APIs reales de
5
+ // plataforma — UIA (árbol de accesibilidad, equivalente al uiautomator
6
+ // dump de Android y al AT-SPI de Linux), CopyFromScreen (píxeles) y
7
+ // mouse_event/SendKeys (input inyectado) — no por auto-reporte del host.
8
+ //
9
+ // TCK-BOOT ventana real + árbol UIA poblado
10
+ // TCK-WIN frame con extents
11
+ // TCK-A11Y label→Name en ControlView
12
+ // TCK-A11Y-HIDDEN accessible=false fuera de ControlView
13
+ // TCK-IMG-* píxeles en BoundingRectangle: remote/data/asset/error
14
+ // TCK-IMG-SLOW hold→release del server → bitmap llega
15
+ // TCK-RTL rects de hijos en row dir=rtl vs ltr
16
+ // TCK-FONT serif/mono presentes
17
+ // TCK-I18N módulo i18n NO registrado en el host → gap declarado
18
+ // TCK-IME foco+SendKeys → ValuePattern.Value con el texto
19
+ // TCK-SCROLL wheel → filas nuevas en el árbol
20
+ // TCK-MEM WorkingSet antes/después del scroll
21
+ // TCK-GEOM MoveWindow → la ventana redimensiona
22
+ // TCK-LIFECYCLE kill + relaunch → app vuelve a UIA
23
+ // TCK-STATE NavState persistente (LOCALAPPDATA) → stack restaura
24
+ // TCK-EV-* longPress/press/shortcut/submit/key — pan sin
25
+ // deltas con input inyectado (gap documentado)
26
+ //
27
+ // Uso: bun cli/tck-platform-windows.mjs [--skip-build]
28
+ // Requiere: python3 cli/vm-job-server.py corriendo + agente guest
29
+ // vivo (powershell -w h -ep bypass -c "iex(irm http://10.0.2.2:8899/agent/<VM>)")
30
+ //
31
+ // Env: ELUR_VM (queue, def "WIN11R"), ELUR_VM_JOB (def http://localhost:8899),
32
+ // ELUR_WIN_WORKDIR (def C:\Users\elur\fdtest),
33
+ // ELUR_WIN_EXE (def <workdir>\elur-windows.exe)
34
+
35
+ import { spawnSync, execSync } from "node:child_process";
36
+ import { writeFileSync, mkdirSync, readFileSync } from "node:fs";
37
+ import { join } from "node:path";
38
+
39
+ const VM = process.env.ELUR_VM ?? "WIN11R";
40
+ const JOBS = (process.env.ELUR_VM_JOB ?? "http://localhost:8899").replace(/\/$/, "");
41
+ const WDIR = process.env.ELUR_WIN_WORKDIR ?? "C:\\Users\\elur\\fdtest";
42
+ const EXE = process.env.ELUR_WIN_EXE ?? `${WDIR}\\elur-windows.exe`;
43
+ const PROBE_PS1 = `${WDIR}\\tck-windows-uia.ps1`;
44
+ const PORT = 8377;
45
+ const skipBuild = process.argv.includes("--skip-build");
46
+
47
+ const outDir = `docs/benchmarks/tck-platform-windows-${new Date().toISOString().slice(0, 10)}`;
48
+ mkdirSync(outDir, { recursive: true });
49
+
50
+ const GREEN_PNG = Buffer.from(
51
+ "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAAFElEQVR4nGMUWeDGgA0wYRUdtBIAyDIBCgyi/HoAAAAASUVORK5CYII=",
52
+ "base64"
53
+ );
54
+ const BLUE_PNG = Buffer.from(
55
+ "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAAFElEQVR4nGMUibrDgA0wYRUdtBIABYsBWtDwjBMAAAAASUVORK5CYII=",
56
+ "base64"
57
+ );
58
+ // El entry pide src="tck_pixel.png" — el host lo resuelve por CWD.
59
+ const assetB64 = BLUE_PNG.toString("base64");
60
+
61
+ let releaseHold = null;
62
+ Bun.serve({
63
+ port: PORT,
64
+ // El ?hold del carril slow retiene la respuesta >10s — el default
65
+ // de Bun (10s) aborta el stream y el BitmapImage nunca completa.
66
+ idleTimeout: 240,
67
+ async fetch(req) {
68
+ const url = new URL(req.url);
69
+ if (url.pathname === "/release") {
70
+ releaseHold?.();
71
+ releaseHold = null;
72
+ return new Response("released");
73
+ }
74
+ const body = new ReadableStream({
75
+ async start(c) {
76
+ if (url.searchParams.has("hold"))
77
+ await new Promise((r) => { releaseHold = r; });
78
+ c.enqueue(GREEN_PNG);
79
+ c.close();
80
+ },
81
+ });
82
+ return new Response(body, { headers: { "content-type": "image/png" } });
83
+ },
84
+ });
85
+ console.log(`[tck-win] img server :${PORT} (el guest llega por 10.0.2.2)`);
86
+
87
+ let passed = 0, failed = 0;
88
+ const report = [];
89
+ function check(name, cond, detail = "") {
90
+ if (cond) passed++; else failed++;
91
+ const line = `[tck-win] ${name} ${cond ? "PASS" : "FAIL"}${detail ? " — " + detail : ""}`;
92
+ report.push(line);
93
+ console.log(line);
94
+ }
95
+ function note(name, detail) {
96
+ const line = `[tck-win] ${name} INFO — ${detail}`;
97
+ report.push(line);
98
+ console.log(line);
99
+ }
100
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
101
+
102
+ // --- transporte del job server ---
103
+ async function jsubmit(cmd) {
104
+ const r = await fetch(`${JOBS}/submit`, {
105
+ method: "POST",
106
+ headers: { "Content-Type": "application/json" },
107
+ body: JSON.stringify({ vm: VM, cmd }),
108
+ });
109
+ return (await r.json()).id;
110
+ }
111
+ async function jfetch(id, timeout = 90) {
112
+ const t = Date.now();
113
+ while (Date.now() - t < timeout * 1000) {
114
+ const r = await (await fetch(`${JOBS}/fetch/${VM}/${id}`)).text();
115
+ if (r !== "<pending>") return r;
116
+ await sleep(600);
117
+ }
118
+ return "<timeout>";
119
+ }
120
+ const g = async (cmd, timeout = 90) => jfetch(await jsubmit(cmd), timeout);
121
+
122
+ // --- probe UIA ---
123
+ const probe = async (...args) => {
124
+ const quoted = args.map(a => `"${String(a).replace(/"/g, '""')}"`).join(" ");
125
+ const out = await g(
126
+ `powershell -ep bypass -file ${PROBE_PS1} ${quoted}`, 120);
127
+ const lines = out.trim().split(/\r?\n/).filter(Boolean);
128
+ return JSON.parse(lines[lines.length - 1]);
129
+ };
130
+ const probeOk = async (...args) => {
131
+ try { return await probe(...args); } catch { return null; }
132
+ };
133
+
134
+ async function syncFile(rel, dst) {
135
+ await g(`powershell -c "Invoke-WebRequest '${JOBS.replace("localhost", "10.0.2.2")}/files/${rel}' -OutFile '${dst}' -TimeoutSec 60"`, 90);
136
+ }
137
+
138
+ let appPid = 0;
139
+ async function launch(bundle = "elurPlatform.js", title = "Elur TCK Platform") {
140
+ await kill();
141
+ await g(`powershell -c "Set-Location '${WDIR}'; ` +
142
+ `Start-Process '${EXE}' -ArgumentList '--app','${bundle}','--title','${title}' -WindowStyle Hidden; ` +
143
+ `Start-Sleep -Seconds 5; (Get-Process elur-windows).Id"`, 60);
144
+ const out = await g(`powershell -c "(Get-Process elur-windows -ErrorAction SilentlyContinue).Id"`, 30);
145
+ appPid = +(out.trim().split(/\r?\n/).pop() ?? 0);
146
+ if (appPid > 0) await probe("raise", appPid).catch(() => {});
147
+ return appPid;
148
+ }
149
+ const kill = () => g(`powershell -c "$p = Get-Process elur-windows -ErrorAction SilentlyContinue; ` +
150
+ `$p | ForEach-Object { $_.CloseMainWindow() | Out-Null }; ` +
151
+ `for ($i = 0; $i -lt 20 -and (Get-Process elur-windows -ErrorAction SilentlyContinue); $i++) { Start-Sleep -Milliseconds 400 }; ` +
152
+ `Get-Process elur-windows -ErrorAction SilentlyContinue | Stop-Process -Force"`, 30);
153
+ const memKb = async (pid) => {
154
+ const out = await g(`powershell -c "(Get-Process -Id ${pid} -ErrorAction SilentlyContinue).WorkingSet64"`, 30);
155
+ return Math.round(+(out.trim() || 0) / 1024);
156
+ };
157
+
158
+ const nodes = async () => {
159
+ for (let i = 0; i < 3; i++) {
160
+ const t = await probeOk("dump", appPid);
161
+ if (t) return Array.isArray(t) ? t : [t];
162
+ }
163
+ return await probe("dump", appPid).then(t => Array.isArray(t) ? t : [t]);
164
+ };
165
+ const byName = (ns, n) => ns.find(x => x.name === n);
166
+ const byText = (ns, t) => ns.find(x => (x.text ?? "") === t || (x.name ?? "") === t);
167
+ const center = (n) => [Math.floor((n.x ?? 0) + (n.w ?? 0) / 2), Math.floor((n.y ?? 0) + (n.h ?? 0) / 2)];
168
+
169
+ const shotPx = async (x, y) => (await probe("px", x, y)).rgb;
170
+ const isGreen = (c) => c && c[1] > 100 && c[1] - c[0] > 40 && c[1] - c[2] > 20;
171
+ const isRed = (c) => c && c[0] > 160 && c[0] - c[1] > 60 && c[0] - c[2] > 60;
172
+ const isBlue = (c) => c && c[2] > 120 && c[2] - c[0] > 50 && c[2] - c[1] > 30;
173
+
174
+ try {
175
+ // --- sanidad del transporte ---
176
+ const ping = await g("echo PONG", 30);
177
+ if (!/PONG/.test(ping))
178
+ throw new Error(`agente guest sin respuesta (${ping.trim().slice(0, 80)}) — ` +
179
+ `levanta cli/vm-job-server.py y el agente (iex(irm ${JOBS}/agent/${VM}))`);
180
+
181
+ if (!skipBuild) {
182
+ console.log("[tck-win] gen-bundle platform-entry → generated/elurPlatform.js");
183
+ execSync("bun cli/gen-bundle.mjs tests/tck/platform-entry.ts generated/elurPlatform.js --platform windows", { stdio: "inherit" });
184
+ execSync("bun cli/gen-bundle.mjs tests/tck/lifecycle-entry.ts generated/elurLifecycle.js --platform windows", { stdio: "inherit" });
185
+ execSync("bun cli/gen-bundle.mjs tests/tck/events-entry.ts generated/elurEvents.js --platform windows", { stdio: "inherit" });
186
+ }
187
+
188
+ // --- sync probe + bundles + asset al guest ---
189
+ await g(`powershell -c "New-Item -ItemType Directory -Force '${WDIR}\\generated' | Out-Null"`, 30);
190
+ await syncFile("cli/tck-windows-uia.ps1", PROBE_PS1);
191
+ for (const b of ["elurPlatform.js", "elurLifecycle.js", "elurEvents.js"])
192
+ await syncFile(`generated/${b}`, `${WDIR}\\generated\\${b}`);
193
+ await g(`powershell -c "[IO.File]::WriteAllBytes('${WDIR}\\tck_pixel.png',[Convert]::FromBase64String('${assetB64}'))"`, 30);
194
+ console.log("[tck-win] probe + bundles + asset sincronizados");
195
+
196
+ // ---- TCK-BOOT ----
197
+ const pid = await launch();
198
+ check("TCK-BOOT", pid > 0, `pid=${pid}`);
199
+ let tree = null;
200
+ for (let i = 0; i < 60 && !(tree && tree.length > 4); i++) {
201
+ await sleep(500);
202
+ const t = await probeOk("dump", appPid);
203
+ if (t && (!tree || (Array.isArray(t) ? t : [t]).length > tree.length))
204
+ tree = Array.isArray(t) ? t : [t];
205
+ }
206
+ const win = tree?.find(n => n.role === "Window");
207
+ check("TCK-WIN", !!win?.w, win ? `${win.w}x${win.h}` : "sin ventana");
208
+ check("TCK-BOOT", !!tree && tree.length > 4, `nodos UIA=${tree?.length ?? 0}`);
209
+
210
+ await sleep(2500);
211
+ tree = await nodes();
212
+
213
+ // ---- TCK-A11Y ----
214
+ const want = ["tck:img-remote", "tck:input"];
215
+ const missing = want.filter(n => !byName(tree, n));
216
+ if (!byText(tree, "TCK plataforma")) missing.push("text:TCK plataforma");
217
+ check("TCK-A11Y", missing.length === 0,
218
+ missing.length ? `faltan: ${missing}` : "labels→Name + text→name propio");
219
+ const heading = tree.find(n => (n.lct ?? "").toLowerCase().includes("head") && (n.name ?? "") === "TCK plataforma");
220
+ if (heading) check("TCK-A11Y-AS", true, `lct='${heading.lct}'`);
221
+ else note("TCK-A11Y-AS", "as=h1 sin LocalizedControlType 'heading' en UIA — gap declarado");
222
+ check("TCK-A11Y-HIDDEN", !byName(tree, "tck:lane-a11y-hidden"),
223
+ "accessible=false fuera de ControlView");
224
+
225
+ // ---- TCK-IMG (pixel al centro del BoundingRectangle) ----
226
+ // Una imagen sin bitmap aún no tiene rect UIA (carga async) — hay
227
+ // que esperar a que remota/asset materialicen; error puede quedar
228
+ // sin rect para siempre (su check es "no coloreado").
229
+ await probeOk("raise", appPid);
230
+ const shots = {};
231
+ for (let i = 0; i < 20 && ["remote", "data", "asset"].some(l => !shots[l]); i++) {
232
+ await sleep(600);
233
+ const t = await probeOk("dump", appPid);
234
+ const ns = t ? (Array.isArray(t) ? t : [t]) : [];
235
+ for (const lane of ["remote", "slow", "error", "data", "asset"]) {
236
+ const n = byName(ns, `tck:img-${lane}`);
237
+ if (n?.w && !shots[lane]) shots[lane] = center(n);
238
+ }
239
+ }
240
+ const px = async (lane) => shots[lane] ? shotPx(...shots[lane]) : null;
241
+ check("TCK-IMG-REMOTE", isGreen(await px("remote")),
242
+ shots.remote ? "" : "nodo sin rect tras espera");
243
+ check("TCK-IMG-DATA", isRed(await px("data")),
244
+ shots.data ? "" : "nodo sin rect tras espera");
245
+ check("TCK-IMG-ASSET", isBlue(await px("asset")),
246
+ shots.asset ? "" : "nodo sin rect tras espera");
247
+ const errPx = await px("error");
248
+ check("TCK-IMG-ERROR",
249
+ !isGreen(errPx) && !isBlue(errPx) && !isRed(errPx),
250
+ JSON.stringify(errPx));
251
+ check("TCK-IMG-SLOW-PENDING", !isGreen(await px("slow")), "");
252
+
253
+ await fetch(`http://localhost:${PORT}/release`).catch(() => { });
254
+ let slowGreen = false;
255
+ for (let i = 0; i < 15 && !slowGreen; i++) {
256
+ await sleep(800);
257
+ slowGreen = isGreen(await px("slow"));
258
+ }
259
+ check("TCK-IMG-SLOW", slowGreen, "");
260
+
261
+ // ---- TCK-RTL: orden de rects (dir prop → Yoga direction) ----
262
+ const ltrA = byName(tree, "tck:ltr-a"), ltrB = byName(tree, "tck:ltr-b");
263
+ const rtlA = byName(tree, "tck:rtl-a"), rtlB = byName(tree, "tck:rtl-b");
264
+ check("TCK-RTL",
265
+ !!ltrA && !!ltrB && !!rtlA && !!rtlB &&
266
+ ltrA.x < ltrB.x && rtlA.x > rtlB.x,
267
+ `ltr ${ltrA?.x}<${ltrB?.x} · rtl ${rtlA?.x}>${rtlB?.x}`);
268
+
269
+ // ---- TCK-FONT ----
270
+ check("TCK-FONT", !!(byText(tree, "serif Aa") && byText(tree, "mono Aa")),
271
+ "serif+mono presentes");
272
+
273
+ // ---- TCK-I18N: el `label` pisa el Name del wrapper; el valor
274
+ // renderizado vive en el hijo Text sin etiquetar. Medido: 'en-US',
275
+ // '1,234,567.891', '2 items' — el módulo i18n sí está registrado.
276
+ check("TCK-I18N",
277
+ !!byText(tree, "en-US") && !!byText(tree, "1,234,567.891"),
278
+ "locale+num renderizados");
279
+
280
+ // ---- TCK-IME: foco + SendKeys → ValuePattern ----
281
+ const input = byName(tree, "tck:input");
282
+ if (input) {
283
+ await probe("focus", appPid, "tck:input");
284
+ await sleep(300);
285
+ await probe("type", appPid, "tck:input", "tckhola");
286
+ await sleep(800);
287
+ const after = await nodes();
288
+ // El texto vive en el Edit interno (ValuePattern) — el wrapper
289
+ // Custom no lo expone. El label nombra a los dos; tomamos el
290
+ // nodo con value real.
291
+ const typed = after.find(n => n.name === "tck:input" &&
292
+ typeof n.value === "string")?.value ?? "";
293
+ check("TCK-IME", /tckhola/.test(typed), `value=${JSON.stringify(typed)}`);
294
+ } else check("TCK-IME", false, "tck:input no encontrado");
295
+
296
+ // ---- TCK-SCROLL: wheel → filas nuevas en el árbol ----
297
+ const memBefore = await memKb(appPid);
298
+ const filaNum = (n) => +((n.text ?? n.name ?? "").match(/^fila (\d+)/)?.[1] ?? -1);
299
+ const maxPre = Math.max(...tree.map(filaNum));
300
+ // El wheel debe caer sobre un nodo CON rect: las filas
301
+ // virtualizadas sin rect no reciben entrada. Preferimos la última
302
+ // fila materializada (borde del viewport) y como fallback el
303
+ // contenedor grande con rect.
304
+ const filaConRect = tree.filter(n => filaNum(n) >= 0 && n.w)
305
+ .sort((a, b) => (a.y + a.h) - (b.y + b.h))
306
+ .pop();
307
+ const scrollN = filaConRect ??
308
+ tree.filter(n => n.w > 100 && n.h > 100 && n.role !== "Window")
309
+ .sort((a, b) => b.w * b.h - a.w * a.h)[0];
310
+ if (scrollN?.w) {
311
+ const [cx, cy] = center(scrollN);
312
+ await probe("wheel", cx, cy, -8);
313
+ }
314
+ await sleep(1500);
315
+ const treeAfter = await nodes();
316
+ const maxNow = Math.max(...treeAfter.map(filaNum));
317
+ check("TCK-SCROLL", !!scrollN && maxNow > maxPre, `max fila ${maxPre}→${maxNow}`);
318
+ const memAfter = await memKb(appPid);
319
+ check("TCK-MEM", memAfter > 0 && memAfter - memBefore < 150 * 1024,
320
+ `WorkingSet ${memBefore}→${memAfter}KB delta<150MB`);
321
+
322
+ // ---- TCK-GEOM: MoveWindow → redimensiona ----
323
+ const before = tree.find(n => n.role === "Window");
324
+ if (before?.w) {
325
+ await probe("resize", appPid, 560, 980);
326
+ await sleep(1500);
327
+ const after = (await nodes()).find(n => n.role === "Window");
328
+ check("TCK-GEOM", !!after && Math.abs((after.w ?? 0) - 560) <= 40,
329
+ `w ${before.w}→${after?.w}`);
330
+ } else check("TCK-GEOM", false, "ventana no encontrada");
331
+
332
+ // ---- TCK-LIFECYCLE: kill + relaunch ----
333
+ await kill();
334
+ await sleep(800);
335
+ const pid2 = await launch();
336
+ let back = null;
337
+ for (let i = 0; i < 40 && !back; i++) {
338
+ await sleep(500);
339
+ back = await probeOk("dump", appPid);
340
+ }
341
+ check("TCK-LIFECYCLE", pid2 > 0 && !!back, `re-init tras kill (pid=${pid2})`);
342
+
343
+ // ---- TCK-STATE: NavState persistente → stack restaura ----
344
+ await g(`powershell -c "Remove-Item -Force '%LOCALAPPDATA%\\elur\\elurLifecycle\\navstate.json' -ErrorAction SilentlyContinue"`, 30);
345
+ await kill();
346
+ await launch("elurLifecycle.js", "ElurLifecycle");
347
+ await sleep(4000);
348
+ let lc = await probeOk("dump", appPid);
349
+ lc = Array.isArray(lc) ? lc : (lc ? [lc] : null);
350
+ const btn = lc?.find(n => n.name === "detalle →");
351
+ let restored = false;
352
+ if (btn?.w) {
353
+ await probe("click", ...center(btn));
354
+ await sleep(1500);
355
+ await kill();
356
+ await sleep(800);
357
+ await launch("elurLifecycle.js", "ElurLifecycle");
358
+ await sleep(4000);
359
+ lc = await probeOk("dump", appPid);
360
+ lc = Array.isArray(lc) ? lc : (lc ? [lc] : null);
361
+ restored = !!lc?.find(n => n.name === "lifecycle-detail") &&
362
+ !!lc?.find(n => n.name === "estado:saved-session");
363
+ }
364
+ check("TCK-STATE", !!btn && restored,
365
+ btn ? (restored ? "stack + app-state restaurados" : "relaunch cayó a home") : "botón detalle no encontrado");
366
+ await g(`powershell -c "Remove-Item -Force '%LOCALAPPDATA%\\elur\\elurLifecycle\\navstate.json' -ErrorAction SilentlyContinue"`, 30);
367
+
368
+ // ---- TCK-EV-*: gestos y teclado con entrada real ----
369
+ await kill();
370
+ await launch("elurEvents.js", "Elur TCK Eventos");
371
+ let ev = null;
372
+ for (let i = 0; i < 40 && !ev?.find?.(n => n.name === "tck:lp-box"); i++) {
373
+ await sleep(500);
374
+ const t = await probeOk("dump", appPid);
375
+ ev = t ? (Array.isArray(t) ? t : [t]) : null;
376
+ }
377
+ const evText = async (prefix) => {
378
+ const ns = await nodes();
379
+ return (ns.find(n => (n.text ?? "").startsWith(prefix))?.text ??
380
+ ns.find(n => (n.name ?? "").startsWith(prefix))?.name ?? "");
381
+ };
382
+ const evCenter = (name) => {
383
+ const n = ev?.find(x => x.name === name);
384
+ return n?.w ? center(n) : null;
385
+ };
386
+
387
+ const lp = evCenter("tck:lp-box");
388
+ if (lp) {
389
+ await probe("longpress", lp[0], lp[1], 1100);
390
+ await sleep(600);
391
+ const lpTxt = await evText("lp:"), prTxt = await evText("press:");
392
+ check("TCK-EV-LONGPRESS", /^lp:\d+,\d+$/.test(lpTxt) && prTxt === "press:0",
393
+ `${lpTxt} · ${prTxt} (el long-press no es press)`);
394
+ await probe("click", lp[0], lp[1]);
395
+ await sleep(600);
396
+ check("TCK-EV-PRESS-AFTER-LP", (await evText("press:")) === "press:1",
397
+ `${await evText("press:")} (un tap normal vuelve a ser press)`);
398
+ } else check("TCK-EV-LONGPRESS", false, "tck:lp-box no encontrado");
399
+
400
+ const pan = evCenter("tck:pan-box");
401
+ if (pan) {
402
+ await probe("drag", pan[0], pan[1], pan[0] + 120, pan[1], 14);
403
+ await sleep(900);
404
+ const panTxt = await evText("pan:");
405
+ // mouse_event inyectado no produce ManipulationDelta en WinUI3 —
406
+ // el gap está documentado (ADR-0220): el wiring vive en gestureEl.
407
+ if (/^pan:start>/.test(panTxt))
408
+ check("TCK-EV-PAN", true, panTxt);
409
+ else {
410
+ check("TCK-EV-PAN", false, panTxt || "pan:none");
411
+ note("TCK-EV-PAN", "input inyectado no produce ManipulationDelta (ADR-0220) — pendiente hardware real");
412
+ }
413
+ } else note("TCK-EV-PAN", "tck:pan-box no encontrado");
414
+
415
+ const submitInput = ev?.find(n => n.name === "tck:submit-input");
416
+ if (submitInput) {
417
+ await probe("type", appPid, "tck:submit-input", "hola");
418
+ await probe("keys", "{ENTER}");
419
+ await sleep(800);
420
+ check("TCK-EV-SUBMIT", /^submit:hola/.test(await evText("submit:")),
421
+ await evText("submit:"));
422
+ } else note("TCK-EV-SUBMIT", "tck:submit-input no encontrado");
423
+
424
+ // shortcut Mod+K → ctrl+k: requiere un control XAML con foco —
425
+ // el click previo en submit-input lo deja, pero los combos safe en
426
+ // edición sí disparan (ctrl+… pasa el guard).
427
+ await probe("keys", "^k");
428
+ await sleep(800);
429
+ check("TCK-EV-SHORTCUT", /^sc:(ctrl\+k|k)/.test(await evText("sc:")),
430
+ await evText("sc:"));
431
+
432
+ const keyBox = evCenter("tck:key-box");
433
+ if (keyBox) {
434
+ await probe("click", keyBox[0], keyBox[1]);
435
+ await probe("keys", "x");
436
+ await sleep(600);
437
+ check("TCK-EV-KEY", /^key:x/.test(await evText("key:")),
438
+ await evText("key:"));
439
+ } else note("TCK-EV-KEY", "tck:key-box no encontrado");
440
+
441
+ } catch (e) {
442
+ failed++;
443
+ report.push(`[tck-win] ERROR ${e.message}`);
444
+ console.error("[tck-win] ERROR", e);
445
+ } finally {
446
+ await kill().catch(() => { });
447
+ writeFileSync(join(outDir, "report.txt"), report.join("\n") + "\n");
448
+ console.log(`[tck-win] ${passed} passed, ${failed} failed → ${outDir}/report.txt`);
449
+ }
450
+ process.exit(failed ? 1 : 0);