litclaude-ai 0.3.3 → 0.3.7

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 (56) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +5 -5
  3. package/README_ko-KR.md +5 -5
  4. package/RELEASE_CHECKLIST.md +8 -6
  5. package/cover.png +0 -0
  6. package/generate_cover.py +1 -1
  7. package/package.json +1 -1
  8. package/plugins/litclaude/.claude-plugin/plugin.json +1 -1
  9. package/plugins/litclaude/bin/litclaude-hook.js +42 -6
  10. package/plugins/litclaude/commands/dynamic-workflow.md +6 -6
  11. package/plugins/litclaude/commands/litresearch.md +37 -0
  12. package/plugins/litclaude/commands/review-work.md +5 -5
  13. package/plugins/litclaude/hooks/hooks.json +12 -0
  14. package/plugins/litclaude/lib/litgoal/autoloop.mjs +78 -0
  15. package/plugins/litclaude/lib/litgoal/cli.mjs +8 -0
  16. package/plugins/litclaude/skills/lit-loop/SKILL.md +12 -10
  17. package/plugins/litclaude/skills/lit-plan/SKILL.md +9 -10
  18. package/plugins/litclaude/skills/litgoal/SKILL.md +41 -5
  19. package/plugins/litclaude/skills/litresearch/SKILL.md +148 -0
  20. package/plugins/litclaude/skills/lsp-setup/SKILL.md +151 -0
  21. package/plugins/litclaude/skills/lsp-setup/references/bash/README.md +63 -0
  22. package/plugins/litclaude/skills/lsp-setup/references/c-cpp/README.md +72 -0
  23. package/plugins/litclaude/skills/lsp-setup/references/csharp/README.md +81 -0
  24. package/plugins/litclaude/skills/lsp-setup/references/dart/README.md +53 -0
  25. package/plugins/litclaude/skills/lsp-setup/references/elixir/README.md +57 -0
  26. package/plugins/litclaude/skills/lsp-setup/references/go/README.md +59 -0
  27. package/plugins/litclaude/skills/lsp-setup/references/haskell/README.md +64 -0
  28. package/plugins/litclaude/skills/lsp-setup/references/java/README.md +66 -0
  29. package/plugins/litclaude/skills/lsp-setup/references/julia/README.md +62 -0
  30. package/plugins/litclaude/skills/lsp-setup/references/kotlin/README.md +68 -0
  31. package/plugins/litclaude/skills/lsp-setup/references/lua/README.md +64 -0
  32. package/plugins/litclaude/skills/lsp-setup/references/php/README.md +56 -0
  33. package/plugins/litclaude/skills/lsp-setup/references/python/README.md +68 -0
  34. package/plugins/litclaude/skills/lsp-setup/references/ruby/README.md +62 -0
  35. package/plugins/litclaude/skills/lsp-setup/references/rust/README.md +61 -0
  36. package/plugins/litclaude/skills/lsp-setup/references/swift/README.md +60 -0
  37. package/plugins/litclaude/skills/lsp-setup/references/terraform/README.md +61 -0
  38. package/plugins/litclaude/skills/lsp-setup/references/typescript/README.md +77 -0
  39. package/plugins/litclaude/skills/lsp-setup/references/yaml/README.md +60 -0
  40. package/plugins/litclaude/skills/lsp-setup/references/zig/README.md +55 -0
  41. package/plugins/litclaude/skills/lsp-setup/scripts/detect-lsp.ts +220 -0
  42. package/plugins/litclaude/skills/lsp-setup/scripts/lsp-server-table.ts +146 -0
  43. package/plugins/litclaude/skills/lsp-setup/scripts/tsconfig.json +18 -0
  44. package/plugins/litclaude/skills/lsp-setup/scripts/verify-lsp.ts +242 -0
  45. package/plugins/litclaude/skills/start-work/SKILL.md +12 -13
  46. package/plugins/litclaude/skills/visual-qa/SKILL.md +259 -0
  47. package/plugins/litclaude/skills/visual-qa/scripts/ansi.ts +17 -0
  48. package/plugins/litclaude/skills/visual-qa/scripts/cli.ts +96 -0
  49. package/plugins/litclaude/skills/visual-qa/scripts/east-asian-width.ts +72 -0
  50. package/plugins/litclaude/skills/visual-qa/scripts/image-diff.ts +109 -0
  51. package/plugins/litclaude/skills/visual-qa/scripts/png-crc.ts +27 -0
  52. package/plugins/litclaude/skills/visual-qa/scripts/png-decode.ts +206 -0
  53. package/plugins/litclaude/skills/visual-qa/scripts/png-synth.ts +57 -0
  54. package/plugins/litclaude/skills/visual-qa/scripts/tui-grid.ts +88 -0
  55. package/plugins/litclaude/skills/visual-qa/scripts/types.ts +54 -0
  56. package/scripts/qa-portable-install.sh +1 -1
@@ -0,0 +1,259 @@
1
+ ---
2
+ name: visual-qa
3
+ description: "Rigorous visual QA for any UI you built or changed, across BOTH web/page UIs and TUI/terminal UIs. MUST USE after building or changing any UI to verify it visually before declaring it done. Captures objective reference evidence with a bundled diff script (image-diff for screenshots, tui-check for terminal captures), then runs two parallel read-only oracle passes (design-system and functional integrity; visual fidelity and CJK precision) and synthesizes one good/bad verdict. Triggers: visual QA, visual regression, screenshot diff, pixel diff, image comparison, UI looks wrong, design system check, alpha channel breakage, responsive check, CJK text, Korean/Japanese/Chinese text clipping, glyph drop, TUI alignment, terminal UI, tmux capture, box-drawing border misalignment, wide-character column drift."
4
+ ---
5
+
6
+ # Visual QA - Dual-Oracle Web and TUI Verification
7
+
8
+ The LitClaude visual specialist for Claude Code. Verify a rendered UI against
9
+ intent using objective script evidence plus two parallel read-only oracle
10
+ passes, then synthesize one good/bad verdict. The script numbers focus the
11
+ reviewers. They are not the verdict.
12
+
13
+ ## Runtime
14
+
15
+ The bundled scripts are dependency-free TypeScript with zero external packages
16
+ (no install step). Run them with either:
17
+
18
+ - Node 22.6+: `node --experimental-strip-types "$SKILL_DIR/scripts/cli.ts" ...`
19
+ - bun: `bun "$SKILL_DIR/scripts/cli.ts" ...`
20
+
21
+ PNG decoding, CRC, deflate/inflate, ANSI stripping, and East-Asian width all use
22
+ only Node built-ins (`node:fs`, `node:zlib`, `node:buffer`). `$SKILL_DIR` is this
23
+ skill's own directory (the folder containing this SKILL.md).
24
+
25
+ ## Purpose and when to use
26
+
27
+ - Use after you build or change any UI, before calling it done. Covers web/page
28
+ UIs and TUI/terminal UIs.
29
+ - Use when output must match a mock, a baseline, or a stated design intent; when
30
+ you suspect a regression; when CJK (Korean/Japanese/Chinese) text may clip,
31
+ misalign, or wrap awkwardly; when a claimed design system might actually be a
32
+ flat image; when a terminal layout may overflow or its borders may break.
33
+ - Skip when there is no rendered surface (pure backend or library logic with no
34
+ visual or terminal output). For broad post-implementation review use
35
+ review-work; this skill is the visual specialist.
36
+
37
+ ## Step 1 - Detect the surface
38
+
39
+ - Web/page UI: renders in a browser (HTML/CSS/JS, components, canvas, SVG).
40
+ Evidence is screenshots.
41
+ - TUI/terminal UI: renders as text in a terminal (box-drawing, panes, status
42
+ lines, REPL/TUI apps). Evidence is terminal captures.
43
+
44
+ If the change touches both, run both capture tracks and feed both into the passes.
45
+
46
+ ## Step 2 - Capture objective reference evidence
47
+
48
+ ### Web
49
+
50
+ 1. Capture a REFERENCE image: the user's mock/target, or a known-good baseline.
51
+ Save as PNG.
52
+ 2. Capture the ACTUAL rendered screenshot at the same viewport size using the
53
+ project's browser tooling (Claude Code's browser/Playwright tooling). Save as
54
+ PNG.
55
+ 3. Run the diff and keep the JSON:
56
+
57
+ ```
58
+ node --experimental-strip-types "$SKILL_DIR/scripts/cli.ts" image-diff <reference.png> <actual.png>
59
+ ```
60
+
61
+ Key fields: `dimensionsMatch`, `diffRatio` (0..1), `similarityScore` (0..100),
62
+ `alphaChannelIntact`, `hotspots[]` (grid regions ranked by `diffRatio`).
63
+
64
+ ### TUI
65
+
66
+ 1. Capture plain text and an ANSI-preserving copy:
67
+
68
+ ```
69
+ tmux capture-pane -p > capture.txt
70
+ tmux capture-pane -e -p > capture-ansi.txt
71
+ ```
72
+
73
+ 2. Run the check with the REAL terminal width and keep the JSON:
74
+
75
+ ```
76
+ node --experimental-strip-types "$SKILL_DIR/scripts/cli.ts" tui-check capture.txt --cols <N>
77
+ ```
78
+
79
+ Key fields: `maxWidth`, `overflowLines[]`, `borderMisaligned`,
80
+ `wideCharColumns[]`, `hasAnsi`.
81
+
82
+ This JSON (diff ratio, similarity score, hotspots or overflow lines, border
83
+ alignment, wide-char columns, alpha) is REFERENCE evidence to aim the reviewers.
84
+ It is not the verdict by itself.
85
+
86
+ ## Step 3 - Dispatch two read-only QA subagents in parallel
87
+
88
+ Spawn BOTH oracle passes as background subagents in a single message using
89
+ Claude Code's `Task` tool with `run_in_background: true`, so they run
90
+ concurrently. Each oracle is read-only: it reviews and reports, and must not
91
+ modify files. Each returns PASS, REVISE, or FAIL with concrete, located
92
+ findings. Pass A proves the surface is a real design-system implementation, not
93
+ a mock-only or faked-image substitute. Pass B directly opens screenshots and
94
+ inspects source/content for visual and CJK defects. The main session waits for
95
+ both background subagents to finish, then synthesizes the verdict.
96
+
97
+ Paste evidence directly into each prompt: source code, the plain-text TUI
98
+ captures, the script JSON, and the screenshot paths plus your described
99
+ observations for web. The two passes differ in depth by charter, not by any
100
+ model or effort setting.
101
+
102
+ ### Pass A - Design-system and functional integrity (deeper, strict)
103
+
104
+ Launch with the `Task` tool, `run_in_background: true`, description
105
+ "Visual QA pass A: design-system and functional integrity", prompt:
106
+
107
+ ```
108
+ REVIEW TYPE: DESIGN-SYSTEM AND FUNCTIONAL INTEGRITY (read-only)
109
+ TIER INTENT: Treat this as the deeper, stricter pass. Reason exhaustively before concluding. Assume a plausible-looking surface may be faked or mock-only until the source proves otherwise. Do not modify any file.
110
+
111
+ INTENT:
112
+ {What the user asked for, the mock or baseline, and the constraints.}
113
+
114
+ SURFACE: {web | tui | both}
115
+
116
+ SOURCE CODE:
117
+ {Full source of the UI: components, styles/tokens, layout, render code. Include neighboring files that show existing patterns.}
118
+
119
+ CAPTURES:
120
+ {Web: actual screenshot path(s) plus your described observations. TUI: paste capture.txt and capture-ansi.txt inline.}
121
+
122
+ SHARED SCRIPT EVIDENCE (reference, not verdict):
123
+ {Paste the image-diff or tui-check JSON. Use alphaChannelIntact for the transparency check.}
124
+
125
+ CHECK EACH:
126
+ 1. Real design system vs ad-hoc/mock-only: are styles driven by coherent design tokens and reused primitives, or one-off hardcoded values scattered per element? Treat mock-only screens, static compositions, or one-page hardcoded styling with no reusable system as BLOCKING unless the user explicitly requested a throwaway mock.
127
+ 2. Faked-with-an-image anti-pattern: is the UI a real DOM/component tree, or a pasted raster/screenshot or background-image standing in for live elements? For TUI: a real layout that reflows, or hardcoded pre-rendered text at fixed widths?
128
+ 3. Alpha and transparency: handled correctly, with no unexpected opaque or black fills and correct PNG/CSS alpha? Cross-check alphaChannelIntact.
129
+ 4. Code style and implementation quality.
130
+ 5. Responsive and resize behavior across viewport sizes (web) or terminal resize (TUI).
131
+ 6. Do the user-intended FEATURES actually work: interactions, states, navigation (web); input handling, resize, scroll (TUI)? Trace the code paths.
132
+
133
+ OUTPUT:
134
+ VERDICT: PASS | REVISE | FAIL
135
+ CONFIDENCE: HIGH | MEDIUM | LOW
136
+ SUMMARY: 1-3 sentences
137
+ FINDINGS: for each, [dimension] [severity] what is wrong, where (file/line or capture region), and the concrete fix
138
+ WHAT IS GOOD: correct aspects that must not regress
139
+ BLOCKING: items that must be fixed; empty if PASS
140
+ ```
141
+
142
+ ### Pass B - Visual fidelity and CJK precision (focused)
143
+
144
+ Launch with the `Task` tool, `run_in_background: true`, description
145
+ "Visual QA pass B: visual fidelity and CJK precision", prompt:
146
+
147
+ ```
148
+ REVIEW TYPE: VISUAL FIDELITY AND CJK PRECISION (read-only)
149
+ TIER INTENT: Treat this as the focused visual pass. Directly open the screenshots with Claude Code's image-reading tool (the Read tool on the PNG path) before judging. Anchor every claim to the script evidence, source code, and captures. Do not modify any file.
150
+
151
+ INTENT:
152
+ {What the user requested and the mock or baseline to match.}
153
+
154
+ SURFACE: {web | tui | both}
155
+
156
+ CAPTURES:
157
+ {Web: actual and reference screenshot paths plus your described observations. TUI: paste capture.txt and capture-ansi.txt inline.}
158
+
159
+ SOURCE CODE:
160
+ {For web: include the rendered text/content, components, typography, layout, and style code. For TUI: include render code that controls wrapping, width, and wide-character handling.}
161
+
162
+ SCRIPT EVIDENCE (required, consume every field):
163
+ {Paste the image-diff or tui-check JSON.}
164
+
165
+ USE THE EVIDENCE:
166
+ - Web (image-diff): start from diffRatio and similarityScore, then directly open every screenshot path and inspect every hotspots[] entry (gridX, gridY, x, y, width, height, diffRatio). Explain the visual cause of each flagged region from the pixels and source/content together.
167
+ - TUI (tui-check): inspect maxWidth vs expectedColumns, every overflowLines[] entry, borderMisaligned, and wideCharColumns[].
168
+
169
+ CHECK:
170
+ 1. Does the rendered output match what the user requested: layout, spacing, color, type, alignment?
171
+ 2. CJK precision:
172
+ - Web: natural CJK line breaking for display and body text. Flag oversized headings that create orphaned one-character or final-syllable lines, split Korean/Japanese/Chinese semantic phrases unnaturally, detach labels such as `[Image #1]` from their content, clip baselines/descenders, drop glyphs (tofu), or show font metric mismatch.
173
+ - TUI: wide-character column drift (CJK cells counted as 1 instead of 2), box-drawing border misalignment, content overflowing past the terminal width.
174
+
175
+ OUTPUT:
176
+ VERDICT: PASS | REVISE | FAIL
177
+ CONFIDENCE: HIGH | MEDIUM | LOW
178
+ SUMMARY: 1-3 sentences
179
+ EVIDENCE TRACE: each hotspot or overflow line mapped to its visual cause
180
+ FINDINGS: for each, [severity] what is wrong, where (hotspot grid or capture line:col), and the concrete fix
181
+ BLOCKING: items that must be fixed; empty if PASS
182
+ ```
183
+
184
+ ## Step 4 - Synthesize one verdict
185
+
186
+ When both background subagents return, merge them into a single report. Per
187
+ dimension, mark good or bad with evidence. For each bad item, state what is
188
+ wrong, where (file/line, hotspot grid, or capture line), and the concrete fix.
189
+ Call out what is genuinely good so it is not regressed later.
190
+
191
+ Completion gate: do not declare the UI done until both passes are satisfied, OR
192
+ the remaining gaps are explicitly listed and accepted by the user. A high
193
+ `similarityScore` with an open Pass A finding, for example a faked-image layout
194
+ or a broken feature, is still a FAIL.
195
+
196
+ ```markdown
197
+ # Visual QA - Verdict: GOOD | NEEDS WORK
198
+
199
+ | Dimension | Pass | Verdict | Evidence |
200
+ |---|---|---|---|
201
+ | Design system real vs faked | A | good/bad | ... |
202
+ | Features work | A | good/bad | ... |
203
+ | Responsive / resize | A | good/bad | ... |
204
+ | Alpha / transparency | A+B | good/bad | ... |
205
+ | Visual fidelity to intent | B | good/bad | ... |
206
+ | CJK precision | B | good/bad | ... |
207
+
208
+ ## Must fix
209
+ [Blocking items, each with location and fix, in priority order]
210
+
211
+ ## Good, keep it
212
+ [Correct aspects that must not regress]
213
+
214
+ ## Completion gate
215
+ [Satisfied, or the exact remaining gaps and who accepted them]
216
+ ```
217
+
218
+ ## Reference evidence is not the verdict
219
+
220
+ The script quantifies pixels and columns. It cannot judge whether the result is
221
+ a real design system, whether features work, or whether intent was met. A 99/100
222
+ `similarityScore` can still hide a pasted-image fake, a broken interaction, or
223
+ clipped CJK descenders. Use the numbers to aim the oracles, then trust the
224
+ synthesized review.
225
+
226
+ Illustrative output (locked field names):
227
+
228
+ ```json
229
+ {
230
+ "command": "image-diff",
231
+ "dimensionsMatch": true,
232
+ "reference": { "width": 1440, "height": 900 },
233
+ "actual": { "width": 1440, "height": 900 },
234
+ "totalPixels": 1296000,
235
+ "diffPixels": 38880,
236
+ "diffRatio": 0.03,
237
+ "similarityScore": 97,
238
+ "alphaChannelIntact": true,
239
+ "hotspots": [
240
+ { "gridX": 2, "gridY": 0, "x": 960, "y": 0, "width": 480, "height": 300, "diffRatio": 0.21 }
241
+ ],
242
+ "summary": "97/100 similarity; one hotspot in the top-right header region."
243
+ }
244
+ ```
245
+
246
+ ```json
247
+ {
248
+ "command": "tui-check",
249
+ "expectedColumns": 80,
250
+ "lineCount": 24,
251
+ "lineWidths": [80, 80, 82, 80],
252
+ "maxWidth": 82,
253
+ "overflowLines": [ { "line": 3, "width": 82 } ],
254
+ "borderMisaligned": true,
255
+ "wideCharColumns": [12, 13],
256
+ "hasAnsi": false,
257
+ "summary": "Line 3 overflows 80 cols by 2; borders misaligned at wide-char columns 12-13."
258
+ }
259
+ ```
@@ -0,0 +1,17 @@
1
+ const ESC = String.fromCharCode(0x1b)
2
+ const CSI = String.fromCharCode(0x9b)
3
+
4
+ // Matches CSI/escape sequences (colors, cursor moves) without embedding raw
5
+ // control characters in the regex source.
6
+ const ANSI_PATTERN = new RegExp(
7
+ `[${ESC}${CSI}][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]`,
8
+ "g",
9
+ )
10
+
11
+ export function stripAnsi(input: string): string {
12
+ return input.replace(ANSI_PATTERN, "")
13
+ }
14
+
15
+ export function hasAnsi(input: string): boolean {
16
+ return stripAnsi(input) !== input
17
+ }
@@ -0,0 +1,96 @@
1
+ import { readFileSync } from "node:fs"
2
+ import { fileURLToPath } from "node:url"
3
+ import { resolve } from "node:path"
4
+ import process from "node:process"
5
+
6
+ import { diffImages } from "./image-diff.ts"
7
+ import { decodePng } from "./png-decode.ts"
8
+ import { checkTui } from "./tui-grid.ts"
9
+ import type { ImageDiffResult, TuiCheckResult } from "./types.ts"
10
+
11
+ export class CliError extends Error {
12
+ readonly name = "CliError"
13
+ }
14
+
15
+ const DEFAULT_COLUMNS = 80
16
+ const COLS_FLAG = "--cols"
17
+
18
+ export function runImageDiff(args: readonly string[]): ImageDiffResult {
19
+ const referencePath = args[0]
20
+ const actualPath = args[1]
21
+ if (referencePath === undefined || actualPath === undefined) {
22
+ throw new CliError("usage: image-diff <reference.png> <actual.png>")
23
+ }
24
+ const reference = decodePng(readFileSync(referencePath))
25
+ const actual = decodePng(readFileSync(actualPath))
26
+ return diffImages(reference, actual)
27
+ }
28
+
29
+ function parseColumns(args: readonly string[]): number {
30
+ for (let index = 0; index < args.length; index++) {
31
+ const arg = args[index] ?? ""
32
+ if (arg === COLS_FLAG) {
33
+ const parsed = Number(args[index + 1])
34
+ if (!Number.isInteger(parsed) || parsed <= 0) {
35
+ throw new CliError(`${COLS_FLAG} requires a positive integer`)
36
+ }
37
+ return parsed
38
+ }
39
+ if (arg.startsWith(`${COLS_FLAG}=`)) {
40
+ const parsed = Number(arg.slice(COLS_FLAG.length + 1))
41
+ if (!Number.isInteger(parsed) || parsed <= 0) {
42
+ throw new CliError(`${COLS_FLAG} requires a positive integer`)
43
+ }
44
+ return parsed
45
+ }
46
+ }
47
+ return DEFAULT_COLUMNS
48
+ }
49
+
50
+ export function runTuiCheck(args: readonly string[]): TuiCheckResult {
51
+ const capturePath = args[0]
52
+ if (capturePath === undefined || capturePath.startsWith("--")) {
53
+ throw new CliError("usage: tui-check <capture.txt> [--cols N]")
54
+ }
55
+ const text = readFileSync(capturePath, "utf8")
56
+ return checkTui(text, parseColumns(args.slice(1)))
57
+ }
58
+
59
+ export function run(argv: readonly string[]): ImageDiffResult | TuiCheckResult {
60
+ const command = argv[0]
61
+ const rest = argv.slice(1)
62
+ switch (command) {
63
+ case "image-diff":
64
+ return runImageDiff(rest)
65
+ case "tui-check":
66
+ return runTuiCheck(rest)
67
+ default:
68
+ throw new CliError(`unknown command "${command ?? ""}"; expected "image-diff" or "tui-check"`)
69
+ }
70
+ }
71
+
72
+ function main(argv: readonly string[]): void {
73
+ try {
74
+ const result = run(argv)
75
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`)
76
+ } catch (error) {
77
+ const message = error instanceof Error ? error.message : String(error)
78
+ process.stderr.write(`visual-qa error: ${message}\n`)
79
+ process.exitCode = 1
80
+ }
81
+ }
82
+
83
+ // Entry guard that works under both bun and Node (`--experimental-strip-types`).
84
+ function isMainModule(): boolean {
85
+ const entry = process.argv[1]
86
+ if (entry === undefined) return false
87
+ try {
88
+ return resolve(fileURLToPath(import.meta.url)) === resolve(entry)
89
+ } catch {
90
+ return false
91
+ }
92
+ }
93
+
94
+ if (isMainModule()) {
95
+ main(process.argv.slice(2))
96
+ }
@@ -0,0 +1,72 @@
1
+ export interface CodePointRange {
2
+ readonly start: number
3
+ readonly end: number
4
+ }
5
+
6
+ // Combining marks and zero-width code points advance the cursor by 0 columns.
7
+ const ZERO_WIDTH_RANGES: readonly CodePointRange[] = [
8
+ { start: 0x0300, end: 0x036f }, // combining diacritical marks
9
+ { start: 0x0483, end: 0x0489 }, // combining Cyrillic
10
+ { start: 0x0591, end: 0x05bd }, // Hebrew points
11
+ { start: 0x0610, end: 0x061a }, // Arabic marks
12
+ { start: 0x064b, end: 0x065f }, // Arabic marks
13
+ { start: 0x0670, end: 0x0670 }, // Arabic superscript alef
14
+ { start: 0x06d6, end: 0x06dc }, // Arabic small high marks
15
+ { start: 0x1160, end: 0x11ff }, // Hangul Jamo medial/final (combining)
16
+ { start: 0x200b, end: 0x200f }, // zero-width space / directional marks
17
+ { start: 0x202a, end: 0x202e }, // bidi embeddings
18
+ { start: 0x2060, end: 0x2064 }, // word joiner / invisible operators
19
+ { start: 0x20d0, end: 0x20ff }, // combining marks for symbols
20
+ { start: 0xfe20, end: 0xfe2f }, // combining half marks
21
+ { start: 0xfeff, end: 0xfeff }, // zero-width no-break space (BOM)
22
+ ]
23
+
24
+ // East Asian Wide + Fullwidth code points advance the cursor by 2 columns.
25
+ const WIDE_RANGES: readonly CodePointRange[] = [
26
+ { start: 0x1100, end: 0x115f }, // Hangul Jamo (leading consonants)
27
+ { start: 0x231a, end: 0x231b }, // watch / hourglass
28
+ { start: 0x2e80, end: 0x303e }, // CJK radicals, Kangxi, CJK symbols
29
+ { start: 0x3041, end: 0x33ff }, // Kana, Bopo phonetics, CJK compatibility
30
+ { start: 0x3400, end: 0x4dbf }, // CJK Unified Ext A
31
+ { start: 0x4e00, end: 0x9fff }, // CJK Unified Ideographs
32
+ { start: 0xa000, end: 0xa4cf }, // Yi syllables
33
+ { start: 0xa960, end: 0xa97f }, // Hangul Jamo Ext-A
34
+ { start: 0xac00, end: 0xd7a3 }, // Hangul syllables
35
+ { start: 0xf900, end: 0xfaff }, // CJK compatibility ideographs
36
+ { start: 0xfe10, end: 0xfe19 }, // vertical forms
37
+ { start: 0xfe30, end: 0xfe6f }, // CJK compatibility / small forms
38
+ { start: 0xff00, end: 0xff60 }, // fullwidth forms (halfwidth starts at 0xff61)
39
+ { start: 0xffe0, end: 0xffe6 }, // fullwidth signs
40
+ { start: 0x1b000, end: 0x1b16f }, // Kana supplement / extended
41
+ { start: 0x1f200, end: 0x1f2ff }, // enclosed ideographic supplement
42
+ { start: 0x1f300, end: 0x1faff }, // emoji and pictographs
43
+ { start: 0x20000, end: 0x3fffd }, // CJK Unified Ext B and beyond
44
+ ]
45
+
46
+ function inRanges(codePoint: number, ranges: readonly CodePointRange[]): boolean {
47
+ for (const range of ranges) {
48
+ if (codePoint >= range.start && codePoint <= range.end) {
49
+ return true
50
+ }
51
+ }
52
+ return false
53
+ }
54
+
55
+ export function charWidth(codePoint: number): 0 | 1 | 2 {
56
+ if (codePoint === 0) return 0
57
+ if (codePoint < 0x20) return 0 // C0 control
58
+ if (codePoint >= 0x7f && codePoint <= 0x9f) return 0 // DEL and C1 control
59
+ if (inRanges(codePoint, ZERO_WIDTH_RANGES)) return 0
60
+ if (inRanges(codePoint, WIDE_RANGES)) return 2
61
+ return 1
62
+ }
63
+
64
+ export function stringWidth(text: string): number {
65
+ let total = 0
66
+ for (const char of text) {
67
+ const codePoint = char.codePointAt(0)
68
+ if (codePoint === undefined) continue
69
+ total += charWidth(codePoint)
70
+ }
71
+ return total
72
+ }
@@ -0,0 +1,109 @@
1
+ import type { DecodedImage, Hotspot, ImageDiffResult } from "./types.ts"
2
+
3
+ const GRID_SIZE = 8
4
+
5
+ function round4(value: number): number {
6
+ return Math.round(value * 10000) / 10000
7
+ }
8
+
9
+ function pixelsDiffer(ref: Uint8Array, refOffset: number, act: Uint8Array, actOffset: number): boolean {
10
+ return (
11
+ ref[refOffset] !== act[actOffset] ||
12
+ ref[refOffset + 1] !== act[actOffset + 1] ||
13
+ ref[refOffset + 2] !== act[actOffset + 2] ||
14
+ ref[refOffset + 3] !== act[actOffset + 3]
15
+ )
16
+ }
17
+
18
+ function buildHotspots(
19
+ cellDiff: readonly number[],
20
+ cellTotal: readonly number[],
21
+ cols: number,
22
+ rows: number,
23
+ overlapWidth: number,
24
+ overlapHeight: number,
25
+ ): Hotspot[] {
26
+ const hotspots: Hotspot[] = []
27
+ for (let gridY = 0; gridY < rows; gridY++) {
28
+ for (let gridX = 0; gridX < cols; gridX++) {
29
+ const index = gridY * cols + gridX
30
+ const diff = cellDiff[index] ?? 0
31
+ const total = cellTotal[index] ?? 0
32
+ if (diff === 0 || total === 0) continue
33
+ const left = Math.floor((gridX * overlapWidth) / cols)
34
+ const right = Math.floor(((gridX + 1) * overlapWidth) / cols)
35
+ const top = Math.floor((gridY * overlapHeight) / rows)
36
+ const bottom = Math.floor(((gridY + 1) * overlapHeight) / rows)
37
+ hotspots.push({
38
+ gridX,
39
+ gridY,
40
+ x: left,
41
+ y: top,
42
+ width: right - left,
43
+ height: bottom - top,
44
+ diffRatio: round4(diff / total),
45
+ })
46
+ }
47
+ }
48
+ hotspots.sort((a, b) => b.diffRatio - a.diffRatio)
49
+ return hotspots
50
+ }
51
+
52
+ function buildSummary(
53
+ similarityScore: number,
54
+ diffPixels: number,
55
+ totalPixels: number,
56
+ dimensionsMatch: boolean,
57
+ hotspotCount: number,
58
+ ): string {
59
+ const parts = [`${similarityScore}/100 similarity`, `${diffPixels}/${totalPixels} pixels differ`]
60
+ if (!dimensionsMatch) parts.push("dimensions differ")
61
+ if (hotspotCount > 0) parts.push(`${hotspotCount} hotspot region(s)`)
62
+ return `${parts.join("; ")}.`
63
+ }
64
+
65
+ export function diffImages(reference: DecodedImage, actual: DecodedImage): ImageDiffResult {
66
+ const overlapWidth = Math.min(reference.width, actual.width)
67
+ const overlapHeight = Math.min(reference.height, actual.height)
68
+ const totalPixels = overlapWidth * overlapHeight
69
+ const cols = Math.max(1, Math.min(GRID_SIZE, overlapWidth))
70
+ const rows = Math.max(1, Math.min(GRID_SIZE, overlapHeight))
71
+ const cellDiff = new Array<number>(cols * rows).fill(0)
72
+ const cellTotal = new Array<number>(cols * rows).fill(0)
73
+
74
+ let diffPixels = 0
75
+ for (let y = 0; y < overlapHeight; y++) {
76
+ const cellY = Math.min(rows - 1, Math.floor((y * rows) / overlapHeight))
77
+ for (let x = 0; x < overlapWidth; x++) {
78
+ const cellX = Math.min(cols - 1, Math.floor((x * cols) / overlapWidth))
79
+ const cellIndex = cellY * cols + cellX
80
+ cellTotal[cellIndex] = (cellTotal[cellIndex] ?? 0) + 1
81
+ const refOffset = (y * reference.width + x) * 4
82
+ const actOffset = (y * actual.width + x) * 4
83
+ if (pixelsDiffer(reference.rgba, refOffset, actual.rgba, actOffset)) {
84
+ diffPixels++
85
+ cellDiff[cellIndex] = (cellDiff[cellIndex] ?? 0) + 1
86
+ }
87
+ }
88
+ }
89
+
90
+ const diffRatio = totalPixels === 0 ? 0 : diffPixels / totalPixels
91
+ const similarityScore = Math.round((1 - diffRatio) * 100)
92
+ const hotspots = buildHotspots(cellDiff, cellTotal, cols, rows, overlapWidth, overlapHeight)
93
+ const dimensionsMatch = reference.width === actual.width && reference.height === actual.height
94
+ const alphaChannelIntact = !(reference.hasTransparentPixels && !actual.hasTransparentPixels)
95
+
96
+ return {
97
+ command: "image-diff",
98
+ dimensionsMatch,
99
+ reference: { width: reference.width, height: reference.height },
100
+ actual: { width: actual.width, height: actual.height },
101
+ totalPixels,
102
+ diffPixels,
103
+ diffRatio: round4(diffRatio),
104
+ similarityScore,
105
+ alphaChannelIntact,
106
+ hotspots,
107
+ summary: buildSummary(similarityScore, diffPixels, totalPixels, dimensionsMatch, hotspots.length),
108
+ }
109
+ }
@@ -0,0 +1,27 @@
1
+ import { Buffer } from "node:buffer"
2
+
3
+ export const PNG_SIGNATURE: Buffer = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
4
+
5
+ function buildCrcTable(): Uint32Array {
6
+ const table = new Uint32Array(256)
7
+ for (let n = 0; n < 256; n++) {
8
+ let c = n
9
+ for (let k = 0; k < 8; k++) {
10
+ c = (c & 1) === 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
11
+ }
12
+ table[n] = c >>> 0
13
+ }
14
+ return table
15
+ }
16
+
17
+ const CRC_TABLE = buildCrcTable()
18
+
19
+ export function crc32(data: Buffer): number {
20
+ let crc = 0xffffffff
21
+ for (let i = 0; i < data.length; i++) {
22
+ const byte = data[i] ?? 0
23
+ const entry = CRC_TABLE[(crc ^ byte) & 0xff] ?? 0
24
+ crc = entry ^ (crc >>> 8)
25
+ }
26
+ return (crc ^ 0xffffffff) >>> 0
27
+ }