kaizen-agent 1.69.1 → 1.71.0

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.
Files changed (62) hide show
  1. package/README.md +2 -2
  2. package/cli/annotate-proxy.ts +135 -0
  3. package/cli/annotate.ts +86 -0
  4. package/cli/automations.ts +10 -3
  5. package/cli/browser.ts +1 -1
  6. package/cli/chat.ts +9 -1
  7. package/cli/chatgpt.ts +2 -1
  8. package/cli/docs.ts +1 -1
  9. package/cli/google.ts +2 -1
  10. package/cli/handoff.ts +1 -1
  11. package/cli/install.ts +28 -8
  12. package/cli/knowledge.ts +1 -1
  13. package/cli/notes.ts +10 -1
  14. package/cli/pty.ts +21 -0
  15. package/cli/settings.ts +5 -1
  16. package/cli/sources.ts +3 -2
  17. package/cli/state.ts +43 -5
  18. package/cli/versions.ts +1 -1
  19. package/cli/video.ts +1 -1
  20. package/cli/web.ts +137 -35
  21. package/cli/workers.ts +20 -7
  22. package/cli/worktree.ts +55 -15
  23. package/package.json +1 -1
  24. package/skills/kaizen/SKILL.md +12 -8
  25. package/skills/kaizen/config.default.yml +18 -2
  26. package/skills/kaizen/settings.md +3 -1
  27. package/skills/kaizen/spec-build.md +13 -2
  28. package/skills/kaizen/spec-main.md +2 -0
  29. package/skills/kaizen-help/SKILL.md +1 -0
  30. package/skills/media/kaizen-game/SKILL.md +96 -0
  31. package/skills/media/kaizen-game/assets/gdd.css +12 -0
  32. package/skills/media/kaizen-game/references/build.md +81 -0
  33. package/skills/media/kaizen-game/references/content.md +32 -0
  34. package/skills/media/kaizen-game/references/design.md +81 -0
  35. package/skills/media/kaizen-game/references/ship.md +34 -0
  36. package/skills/media/kaizen-game/references/verify.md +33 -0
  37. package/skills/media/kaizen-game/scripts/check.sh +13 -0
  38. package/skills/media/kaizen-game/scripts/frames.mjs +34 -0
  39. package/skills/media/kaizen-game/scripts/gdd-pdf.mjs +19 -0
  40. package/skills/media/kaizen-game/scripts/pw.mjs +18 -0
  41. package/skills/media/kaizen-game/scripts/serve.mjs +53 -0
  42. package/skills/media/kaizen-game/scripts/serve.test.mjs +18 -0
  43. package/skills/media/kaizen-game/scripts/setup.sh +9 -0
  44. package/skills/media/kaizen-game/scripts/smoke.mjs +40 -0
  45. package/skills/media/kaizen-game/skill.json +1 -0
  46. package/web/annotate.js +382 -0
  47. package/web/board/annotate-lib.ts +15 -0
  48. package/web/board/annotate.ts +181 -0
  49. package/web/board/badge.ts +12 -0
  50. package/web/board/icebox.ts +6 -3
  51. package/web/board/markdown.ts +7 -2
  52. package/web/board/run-view.ts +83 -9
  53. package/web/board/settings-orchestration.ts +1 -1
  54. package/web/board/settings-pages.ts +1 -0
  55. package/web/board/settings-skills.ts +1 -0
  56. package/web/board/settings.ts +2 -2
  57. package/web/board.html +5 -3
  58. package/web/board.js +119 -119
  59. package/web/notebook.js +23 -23
  60. package/web/term.js +48 -48
  61. package/web/term.ts +16 -4
  62. package/web/video.js +25 -25
@@ -0,0 +1,32 @@
1
+ # Content: cases from real rules
2
+
3
+ Learning and event games live or die on content that the client's expert accepts. Write sample cases yourself, from sources,
4
+ so the client reviews something concrete instead of starting from a blank sheet.
5
+
6
+ ## Sources
7
+ 1. Know the client's sector and their own rules first (see the brief).
8
+ 2. Find their **published** documents: guidelines, codes of conduct, policies, the regulator's rules for their sector.
9
+ Download each into its own folder and extract the text (`pdftotext -layout`), then read the parts you cite.
10
+ 3. A rule cited in a case needs a document you read. Cite an article, chapter or paragraph number only when it is in the text you read. Otherwise cite the document title alone.
11
+ Quote thresholds, deadlines and channels exactly as written (for example "within 10 working days to the unit, 30 to the regulator", "exempt up to Rp1,000,000").
12
+ 4. Where no source exists (an internal SOP you could not find), use a general standard (for example ISO 27001) and flag the case for confirmation.
13
+ Example domains used in phishing cases must be visibly made up, or lookalikes of the client's real domain.
14
+
15
+ ## Writing cases
16
+ - Each case is a real situation from the players' work, in their words: their customers, partners and documents.
17
+ Don't use other sectors' terms (for example "nasabah" for an insurer's claimants).
18
+ - `prompt`: what the player sees in the game, short enough for a label or a sign.
19
+ - `action`: the correct thing to do. `reason`: one line a player understands. `source`: the document (and article if verified).
20
+ - Order: obvious first, subtle last. Keep the totals the GDD fixes, so times stay comparable.
21
+ - Mark everything as a sample that needs the client's check, in the UI and in the data.
22
+ - Check the fit on screen: word lengths in letter tiles and grids, and long sentences in cards and buttons.
23
+
24
+ ## The review file (`docs/CONTENT-REVIEW.md`)
25
+ - One table per game: id, situation, correct action, reason, source, and **"needs confirmation"** (empty, or what exactly is uncertain).
26
+ - Generate it from the game data with a small script (import the modules and read `CASES`), so it never drifts from what players see. Rerun it after every content edit.
27
+ - Offer it as a download on the landing page next to the GDD, and list the open points in GDD section 14.
28
+
29
+ ## After a rewrite
30
+ - `grep` the whole site for terms that must be gone (old sector words, wrong laws, wrong domains). The result must be empty.
31
+ - Spot-check three or four key facts back in the extracted source text, with line numbers.
32
+ - Replay each changed round at 390 px for overflow.
@@ -0,0 +1,81 @@
1
+ # Design: brief, concepts, GDD
2
+
3
+ ## Brief: ask before anything is built
4
+ One message, grouped, with a default for each question so the user can answer "defaults are fine".
5
+ - **The game.** Genre or reference feel (described by mechanic, not by a game to copy), 2D or 3D, session length, solo or multiplayer, and what makes a player come back.
6
+ - **Track.** Just a game, or an event / learning game with real content (see below)?
7
+ - **Players.** How many, solo or teams, one device each? Phone, laptop or both (default: phone first, laptop works)?
8
+ - **Setting.** A live event (a fixed time, a host, everyone at once, rankings) or played anytime? How long, and how many rounds?
9
+ - **Client** (event / learning). The organisation, its sector, the unit that owns the content, and the person who signs it off.
10
+ Ask this first. Content written before the sector is known has to be rewritten: bank wording for an insurer, civil-servant rules for a state company.
11
+ - **Purpose.** What should players learn, practise or prove? What counts as winning?
12
+ - **Channel.** Zoom, Teams, a stage screen? Who shares what? (On the real project, Zoom was used by moderators only. Players played in their own browser.)
13
+ - **Language and tone.** The players' language, and everyday office or playful.
14
+ - **Brand and limits.** Logo, colours, real places to include, devices that must work, hosting rules, the event date.
15
+
16
+ Write the answers into GDD section 1 and keep the unknowns in section 14 (open questions).
17
+
18
+ ## Concepts
19
+ When the direction is open, use `kaizen-concept`. What worked:
20
+ - Three truly different concepts, not one idea in three skins. For example: case files and stamps, a 3D toy town, a TV game show.
21
+ - All three share one `shared/data.js` (teams, sample cases, a `simulateRound`), so they are compared on design and not on content.
22
+ - Each concept plays its signature round to the result by real input, and has a spectator view for the shared screen.
23
+ - One review page with a vote per concept. The user picked one, then asked for two separate passes:
24
+ a UI pass ("follow Apple philosophy") and a richness pass (CC0 models and sound). Offer them as separate steps.
25
+
26
+ ## Every game
27
+ - **Core loop** in one line (for example: run, dodge, collect, reach the goal). If it is not fun with the scoring removed, fix the loop first.
28
+ - **Controls on both devices.** Touch first (tap, swipe, hold, drag), with laptop keys as a bonus. No control may require a keyboard on a phone.
29
+ - **Win state, fail state, and feedback** under 1 s for every action.
30
+ - **Difficulty** rises across a session or level. Write the tuning knobs (speed, spacing, timers) in the GDD so they can be adjusted without redesign.
31
+ - **Juice where it counts.** Small camera kicks, particles, sound on every action, and a short slow-motion beat on big moments. Respect reduced motion.
32
+
33
+ ## Event / learning track: not a quiz in a skin
34
+ The user rejected "Kahoot style" outright. In every round:
35
+ - The question is a **situation inside the game**: a vendor holding out a parcel on the street, a visitor without a badge, an email in the inbox.
36
+ - The answer is an **action**: dodge or collect, stop or let through, flag or open, put away, choose a path.
37
+ - Skill (speed, aim, timing) and knowledge both count, and knowledge decides.
38
+ - A text question is allowed only as a short checkpoint inside the action, such as a gate with three lanes. It never fills a whole screen.
39
+
40
+ ## Shared systems for the event / learning track (state once in the GDD)
41
+ - **Case model.** `{ id, prompt, action, reason, source }`, in play order, the same for every player.
42
+ `reason` is one line a player understands. `source` names the real rule.
43
+ - **Ranking.** Cases solved first, then time with a fixed penalty per wrong action (for example 5 s), then fewer wrong actions.
44
+ Points per rank (for example 100, minus 3 per place, minimum 10). Top N go to a harder final. Add tie-breaks.
45
+ - **Cosmetic pickups** (coins) are shown on the result only and never change the ranking.
46
+ - **First result counts.** Replays are labelled as practice and leave the standings unchanged. Finals have no replay.
47
+ - **Answer review** after every round lists the round's cases with the correct action, reason and source, and highlights the player's mistakes.
48
+ This is the learning moment and the host's talking point. Build it from the solved and missed case sets, not from the order of play.
49
+ Otherwise a timeout or cases solved out of order give wrong rows.
50
+ - **Difficulty curve.** Obvious cases first and subtle ones last (a near-identical domain). The final is clearly harder than any round.
51
+ - **Fairness pillar.** The same content and the same clock for everyone. Timing never depends on the video call (Zoom lags 1–3 s).
52
+
53
+ ## GDD skeleton (`docs/GDD.md`)
54
+ ```
55
+ # <Name>: Game Design Document
56
+ Version, date, status line, client and content owner.
57
+ 1. One-page overview: pitch, track, players, session or event shape, pillars, anti-pillars
58
+ 2. Event format and run-of-show (live events only): table of time, segment, player screen, shared screen
59
+ 3. Core loop and shared systems: loop diagram, scoring, progression, character, difficulty curve
60
+ (event / learning: case model, ranking, pickups, answer review)
61
+ 4..N. One section per game, level or round:
62
+ Building or place, genre, what it teaches
63
+ Fantasy: one line
64
+ How it plays: controls on phone and on laptop, what the player does each second
65
+ Objects, enemies, obstacles (event / learning: the cases in the world, and the correct action for each)
66
+ Level or case data shape; fixed totals where times must be comparable
67
+ Feedback: correct and wrong, both under 1 s so play keeps flowing
68
+ Spectator: what the shared screen shows
69
+ Tuning knobs, edge cases (reconnect, hidden tab), effort S/M/L
70
+ N+1. Final
71
+ .. Screens and UI: table of screen and purpose; design language
72
+ .. Tech, content, accessibility: stack, server-authoritative rules, assets and sizes, performance targets, content pipeline
73
+ .. Build plan: steps and the result of each
74
+ .. Risks and fallback (phones, network, server, content errors, disputes, call delay)
75
+ .. Open questions for the client
76
+ ```
77
+ Write each game section so another agent can build it without asking anything. The real project's sub-agents built five games in parallel from their sections alone.
78
+
79
+ ## Originality
80
+ Genres and mechanics are free to use: a 3-lane runner, a memory match, a word search. Names, characters, art, music and levels are your own.
81
+ Never recreate a specific existing game, even when it is renamed. Kenney CC0 packs give a consistent toy look that belongs to nobody.
@@ -0,0 +1,34 @@
1
+ # Ship: a link the client can play
2
+
3
+ ## Serve
4
+ `node $S/serve.mjs .preview 4321` serves the whole folder on 127.0.0.1 for you and your agents.
5
+ `PUBLIC=1 node $S/serve.mjs .preview 8060` serves only what `tools/serve.json` (or `--config <file>`) allows:
6
+ ```json
7
+ {
8
+ "public": ["index.html", "game.html", "shared/data.js", "rounds/*.js", "assets/**"],
9
+ "downloads": { "/download/GDD.pdf": "../docs/GDD.pdf", "/download/Cases.md": "../docs/CONTENT-REVIEW.md" }
10
+ }
11
+ ```
12
+ - `*` matches one path segment and `**` any depth. Download paths are relative to the config file, and are sent as attachments.
13
+ - Old versions (`v1/`), other concepts and scratch files stay private by default. Only list what the client should see.
14
+ - The server never throws on a bad request path: `//` and a lone `%` once took the public server down.
15
+ `node $S/serve.test.mjs` checks the path guard and the allowlist matching.
16
+ - Keep it running as a user service, so it survives your session:
17
+ `systemd-run --user --unit <name>-web -p WorkingDirectory=$PWD -E PUBLIC=1 node $S/serve.mjs .preview 8060`, or a unit file for reboots.
18
+
19
+ ## Expose
20
+ Use the `deploy-tunnel` skill if it is installed (Cloudflare tunnel to a subdomain). Otherwise any static host works for the files.
21
+ Publishing is outward-facing, so confirm with the user before the first public link.
22
+ Once it is public, every save is live: tell agents, and keep the page working at each save.
23
+
24
+ ## Landing page (`index.html`)
25
+ - The play link (and a "jump to the latest part" link for reviewers), the GDD (PDF and MD), and the case list for the content owner.
26
+ - A "what's new" list per version, 3–5 lines in the user's language, from each agent's report.
27
+ - An honest note about what is simulated (other teams, the live server).
28
+
29
+ ## Before the real event (unproven: plan these in the GDD build plan)
30
+ - A server-authoritative game server: it sends one case at a time, keeps the answer keys, stamps time, and decides finish and rank.
31
+ Clients send only actions.
32
+ - Progress that survives a refresh or reconnect, one active device per account, and a moderator console (open, start, pause, end, void a case, export).
33
+ - A load test with simulated clients, tests on a cheap Android phone and an iPhone, and a full rehearsal with the hosts.
34
+ - A fallback (for example a form with the same cases) in case the server fails.
@@ -0,0 +1,33 @@
1
+ # Verify: play it, look at it, measure it
2
+
3
+ ## Browsers
4
+ - **Swiftshader** (CPU WebGL, works headless everywhere, deterministic): use it for screenshots and play-throughs.
5
+ Args: `--use-gl=angle --use-angle=swiftshader --enable-unsafe-swiftshader`. Frame times here are meaningless.
6
+ - **Real GPU** (`--gpu` in the scripts): `--enable-gpu --ignore-gpu-blocklist --use-angle=vulkan --enable-features=Vulkan`.
7
+ Use it for any claim about smoothness. The scripts print the WebGL renderer string, so check that it is not SwiftShader.
8
+
9
+ ## The minimum, every pass
10
+ 1. `node $S/smoke.mjs <url> --screens <list>` at 390×844 (touch, DPR 2) and 1440×900. It fails on page errors, console errors,
11
+ failed requests and horizontal overflow, and writes a screenshot per screen and size.
12
+ 2. **Read every screenshot yourself.** Text overflowing a button, a label hidden behind a control, or a field under the dock show only in pictures.
13
+ Longer translated sentences break layouts that fitted the English sample.
14
+ 3. **Play every round by real input** (Playwright `page.touchscreen.tap`, `page.mouse`, `page.keyboard`) to the result and the review screen.
15
+ Do it once clean and once with deliberate mistakes, and once let a round time out. Never call game functions to skip play, because that hides input bugs.
16
+ 4. **Check the rules end to end.** Unlock gates fire without the URL shortcut, the final is closed to non-qualifiers,
17
+ a replay does not change the score, the review rows match what happened, and the podium leads back to the hub.
18
+ 5. **Check leaks.** Read `__game.gpu` and `document.querySelectorAll('*').length` in the hub, then after playing several rounds in a row and returning.
19
+ The numbers should come back to about the hub baseline.
20
+ 6. `file://` and no-WebGL fallbacks load without errors.
21
+
22
+ Write the long play-through as one `e2e.mjs` in the scratchpad and rerun it after every fix pass, adapting the selectors as the markup changes.
23
+
24
+ ## When the user says it stutters
25
+ Measure before you change anything:
26
+ ```
27
+ node $S/frames.mjs '<url>?screen=hub' --size 2000x1100 --click 700,600 --gpu --ms 2500
28
+ ```
29
+ It wraps `requestAnimationFrame` and reports frame gaps (p50, p95, max, frames over 33 ms) plus long tasks around one interaction.
30
+ - **Gaps over 33 ms or long tasks:** it is a rendering or JS cost. Look for per-frame scene traversal, shader compiles on first view (warm them up with `renderer.compile`), and texture uploads.
31
+ - **A steady 60 fps that still "feels" jerky:** it is the motion. Log the camera every frame (a `page.route` that injects a log line into the page's render call).
32
+ Look for two tweens fighting, a clamp stopping a tween, a target that moves while it is being eased towards, or a spin that stops abruptly.
33
+ - Repeat at the user's window size. If it still feels wrong after a clean measurement, ask which browser and device they use. Don't guess further.
@@ -0,0 +1,13 @@
1
+ #!/bin/sh
2
+ # Lists what kaizen-game needs and whether it is here. Exit 1 if anything required is missing.
3
+ miss=0
4
+ command -v node >/dev/null 2>&1 && echo "ok node $(node -v)" || { echo "MISSING node"; miss=1; }
5
+ found=""
6
+ for h in "$KAIZEN_GAME_HOME" "$HOME/.kaizen/kaizen-game" "$HOME/.kaizen/kaizen-book"; do
7
+ [ -n "$h" ] && [ -d "$h/node_modules/playwright" ] && { found="$h"; break; }
8
+ done
9
+ [ -n "$found" ] && echo "ok playwright ($found)" || { echo "MISSING playwright: run scripts/setup.sh"; miss=1; }
10
+ command -v pandoc >/dev/null 2>&1 && echo "ok pandoc (GDD PDF)" || echo "- pandoc not found (optional, only for gdd-pdf.mjs)"
11
+ command -v ffmpeg >/dev/null 2>&1 && echo "ok ffmpeg (sound conversion)" || echo "- ffmpeg not found (optional, .ogg to .m4a)"
12
+ command -v pdftotext >/dev/null 2>&1 && echo "ok pdftotext (reading source rules)" || echo "- pdftotext not found (optional, poppler)"
13
+ exit $miss
@@ -0,0 +1,34 @@
1
+ // Frame timing around one interaction. Usage:
2
+ // node frames.mjs <url> [--click x,y | --tap x,y | --selector css] [--ms 2500] [--size 2000x1100] [--settle 5000] [--gpu]
3
+ // Wraps requestAnimationFrame before the page loads, so it works on any page. Prints the WebGL renderer
4
+ // (SwiftShader = CPU, timings meaningless), frame gaps p50/p95/max, frames over 33 ms, and long tasks.
5
+ import { chromium, SOFT, GPU, arg, flag } from './pw.mjs';
6
+
7
+ const url = process.argv[2];
8
+ if (!url || url.startsWith('--')) { console.error('usage: node frames.mjs <url> [--click x,y] [--gpu]'); process.exit(2); }
9
+ const [w, h] = String(arg('size', '1440x900')).split('x').map(Number), ms = +arg('ms', 2500);
10
+ const tap = arg('tap'), b = await chromium.launch({ headless: true, args: flag('gpu') ? GPU : SOFT });
11
+ const p = await b.newPage({ viewport: { width: w, height: h }, hasTouch: !!tap, isMobile: !!tap });
12
+ await p.addInitScript(() => {
13
+ window.__fr = []; window.__lt = [];
14
+ const raf = window.requestAnimationFrame.bind(window);
15
+ // count each animation frame once, whatever number of callbacks the page queues in it
16
+ let lastT = -1; window.requestAnimationFrame = cb => raf(t => { if (t !== lastT) { lastT = t; window.__fr.push(t); } cb(t); });
17
+ try { new PerformanceObserver(l => l.getEntries().forEach(e => window.__lt.push([Math.round(e.startTime), Math.round(e.duration)]))).observe({ type: 'longtask', buffered: true }); } catch {}
18
+ });
19
+ const errs = []; p.on('pageerror', e => errs.push(e.message));
20
+ await p.goto(url, { waitUntil: 'networkidle' }); await p.waitForTimeout(+arg('settle', 5000));
21
+ console.log('renderer:', await p.evaluate(() => { const g = document.createElement('canvas').getContext('webgl2') || document.createElement('canvas').getContext('webgl'); const d = g && g.getExtension('WEBGL_debug_renderer_info'); return d ? g.getParameter(d.UNMASKED_RENDERER_WEBGL) : 'no WebGL'; }));
22
+ const t0 = await p.evaluate(() => { window.__fr = []; window.__lt = []; return performance.now(); });
23
+ const xy = s => String(s).split(',').map(Number);
24
+ if (arg('click')) await p.mouse.click(...xy(arg('click')));
25
+ else if (tap) await p.touchscreen.tap(...xy(tap));
26
+ else if (arg('selector')) await p.click(arg('selector'));
27
+ await p.waitForTimeout(ms);
28
+ const { fr, lt } = await p.evaluate(() => ({ fr: window.__fr, lt: window.__lt }));
29
+ await b.close();
30
+ const gaps = fr.slice(1).map((t, i) => t - fr[i]).sort((a, z) => a - z), q = k => gaps.length ? gaps[Math.min(gaps.length - 1, Math.floor(k * gaps.length))].toFixed(1) : '-';
31
+ console.log(`frames ${fr.length} in ${ms} ms (${(fr.length / ms * 1000).toFixed(0)} fps) gap p50 ${q(.5)} p95 ${q(.95)} max ${q(1)} ms over 33 ms: ${gaps.filter(g => g > 33).length}`);
32
+ const late = lt.filter(([s]) => s >= t0);
33
+ console.log(late.length ? 'long tasks: ' + late.map(([s, d]) => `+${Math.round(s - t0)}ms ${d}ms`).join(', ') : 'long tasks: none');
34
+ if (errs.length) { console.log('page errors:', errs.join(' | ')); process.exit(1); }
@@ -0,0 +1,19 @@
1
+ // Builds an A4 PDF from a Markdown GDD: pandoc to HTML with assets/gdd.css, then Chromium print.
2
+ // Usage: node gdd-pdf.mjs docs/GDD.md [docs/GDD.pdf]
3
+ import { execFileSync } from 'node:child_process';
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { chromium } from './pw.mjs';
9
+
10
+ const md = process.argv[2]; if (!md) { console.error('usage: node gdd-pdf.mjs <GDD.md> [out.pdf]'); process.exit(2); }
11
+ const out = process.argv[3] || md.replace(/\.md$/i, '.pdf');
12
+ const css = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'assets', 'gdd.css');
13
+ const title = (fs.readFileSync(md, 'utf8').match(/^#\s+(.+)$/m) || [, path.basename(md, '.md')])[1];
14
+ const tmp = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'gdd-')), 'gdd.html');
15
+ execFileSync('pandoc', ['-f', 'gfm', md, '-s', '--metadata', 'title=' + title, '-c', css, '--embed-resources', '-o', tmp]);
16
+ const b = await chromium.launch(), p = await b.newPage();
17
+ await p.goto('file://' + tmp, { waitUntil: 'networkidle' });
18
+ await p.pdf({ path: out, format: 'A4', printBackground: true, margin: { top: '18mm', bottom: '18mm', left: '16mm', right: '16mm' } });
19
+ await b.close(); console.log('wrote', out);
@@ -0,0 +1,18 @@
1
+ // Finds Playwright: KAIZEN_GAME_HOME, then ~/.kaizen/kaizen-game, then kaizen-book's copy, then a normal import.
2
+ import { createRequire } from 'node:module';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+
7
+ const homes = [process.env.KAIZEN_GAME_HOME, path.join(os.homedir(), '.kaizen', 'kaizen-game'), path.join(os.homedir(), '.kaizen', 'kaizen-book')].filter(Boolean);
8
+ let pw;
9
+ for (const h of homes) {
10
+ if (!fs.existsSync(path.join(h, 'package.json'))) continue;
11
+ try { pw = createRequire(path.join(h, 'package.json'))('playwright'); break; } catch {}
12
+ }
13
+ if (!pw) try { pw = await import('playwright'); } catch { console.error('Playwright not found: run scripts/setup.sh'); process.exit(2); }
14
+ export const { chromium } = pw;
15
+ export const SOFT = ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'];
16
+ export const GPU = ['--enable-gpu', '--ignore-gpu-blocklist', '--use-angle=vulkan', '--enable-features=Vulkan'];
17
+ export const arg = (name, def) => { const i = process.argv.indexOf('--' + name); return i < 0 ? def : (process.argv[i + 1] ?? true); };
18
+ export const flag = name => process.argv.includes('--' + name);
@@ -0,0 +1,53 @@
1
+ // Static server for a game folder. Usage: node serve.mjs [root=.preview] [port=4321] [--config tools/serve.json]
2
+ // PUBLIC=1 serves only the paths the config allows ("public" globs, "downloads" map); without PUBLIC it serves everything
3
+ // under root on 127.0.0.1 (HOST overrides). GET/HEAD only. A bad request path gets 400, never a crash.
4
+ import http from 'node:http';
5
+ import fs from 'node:fs/promises';
6
+ import { readFileSync } from 'node:fs';
7
+ import path from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+
10
+ const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css', '.json': 'application/json', '.md': 'text/markdown; charset=utf-8', '.pdf': 'application/pdf', '.glb': 'model/gltf-binary', '.gltf': 'model/gltf+json', '.png': 'image/png', '.jpg': 'image/jpeg', '.webp': 'image/webp', '.svg': 'image/svg+xml', '.m4a': 'audio/mp4', '.mp3': 'audio/mpeg', '.ogg': 'audio/ogg', '.woff2': 'font/woff2', '.txt': 'text/plain; charset=utf-8' };
11
+
12
+ // new URL('//', base) and decodeURIComponent('%') both throw; an uncaught throw takes the whole server down
13
+ export function reqPath(raw) {
14
+ try { return decodeURIComponent(new URL('http://x' + (String(raw).startsWith('/') ? raw : '/' + raw)).pathname); } catch { return null; }
15
+ }
16
+ // "*" = one path segment, "**" = any depth; matched against the path without its leading slash
17
+ export function globRe(g) {
18
+ const s = g.replace(/^\//, '').split(/(\*\*|\*)/).map(p => p === '**' ? '.+' : p === '*' ? '[^/]+' : p.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('');
19
+ return new RegExp('^' + s + '$');
20
+ }
21
+ export function allowed(rel, res) {
22
+ const r = rel.replace(/^\//, '');
23
+ return !r.split('/').some(seg => seg === '..' || seg.startsWith('.')) && res.some(re => re.test(r));
24
+ }
25
+
26
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
27
+ const pos = process.argv.slice(2).filter((a, i, all) => !a.startsWith('--') && all[i - 1] !== '--config');
28
+ const ROOT = path.resolve(pos[0] || '.preview'), PORT = +(pos[1] || process.env.PORT || 4321);
29
+ const HOST = process.env.HOST || '127.0.0.1', PUBLIC = process.env.PUBLIC === '1';
30
+ const ci = process.argv.indexOf('--config'), cfgPath = path.resolve(ci > 0 ? process.argv[ci + 1] : 'tools/serve.json');
31
+ let cfg = { public: [], downloads: {} };
32
+ try { cfg = { ...cfg, ...JSON.parse(readFileSync(cfgPath, 'utf8')) }; }
33
+ catch (e) { if (PUBLIC) { console.error(`PUBLIC=1 needs a config (${cfgPath}): ${e.message}`); process.exit(1); } }
34
+ const RES = cfg.public.map(globRe);
35
+ const DL = Object.fromEntries(Object.entries(cfg.downloads || {}).map(([k, v]) => [k, path.resolve(path.dirname(cfgPath), v)]));
36
+ const send = (res, code, body, type = 'text/plain; charset=utf-8', head = {}) => {
37
+ res.writeHead(code, { 'content-type': type, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', ...head });
38
+ res.end(body);
39
+ };
40
+ http.createServer(async (req, res) => {
41
+ if (req.method !== 'GET' && req.method !== 'HEAD') return send(res, 405, 'method');
42
+ let rel = reqPath(req.url);
43
+ if (rel == null) return send(res, 400, 'bad request');
44
+ if (rel === '/') rel = '/index.html';
45
+ try {
46
+ if (DL[rel]) return send(res, 200, await fs.readFile(DL[rel]), TYPES[path.extname(rel)] || 'application/octet-stream', { 'content-disposition': `attachment; filename="${path.basename(rel)}"` });
47
+ if (PUBLIC && !allowed(rel, RES)) return send(res, 404, 'not found');
48
+ const file = path.resolve(ROOT, '.' + rel);
49
+ if (!file.startsWith(ROOT + path.sep)) return send(res, 403, 'forbidden');
50
+ send(res, 200, await fs.readFile(file), TYPES[path.extname(file)] || 'application/octet-stream');
51
+ } catch { send(res, 404, 'not found'); }
52
+ }).listen(PORT, HOST, () => console.log(`serving ${ROOT} at http://${HOST}:${PORT}${PUBLIC ? ` (public: ${cfgPath})` : ''}`));
53
+ }
@@ -0,0 +1,18 @@
1
+ // node serve.test.mjs: the path guard and allowlist matching of serve.mjs
2
+ import assert from 'node:assert';
3
+ import { reqPath, globRe, allowed } from './serve.mjs';
4
+ assert.equal(reqPath('//'), '//');
5
+ assert.equal(reqPath('/%'), null);
6
+ assert.equal(reqPath('/a/%2e%2e/x?q=1'), '/x'); // dot segments resolve, nothing climbs above root
7
+ assert.equal(reqPath('/a%20b'), '/a b');
8
+ const res = ['index.html', 'game.html', 'rounds/*.js', 'assets/**'].map(globRe);
9
+ assert.ok(allowed('/game.html', res));
10
+ assert.ok(allowed('/rounds/kurir.js', res));
11
+ assert.ok(!allowed('/rounds/sub/kurir.js', res)); // * is one segment
12
+ assert.ok(!allowed('/rounds/kurir.mjs', res));
13
+ assert.ok(allowed('/assets/kit/Textures/colormap.png', res));
14
+ assert.ok(!allowed('/v1/game.html', res)); // old versions stay private
15
+ assert.ok(!allowed('/assets/.env', res)); // no dotfiles, even under **
16
+ assert.ok(!allowed('/assets/../tools/serve.json', res));
17
+ assert.ok(!allowed('/gameXhtml', res)); // dots are literal
18
+ console.log('serve OK');
@@ -0,0 +1,9 @@
1
+ #!/bin/sh
2
+ # Installs Playwright + Chromium into ~/.kaizen/kaizen-game (override KAIZEN_GAME_HOME). About 150 MB.
3
+ set -e
4
+ H="${KAIZEN_GAME_HOME:-$HOME/.kaizen/kaizen-game}"
5
+ mkdir -p "$H"
6
+ [ -f "$H/package.json" ] || echo '{"private":true}' > "$H/package.json"
7
+ npm install --prefix "$H" --no-audit --no-fund playwright@1.62.1
8
+ cd "$H" && npx playwright install chromium
9
+ echo "ok: $H"
@@ -0,0 +1,40 @@
1
+ // Smoke test: load a page (or each ?screen=) at phone and desktop size, fail on errors and horizontal overflow.
2
+ // Usage: node smoke.mjs <url> [--screens hub,result,view=spectator] [--param screen] [--out shots] [--wait 2500] [--gpu]
3
+ // An entry with "=" is added to the query as is; others become ?<param>=<entry>. Exit 1 on any failure.
4
+ import fs from 'node:fs';
5
+ import { chromium, SOFT, GPU, arg, flag } from './pw.mjs';
6
+
7
+ const base = process.argv[2];
8
+ if (!base || base.startsWith('--')) { console.error('usage: node smoke.mjs <url> [--screens a,b] [--out shots] [--gpu]'); process.exit(2); }
9
+ const screens = String(arg('screens', '')).split(',').filter(Boolean), param = arg('param', 'screen');
10
+ const out = arg('out', 'shots'), wait = +arg('wait', 2500);
11
+ fs.mkdirSync(out, { recursive: true });
12
+ const SIZES = [['phone', { viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true }],
13
+ ['desktop', { viewport: { width: 1440, height: 900 }, deviceScaleFactor: 1 }]];
14
+ const url = s => { if (!s) return base; const u = new URL(base); const [k, v] = s.includes('=') ? s.split('=') : [param, s]; u.searchParams.set(k, v); return u.href; };
15
+
16
+ const b = await chromium.launch({ args: flag('gpu') ? GPU : SOFT });
17
+ let fails = 0;
18
+ for (const [size, opts] of SIZES) {
19
+ const ctx = await b.newContext(opts);
20
+ for (const s of screens.length ? screens : ['']) {
21
+ const p = await ctx.newPage(), errs = [];
22
+ p.on('pageerror', e => errs.push('pageerror: ' + e.message));
23
+ p.on('console', m => { if (m.type() === 'error') errs.push('console: ' + m.text()); });
24
+ p.on('response', r => { if (r.status() >= 400) errs.push(`http ${r.status()}: ${r.url()}`); });
25
+ p.on('requestfailed', r => r.failure()?.errorText !== 'net::ERR_ABORTED' && errs.push(`failed: ${r.url()} ${r.failure()?.errorText}`));
26
+ try { await p.goto(url(s), { waitUntil: 'networkidle', timeout: 30000 }); } catch (e) { errs.push('load: ' + e.message.split('\n')[0]); }
27
+ await p.waitForTimeout(wait);
28
+ const ov = await p.evaluate(() => document.documentElement.scrollWidth - innerWidth).catch(() => 0);
29
+ if (ov > 1) errs.push(`horizontal overflow ${ov}px`);
30
+ const name = `${out}/${size}-${(s || 'page').replace(/[^\w-]+/g, '_')}.png`;
31
+ await p.screenshot({ path: name }).catch(e => errs.push('screenshot: ' + e.message));
32
+ console.log(`${errs.length ? 'FAIL' : 'PASS'} ${size} ${s || '(page)'} ${name}`);
33
+ errs.forEach(e => console.log(' ' + e)); fails += errs.length ? 1 : 0;
34
+ await p.close();
35
+ }
36
+ await ctx.close();
37
+ }
38
+ await b.close();
39
+ console.log(fails ? `${fails} failed` : 'all checks passed');
40
+ process.exit(fails ? 1 : 0);
@@ -0,0 +1 @@
1
+ {"title": "Make game", "group": "media", "needs": ["node"], "status": "beta"}