@snap/valdi 1.0.11 → 1.1.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 (74) hide show
  1. package/.metadata/.bazelrc.template +7 -6
  2. package/.metadata/MODULE.bazel.template +154 -0
  3. package/bundled-skills/registry.json +13 -2
  4. package/bundled-skills/skills/valdi-animations/skill.md +197 -0
  5. package/bundled-skills/skills/valdi-async/tests/src/reference.tsx +1 -1
  6. package/bundled-skills/skills/valdi-compiler/skill.md +4 -4
  7. package/bundled-skills/skills/valdi-component-dedup/skill.md +263 -0
  8. package/bundled-skills/skills/valdi-component-tests/tests/test/ProfileCardTest.spec.tsx +1 -1
  9. package/bundled-skills/skills/valdi-custom-view/skill.md +43 -1
  10. package/bundled-skills/skills/valdi-error-handling/skill.md +238 -0
  11. package/bundled-skills/skills/valdi-gestures/skill.md +198 -0
  12. package/bundled-skills/skills/valdi-inspect/skill.md +19 -1
  13. package/bundled-skills/skills/valdi-localization/skill.md +142 -0
  14. package/bundled-skills/skills/valdi-mock-breakdown/skill.md +327 -0
  15. package/bundled-skills/skills/valdi-mock-iterate/skill.md +216 -0
  16. package/bundled-skills/skills/valdi-mock-to-module/scripts/diff.py +392 -0
  17. package/bundled-skills/skills/valdi-mock-to-module/scripts/extract_colors.py +277 -0
  18. package/bundled-skills/skills/valdi-mock-to-module/scripts/find_icon.py +303 -0
  19. package/bundled-skills/skills/valdi-mock-to-module/scripts/snapshot-and-diff.sh +53 -0
  20. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_diff.py +207 -0
  21. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_extract_colors.py +167 -0
  22. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_find_icon.py +188 -0
  23. package/bundled-skills/skills/valdi-mock-to-module/scripts/watch-and-diff.sh +181 -0
  24. package/bundled-skills/skills/valdi-mock-to-module/skill.md +451 -0
  25. package/bundled-skills/skills/valdi-navigation/skill.md +187 -0
  26. package/bundled-skills/skills/valdi-overview/skill.md +7 -4
  27. package/bundled-skills/skills/valdi-perf/skill.md +223 -0
  28. package/bundled-skills/skills/valdi-polyglot-module/skill.md +80 -0
  29. package/bundled-skills/skills/valdi-preview/skill.md +303 -0
  30. package/bundled-skills/skills/valdi-setup/skill.md +55 -5
  31. package/bundled-skills/skills/valdi-testing/skill.md +23 -7
  32. package/bundled-skills/skills/valdi-tsx/skill.md +69 -5
  33. package/bundled-skills/skills/valdi-tsx/tests/src/reference.tsx +29 -5
  34. package/dist/commands/agentCheck.js +184 -0
  35. package/dist/commands/analyze.js +16 -0
  36. package/dist/commands/analyze_commands/duplicates.js +134 -0
  37. package/dist/commands/bootstrap.js +57 -73
  38. package/dist/commands/build.js +6 -0
  39. package/dist/commands/doctor.js +42 -266
  40. package/dist/commands/hotreload.js +15 -0
  41. package/dist/commands/inspect_commands/snapshot.js +71 -6
  42. package/dist/commands/inspect_commands/snapshot.spec.js +105 -0
  43. package/dist/commands/install.js +6 -0
  44. package/dist/commands/preview.js +81 -0
  45. package/dist/commands/projectsync.js +9 -7
  46. package/dist/commands/skills_commands/install.js +6 -1
  47. package/dist/commands/skills_commands/update.js +2 -1
  48. package/dist/core/analyze/clusterer.js +150 -0
  49. package/dist/core/analyze/fingerprint.js +2 -0
  50. package/dist/core/analyze/knownPatterns.js +76 -0
  51. package/dist/core/analyze/parser.js +177 -0
  52. package/dist/core/analyze/reporter.js +83 -0
  53. package/dist/core/analyze/scanner.js +172 -0
  54. package/dist/core/analyze/similarity.js +56 -0
  55. package/dist/core/constants.js +6 -3
  56. package/dist/core/packageFiles.spec.js +1 -1
  57. package/dist/preview/previewGenerator.js +240 -0
  58. package/dist/preview/previewGenerator.spec.js +203 -0
  59. package/dist/preview/viewModelParser.js +86 -0
  60. package/dist/preview/viewModelParser.spec.js +171 -0
  61. package/dist/setup/DevSetupHelper.js +0 -54
  62. package/dist/setup/linuxSetup.js +0 -16
  63. package/dist/setup/macOSSetup.js +1 -5
  64. package/dist/utils/BazelClient.js +15 -0
  65. package/dist/utils/applicationUtils.js +15 -0
  66. package/dist/utils/daemonClient.js +3 -1
  67. package/dist/utils/linuxDistro.js +0 -21
  68. package/dist/utils/linuxDistro.spec.js +0 -48
  69. package/dist/utils/skillsAdapters.js +126 -19
  70. package/dist/utils/skillsAdapters.spec.js +141 -0
  71. package/dist/utils/skillsRegistry.js +8 -0
  72. package/package.json +16 -8
  73. package/.metadata/WORKSPACE.template +0 -57
  74. package/dist/setup/versions.js +0 -8
@@ -0,0 +1,181 @@
1
+ #!/usr/bin/env bash
2
+ # Auto-snapshot-and-diff loop: watches for hot-reload completions and
3
+ # automatically captures a snapshot + generates a pixel diff against a mock.
4
+ #
5
+ # This script monitors /tmp/hotreload.log for "Recompilation pass finished"
6
+ # lines, waits for the app to re-render, then runs snapshot + diff. It writes
7
+ # the latest result to /tmp/watch-diff-latest.txt so an AI agent can poll it.
8
+ #
9
+ # The script does NOT kill any running processes -- it only observes and snapshots.
10
+ #
11
+ # Usage:
12
+ # # Watch and auto-diff after each hot-reload
13
+ # bash watch-and-diff.sh /tmp/mock.png --key CommunitiesFeed --port 13592
14
+ #
15
+ # # With context for in-app Playground
16
+ # bash watch-and-diff.sh /tmp/mock.png --key CommunitiesFeed --port 13592 --context "0 8"
17
+ #
18
+ # Arguments:
19
+ # $1 - Mock image path (required)
20
+ # --key - Component key for snapshot (default: "PreviewRoot")
21
+ # --port - App port (default: 13591)
22
+ # --context - Context args for in-app snapshots, e.g. "0 8"
23
+ # --output - Diff output path (default: /tmp/mock-vs-render-diff.png)
24
+
25
+ set -euo pipefail
26
+
27
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
28
+
29
+ # --- Argument parsing ---
30
+ MOCK_PATH="${1:?Usage: watch-and-diff.sh <mock_path> [--key KEY] [--port PORT] [--context \"IDX IDX\"] [--output PATH]}"
31
+ shift
32
+
33
+ KEY="PreviewRoot"
34
+ PORT="13591"
35
+ CONTEXT_ARGS=""
36
+ OUTPUT="/tmp/mock-vs-render-diff.png"
37
+
38
+ while [[ $# -gt 0 ]]; do
39
+ case "$1" in
40
+ --key) KEY="$2"; shift 2 ;;
41
+ --port) PORT="$2"; shift 2 ;;
42
+ --context) CONTEXT_ARGS="$2"; shift 2 ;;
43
+ --output) OUTPUT="$2"; shift 2 ;;
44
+ *) echo "Unknown arg: $1" >&2; exit 1 ;;
45
+ esac
46
+ done
47
+
48
+ # Validate mock image exists
49
+ if [[ ! -f "$MOCK_PATH" ]]; then
50
+ echo "ERROR: Mock image not found: $MOCK_PATH" >&2
51
+ exit 1
52
+ fi
53
+
54
+ HOTRELOAD_LOG="/tmp/hotreload.log"
55
+ LATEST_FILE="/tmp/watch-diff-latest.txt"
56
+
57
+ # We use a FIFO so tail runs as a separate process we can kill on cleanup,
58
+ # while the read loop runs in the main shell (preserving function access).
59
+ FIFO="/tmp/watch-diff-fifo.$$"
60
+ mkfifo "$FIFO"
61
+
62
+ TAIL_PID=""
63
+
64
+ # --- Graceful shutdown ---
65
+ cleanup() {
66
+ echo ""
67
+ echo "[$(date '+%H:%M:%S')] Stopping watch-and-diff..."
68
+ if [[ -n "$TAIL_PID" ]] && kill -0 "$TAIL_PID" 2>/dev/null; then
69
+ kill "$TAIL_PID" 2>/dev/null || true
70
+ wait "$TAIL_PID" 2>/dev/null || true
71
+ fi
72
+ rm -f "$FIFO"
73
+ echo "[$(date '+%H:%M:%S')] Stopped."
74
+ exit 0
75
+ }
76
+ trap cleanup SIGINT SIGTERM EXIT
77
+
78
+ # --- Resolve snapshot command ---
79
+ SNAPSHOT_CMD=""
80
+ if command -v valdi-sc &>/dev/null; then
81
+ SNAPSHOT_CMD="valdi-sc inspect snapshot"
82
+ elif command -v valdi &>/dev/null; then
83
+ SNAPSHOT_CMD="valdi inspect snapshot"
84
+ else
85
+ echo "ERROR: Neither valdi-sc nor valdi found in PATH" >&2
86
+ exit 1
87
+ fi
88
+
89
+ # --- Snapshot + diff function ---
90
+ do_snapshot_and_diff() {
91
+ local ts
92
+ ts="$(date '+%Y-%m-%d %H:%M:%S')"
93
+ echo ""
94
+ echo "[$ts] Hot-reload detected. Waiting 4s for re-render..."
95
+ sleep 4
96
+
97
+ echo "[$ts] Capturing snapshot (key=$KEY, port=$PORT)..."
98
+
99
+ local snapshot_output snapshot_path
100
+ # shellcheck disable=SC2086
101
+ snapshot_output=$($SNAPSHOT_CMD $CONTEXT_ARGS --key "$KEY" --port "$PORT" 2>&1) || true
102
+ snapshot_path=$(echo "$snapshot_output" | grep -o '"path":"[^"]*"' | head -1 | sed 's/"path":"//;s/"//')
103
+
104
+ if [[ -z "$snapshot_path" || ! -f "$snapshot_path" ]]; then
105
+ echo "[$ts] ERROR: Could not capture snapshot. Output:" >&2
106
+ echo "$snapshot_output" >&2
107
+ {
108
+ echo "timestamp=$ts"
109
+ echo "status=error"
110
+ echo "error=snapshot_failed"
111
+ } > "$LATEST_FILE"
112
+ return 1
113
+ fi
114
+
115
+ echo "[$ts] Snapshot: $snapshot_path"
116
+ echo "[$ts] Generating diff..."
117
+
118
+ local diff_output match_pct
119
+ diff_output=$(python3 "$SCRIPT_DIR/diff.py" "$MOCK_PATH" "$snapshot_path" --output "$OUTPUT" 2>&1) || true
120
+ echo "$diff_output"
121
+
122
+ # Extract match percentage from diff.py output
123
+ match_pct=$(echo "$diff_output" | grep -o 'Match: [0-9.]*%' | head -1 | grep -o '[0-9.]*')
124
+ if [[ -z "$match_pct" ]]; then
125
+ match_pct="unknown"
126
+ fi
127
+
128
+ # Write result to latest file for AI agent polling
129
+ {
130
+ echo "timestamp=$ts"
131
+ echo "status=ok"
132
+ echo "match_pct=$match_pct"
133
+ echo "snapshot=$snapshot_path"
134
+ echo "diff=$OUTPUT"
135
+ echo "mock=$MOCK_PATH"
136
+ } > "$LATEST_FILE"
137
+
138
+ echo ""
139
+ echo "[$ts] Result: ${match_pct}% match"
140
+ echo "[$ts] Diff image: $OUTPUT"
141
+ echo "[$ts] Latest result written to: $LATEST_FILE"
142
+ echo "---"
143
+ }
144
+
145
+ # --- Main loop ---
146
+ echo "============================================"
147
+ echo " watch-and-diff"
148
+ echo "============================================"
149
+ echo "Mock: $MOCK_PATH"
150
+ echo "Key: $KEY"
151
+ echo "Port: $PORT"
152
+ echo "Context: ${CONTEXT_ARGS:-<none>}"
153
+ echo "Output: $OUTPUT"
154
+ echo "Log: $HOTRELOAD_LOG"
155
+ echo "Latest: $LATEST_FILE"
156
+ echo "============================================"
157
+ echo ""
158
+
159
+ # Ensure the hotreload log exists
160
+ if [[ ! -f "$HOTRELOAD_LOG" ]]; then
161
+ echo "Waiting for $HOTRELOAD_LOG to appear..."
162
+ while [[ ! -f "$HOTRELOAD_LOG" ]]; do
163
+ sleep 1
164
+ done
165
+ echo "Log file appeared."
166
+ fi
167
+
168
+ echo "[$(date '+%H:%M:%S')] Monitoring for hot-reload completions (Ctrl+C to stop)..."
169
+ echo ""
170
+
171
+ # Start tail writing to the FIFO in the background.
172
+ # -n 0 means start from the current end of the file (ignore old lines).
173
+ tail -n 0 -f "$HOTRELOAD_LOG" > "$FIFO" &
174
+ TAIL_PID=$!
175
+
176
+ # Read from the FIFO in the main shell so functions and variables are accessible.
177
+ while IFS= read -r line; do
178
+ if [[ "$line" == *"Recompilation pass finished"* ]]; then
179
+ do_snapshot_and_diff || true
180
+ fi
181
+ done < "$FIFO"
@@ -0,0 +1,451 @@
1
+ # valdi-mock-to-module
2
+
3
+ Turn a screenshot or design mock into a running Valdi module. Two-phase pipeline: get something visible fast (Phase 1), then refine with parallel specialist agents and pixel diff (Phase 2).
4
+
5
+ ## When to use
6
+
7
+ - User provides a screenshot or mock and says "build this" or "turn this into a Valdi component"
8
+ - User wants to go from visual design to running code
9
+ - User invokes `/valdi-mock-to-module`
10
+
11
+ ## Prerequisites
12
+
13
+ - A Valdi workspace (Valdi repo, Valdi_Widgets, or any repo with `valdi_modules/`)
14
+ - The `valdi` CLI installed and on PATH
15
+ - For live preview: macOS (uses `valdi_application` -> `_macos` target)
16
+ - Pillow for pixel diff: `pip3 install Pillow`
17
+
18
+ ---
19
+
20
+ ## CRITICAL RULES
21
+
22
+ These rules were learned the hard way. Violating them wastes time.
23
+
24
+ ### 1. NEVER kill the running app — ever
25
+
26
+ **Never** kill the macOS preview app or port 13591. The user keeps the app running across sessions. Killing it forces a slow rebuild/relaunch and loses window positioning.
27
+
28
+ At the start of the pipeline, only kill **hot-reloader processes** (valdi_compiler, valdi_companion, run_hotreloader, "valdi hotreload", port 9010). **Never** kill port 13591 or the app process.
29
+
30
+ During iteration, don't kill anything — just edit files and let hot-reload push changes.
31
+
32
+ ### 2. Check hot-reload log after EVERY edit
33
+
34
+ After EVERY file edit, immediately check compilation:
35
+
36
+ ```bash
37
+ tail -5 /tmp/hotreload.log
38
+ ```
39
+
40
+ - ✅ `Recompilation pass finished` with recent timestamp → success
41
+ - ❌ Error in YOUR file → fix before making more edits
42
+ - ⚠️ Errors in OTHER modules → ignore (pre-existing)
43
+
44
+ ### 3. Batch edits, then check once
45
+
46
+ Apply ALL specialist agent fixes in a single batch edit. Check the hot-reload log once after the batch. Then take one snapshot + diff. This is much faster than one-at-a-time edits. Only split edits if a batch fails to compile — then bisect to find the broken change.
47
+
48
+ ### 4. Phone-width frame for accurate proportions
49
+
50
+ PreviewRoot MUST wrap the component in a fixed 390px-wide container. Without this, the desktop window stretches the layout wider than a phone screen, making pixel diff useless.
51
+
52
+ ```tsx
53
+ onRender(): void {
54
+ <view key="PreviewRoot" style={styles.root}>
55
+ <view style={styles.phoneFrame}>
56
+ <YourComponent />
57
+ </view>
58
+ </view>;
59
+ }
60
+
61
+ const styles = {
62
+ root: new Style<View>({
63
+ width: '100%', height: '100%',
64
+ backgroundColor: '#333333', alignItems: 'center',
65
+ }),
66
+ phoneFrame: new Style<View>({
67
+ width: '390', height: '100%', backgroundColor: '#FFFFFF',
68
+ }),
69
+ };
70
+ ```
71
+
72
+ ### 5. BUILD.bazel dep changes require a full recompile
73
+
74
+ If you change `BUILD.bazel` (e.g. adding a new dependency), you **must kill the app and do a full rebuild**. Hot-reload only recompiles TypeScript within the existing dependency graph — the running binary doesn't have the new dependency's compiled code.
75
+
76
+ After any BUILD.bazel dep change:
77
+ 1. Kill hot-reloader processes
78
+ 2. Kill the app
79
+ 3. Rebuild and relaunch
80
+ 4. Restart hot-reload
81
+
82
+ **Plan your deps up front** to avoid mid-iteration rebuilds.
83
+
84
+ ---
85
+
86
+ ## Pipeline overview
87
+
88
+ ```
89
+ Mock image
90
+ |
91
+ v
92
+ [Phase 1: Bare-bones]
93
+ |-- 1. Breakdown (analyze layout)
94
+ |-- 2. Generate (write TSX — rough structure, placeholder styles)
95
+ |-- 3. Build + launch + hot-reload
96
+ |-- 4. First snapshot + pixel diff
97
+ |
98
+ v
99
+ [Phase 2: Parallel refinement]
100
+ |-- Spin up 3 specialist agents (research only, no edits):
101
+ | |-- Text Agent (fonts, sizes, colors, content, positioning)
102
+ | |-- Icons Agent (icon selection, stroke/fill, tints)
103
+ | |-- Widgets Agent (widget library replacements for raw primitives)
104
+ |
105
+ |-- Diff Coordinator (main agent):
106
+ | |-- Batch all specialist fixes into a single edit
107
+ | |-- Check hot-reload once after the batch
108
+ | |-- Re-diff with --auto-mask after each batch
109
+ | |-- Repeat until MATCH or 5 iterations
110
+ |
111
+ v
112
+ Done — present final render + diff
113
+ ```
114
+
115
+ **Phase 1 goal**: Something visible on screen fast. Don't perfect anything.
116
+
117
+ **Phase 2 goal**: Converge on the mock. Specialists research in parallel; main agent applies edits.
118
+
119
+ ---
120
+
121
+ ## Step 1: Breakdown
122
+
123
+ Analyze the mock image. **Follow the `/valdi-mock-breakdown` skill**.
124
+
125
+ 1. **Copy mock to stable path**: `cp /path/to/mock.png /tmp/mock.png` (Desktop screenshots can disappear)
126
+ 2. **Extract colors programmatically** — NEVER guess. Use the bundled `extract_colors.py`:
127
+ ```bash
128
+ # Auto-detect thumbnail regions (left column) + ALL colored regions (entire image)
129
+ python3 <skill_dir>/scripts/extract_colors.py /tmp/mock.png --auto-thumbnails --auto-colors
130
+
131
+ # Sample specific pixel colors
132
+ python3 <skill_dir>/scripts/extract_colors.py /tmp/mock.png \
133
+ --sample "badge:305,60" "green_dot:90,355"
134
+ ```
135
+ **Always use BOTH `--auto-thumbnails` AND `--auto-colors`** — thumbnails only scans the left column; colors scans the entire image for buttons, badges, and icons.
136
+ **Watch for colored pill badges** — mocks often contain small colored pill badges (e.g., blue "New Chats", red "LIVE") that look like plain text at low resolution. The pixel diff dilutes them across segment averages. Do a manual visual pass through each row looking for colored elements beyond icons/dots. Use `--sample` to extract exact badge colors.
137
+ 3. Describe the visual layout (structure, sections, components)
138
+ 4. Identify which Valdi primitives and widgets to use
139
+ 5. Plan the component tree before writing code
140
+
141
+ Share your analysis with the user before proceeding.
142
+
143
+ ---
144
+
145
+ ## Step 2: Generate the preview harness
146
+
147
+ The preview harness lives at `apps/preview/` in the workspace root.
148
+
149
+ ### PreviewRoot.tsx
150
+
151
+ Write a `StatefulComponent` that renders the target UI, wrapped in a 390px phone frame:
152
+ - Empty `ViewModel` and `ComponentContext`
153
+ - All styles in a `const styles` object at the bottom
154
+ - Sample data hardcoded as constants
155
+
156
+ ### BUILD.bazel
157
+
158
+ ```python
159
+ load("@valdi//bzl/valdi:valdi_application.bzl", "valdi_application")
160
+ load("@valdi//bzl/valdi:valdi_module.bzl", "valdi_module")
161
+
162
+ valdi_module(
163
+ name = "preview",
164
+ srcs = glob(["**/*.ts", "**/*.tsx"]),
165
+ visibility = ["//visibility:public"],
166
+ deps = [
167
+ "@valdi//src/valdi_modules/src/valdi/valdi_core",
168
+ "@valdi//src/valdi_modules/src/valdi/valdi_tsx",
169
+ ],
170
+ )
171
+
172
+ valdi_application(
173
+ name = "preview_app",
174
+ root_component_path = "PreviewRoot@preview/PreviewRoot",
175
+ title = "Valdi Preview",
176
+ deps = [":preview"],
177
+ )
178
+ ```
179
+
180
+ **Workspace detection**: If `WORKSPACE` contains `workspace(name = "valdi")`, use `//` prefix. Otherwise `@valdi//`.
181
+
182
+ ### tsconfig.json
183
+
184
+ For **external repos**:
185
+ ```json
186
+ {
187
+ "extends": "../../valdi_modules/_configs/base.tsconfig.json",
188
+ "compilerOptions": { "paths": { "preview/*": ["./*"] } }
189
+ }
190
+ ```
191
+
192
+ For the **Valdi repo**:
193
+ ```json
194
+ {
195
+ "extends": "../../src/valdi_modules/_configs/base.tsconfig.json",
196
+ "compilerOptions": {
197
+ "paths": {
198
+ "preview/*": ["./*"],
199
+ "valdi_core/*": ["../../src/valdi_modules/src/valdi/valdi_core/*"],
200
+ "valdi_tsx/*": ["../../src/valdi_modules/src/valdi/valdi_tsx/*"]
201
+ }
202
+ }
203
+ }
204
+ ```
205
+
206
+ ### Style pitfalls (causes silent failures)
207
+
208
+ ```tsx
209
+ // opacity must be a number, not a string
210
+ opacity: 0.3 // CORRECT
211
+ opacity: '0.3' // WRONG — TypeScript error
212
+
213
+ // No overflow: 'hidden' on View
214
+ overflow: 'visible' // CORRECT
215
+ overflow: 'hidden' // WRONG — only 'visible' or 'scroll'
216
+
217
+ // Only system, system-bold, system-italic font weights
218
+ font: 'system-bold 16' // CORRECT
219
+ font: 'system-semibold 16' // WRONG — falls back to regular at runtime
220
+
221
+ // flexGrow is a number
222
+ flexGrow: 1 // CORRECT
223
+ flexGrow: '1' // WRONG
224
+
225
+ // boxShadow format
226
+ boxShadow: '0 2 8 rgba(0,0,0,0.12)' // xOffset yOffset blur color
227
+
228
+ // WRONG: <scrollview> doesn't exist
229
+ <scrollview>...</scrollview>
230
+ // CORRECT: The element is <scroll>
231
+ <scroll>...</scroll>
232
+
233
+ // WRONG: scrollDirection prop doesn't exist
234
+ <scroll scrollDirection="horizontal">
235
+ // CORRECT: Use horizontal boolean
236
+ <scroll horizontal={true}>
237
+
238
+ // WRONG: padding on Label
239
+ new Style<Label>({ padding: '10' })
240
+ // CORRECT: Label doesn't support padding — use margin
241
+ new Style<Label>({ margin: '10' })
242
+
243
+ // WRONG: importing Image from NativeTemplateElements
244
+ import { Image } from 'valdi_tsx/src/NativeTemplateElements';
245
+ // CORRECT: <image> is a JSX intrinsic, not an importable class
246
+ // Use Style<View> for image container styles
247
+
248
+ // WRONG: gap property (doesn't exist on View)
249
+ new Style<View>({ flexDirection: 'row', gap: '8' })
250
+ // CORRECT: use margin on child elements instead
251
+ // In JSX: <view marginRight={8}> or margin="0 8 0 0"
252
+
253
+ // WRONG: icon typed as string
254
+ rightIcon?: string;
255
+ <image src={vm.rightIcon} /> // Type error: Asset not assignable to string
256
+ // CORRECT: icon values are Asset type
257
+ import { Asset } from 'valdi_core/src/Asset';
258
+ rightIcon?: Asset;
259
+ ```
260
+
261
+ ---
262
+
263
+ ## Step 3: Build, launch, and set up hot-reload
264
+
265
+ ### Kill stale processes first (ONLY at start, not during iteration)
266
+
267
+ ```bash
268
+ pkill -f valdi_compiler
269
+ pkill -f valdi_companion
270
+ pkill -f run_hotreloader
271
+ pkill -f "valdi hotreload"
272
+ lsof -ti:9010 | xargs kill
273
+ # NEVER kill port 13591 — that's the running app. Leave it open.
274
+ ```
275
+
276
+ ### First build
277
+
278
+ ```bash
279
+ cd <workspace_root>
280
+
281
+ # External repos:
282
+ bazel build //apps/preview:preview_app_macos
283
+ open bazel-bin/apps/preview/preview_app_macos_archive-root/Valdi\ Preview.app
284
+
285
+ # Start hot-reload
286
+ valdi hotreload --target //apps/preview:preview_app_hotreload > /tmp/hotreload.log 2>&1 &
287
+ ```
288
+
289
+ **CRITICAL: Never use `bazel run` with hot-reload.** `bazel run` holds the bazel server lock, blocking hot-reload. Use `bazel build` + `open` separately.
290
+
291
+ Wait for the app to connect:
292
+ ```bash
293
+ valdi inspect status --port 13591
294
+ # Should show {"connected":true}
295
+ ```
296
+
297
+ ---
298
+
299
+ ## Step 4: Capture a screenshot
300
+
301
+ ```bash
302
+ valdi inspect snapshot --key PreviewRoot --port 13591
303
+ ```
304
+
305
+ The `--key` flag resolves a component tag name or element `key` prop to its element ID automatically. **Stable across hot-reloads** — no need to re-query the tree.
306
+
307
+ **Port 13591** = standalone app. Port 13592 = mobile/in-app.
308
+
309
+ Read the PNG file to view the rendered output.
310
+
311
+ ---
312
+
313
+ ## Step 5: Pixel diff
314
+
315
+ **Generate a real pixel diff** — don't eyeball. Use the bundled scripts:
316
+
317
+ ```bash
318
+ # One-shot: capture snapshot + generate diff (ALWAYS use --auto-mask)
319
+ bash <skill_dir>/scripts/snapshot-and-diff.sh /tmp/mock.png --key <ComponentKey> --port 13591
320
+
321
+ # Or just the diff (if you already have a snapshot):
322
+ python3 <skill_dir>/scripts/diff.py /tmp/mock.png /path/to/snapshot.png --auto-mask
323
+
324
+ # For iOS simulator screenshots, also mask the status bar:
325
+ python3 <skill_dir>/scripts/diff.py /tmp/mock.png /path/to/snapshot.png --auto-mask --mask "0,0,400,30"
326
+
327
+ # Auto-watch mode: monitors hot-reload and auto-diffs on each recompile
328
+ bash <skill_dir>/scripts/watch-and-diff.sh /tmp/mock.png --key <ComponentKey> --port 13591
329
+ ```
330
+
331
+ **ALWAYS use `--auto-mask`** on every diff. This auto-detects avatar/thumbnail/Bitmoji regions and excludes them from the match score. These are image-based content that the component renders as colored placeholder circles — penalizing the score for them is misleading and makes progress harder to track. For iOS simulator screenshots, also mask the status bar (`"0,0,400,30"` in resized coords) since the component can't reproduce the clock/battery/signal UI.
332
+
333
+ Output:
334
+ - `/tmp/mock-vs-render-diff.png` — side-by-side: mock | render | amplified diff | shadow diff
335
+ - Match percentage (pixels within threshold)
336
+ - `--mask` regions shown as red-tinted overlays on all panels (exclude thumbnails/photos from diff)
337
+ - `--segments N` adds per-region breakdown showing which vertical band needs the most work
338
+ - Shadow match percentage reported alongside pixel match percentage
339
+
340
+ **IMPORTANT: Always show the user the diff.** After every pixel diff, use the Read tool to display three images:
341
+ 1. The mock image (`/tmp/mock.png`)
342
+ 2. The render snapshot
343
+ 3. The diff image (`/tmp/mock-vs-render-diff.png`)
344
+ 4. **Open the diff image** so it's visible on screen: `open /tmp/mock-vs-render-diff.png`
345
+
346
+ **Bright spots in the third panel = areas that don't match.** This catches background color mismatches, spacing differences, and drop shadow issues that eyeballing misses.
347
+
348
+ ---
349
+
350
+ ## Step 6: Parallel refinement agents
351
+
352
+ After the first diff, spin up **three specialist agents in parallel** (research only, no edits).
353
+
354
+ ### Specialist memory (cross-iteration persistence)
355
+
356
+ Specialists lose context between iterations. Each agent reads/appends to `/tmp/mock-specialist-findings.json` to avoid re-researching resolved issues.
357
+
358
+ Initialize before first run:
359
+ ```bash
360
+ echo '{"text": [], "icons": [], "widgets": [], "iteration": 1}' > /tmp/mock-specialist-findings.json
361
+ ```
362
+
363
+ Include in every specialist prompt:
364
+ ```
365
+ MEMORY: Read /tmp/mock-specialist-findings.json if it exists. Skip RESOLVED issues.
366
+ After analysis, append new findings under your key. Mark fixed issues RESOLVED.
367
+ ```
368
+
369
+ ### Text Agent
370
+ Audits fonts, sizes, weights, colors, content, positioning. Checks every label against the mock.
371
+
372
+ ### Icons Agent
373
+ Audits icon names, stroke vs fill, tints, sizes, icon circle backgrounds. If the project has an icon library, **use `find_icon.py`** for fuzzy matching:
374
+ ```bash
375
+ python3 <skill_dir>/scripts/find_icon.py "chat bubble" --icons-file <path>/Icons.tsx
376
+ ```
377
+
378
+ ### Widgets Agent
379
+ Finds widget library components that could replace raw primitive constructions. Check the workspace for a shared widget/component library and use those instead of hand-building with `<view>` + `<label>`.
380
+
381
+ Each agent outputs structured fix recommendations with specific code changes.
382
+
383
+ ---
384
+
385
+ ## Step 7: Apply fixes (diff coordinator)
386
+
387
+ You are the diff coordinator. After the specialist agents report back:
388
+
389
+ 1. **Triage**: Merge all three reports into a prioritized fix list. Group by visual impact.
390
+ 2. **Batch all fixes**: Apply ALL fixes from the specialist reports in a single edit. Then check hot-reload log once: `tail -5 /tmp/hotreload.log` — confirm `Recompilation pass finished` with a recent timestamp, no errors in your file. Pre-existing errors in other modules can be ignored. If there's an error, bisect to find the broken change.
391
+ 3. **Show the pixel diff after each batch**: Run the diff script with `--auto-mask --segments 4`. **ALWAYS use `--auto-mask`** to exclude avatar/thumbnail regions:
392
+ ```bash
393
+ bash <skill_dir>/scripts/snapshot-and-diff.sh /tmp/mock.png --key <ComponentKey> --port 13591
394
+ # Or with auto-masking and segments:
395
+ python3 <skill_dir>/scripts/diff.py /tmp/mock.png <snapshot_path> --segments 4 --auto-mask --mask "0,0,400,30"
396
+ ```
397
+ Then **Read all three images** (mock, render, diff) to show the side-by-side comparison, and **open the diff image**: `open /tmp/mock-vs-render-diff.png`. The per-region breakdown tells you exactly which band of the screen needs the most work.
398
+ 4. **Read the new diff image**: Use the per-region breakdown to identify which vertical band has the lowest match %. Send that info back to the relevant specialist agent for targeted fixes.
399
+ 5. **Update specialist memory**: Increment iteration counter before re-launching specialists
400
+ 6. **Repeat** until match > 85% or 5 iterations
401
+
402
+ ### Diminishing returns (~84% ceiling)
403
+
404
+ After ~84% match on complex layouts, component tweaks yield <0.5% improvement. Remaining differences come from aspect ratio distortion (cumulative vertical drift), shadow differences, and anti-aliasing. Focus on **semantic accuracy** (correct elements, badges, colors) over pixel perfection. Don't try preserving the render's aspect ratio in the diff — forced resize to the mock's aspect ratio is correct (preserving was tested and worse).
405
+
406
+ ### Specialist semantic gap
407
+
408
+ The pixel diff misses small semantic differences (e.g., gray icon vs blue badge) because segment averages dilute small features. Specialists should **compare element-by-element** against the mock, not just audit broad categories.
409
+
410
+ ### Fix priority order
411
+
412
+ 1. **Structure** — wrong layout, missing sections
413
+ 2. **Widget replacements** — widget library components fix shadows/spacing/fonts in one shot
414
+ 3. **Text** — content, font sizes, weights, colors
415
+ 4. **Icons** — icon names, stroke/fill, tints
416
+ 5. **Colors/shadows** — backgrounds, box shadows, borders
417
+ 6. **Fine-tuning** — sub-pixel spacing, opacity
418
+
419
+ ---
420
+
421
+ ## Troubleshooting
422
+
423
+ **Build fails with "module not found"** -- Missing dep in BUILD.bazel.
424
+
425
+ **`valdi inspect` connects to wrong device** -- adb may forward port 13591. Run `adb forward --remove-all`.
426
+
427
+ **Component renders blank** -- Check `onRender()` renders elements (not returns them).
428
+
429
+ **Hot-reload not compiling** -- Check `tail -20 /tmp/hotreload.log`. Fix TypeScript errors in your file.
430
+
431
+ **`opacity: '0.3'` error** -- Must be a number: `opacity: 0.3`.
432
+
433
+ **`overflow: 'hidden'` error** -- Only `'visible'` or `'scroll'` supported.
434
+
435
+ **`font: 'system-semibold'` renders as regular** -- Only `system`, `system-bold`, `system-italic` work natively.
436
+
437
+ **Pixel diff shows stretched layout** -- Missing 390px phone frame in PreviewRoot.
438
+
439
+ **`<scrollview>` build error** — The element is `<scroll>`, not `<scrollview>`. Valdi uses `<scroll>`.
440
+
441
+ **`scrollDirection` build error** — Use `horizontal={true}` on `<scroll>`, not `scrollDirection="horizontal"`.
442
+
443
+ **`padding` on Label build error** — `Label` doesn't support `padding`. Use `margin` instead.
444
+
445
+ **`Image` import error** — `<image>` is a JSX intrinsic, not an importable class. Don't import Image.
446
+
447
+ **Widget component crashes** — Some widget components only accept a subset of layout props. Check the component's ViewModel interface for available props before passing layout properties.
448
+
449
+ **ErrorBoundary stuck after hot-reload** — If an error persists after fixing code, kill and relaunch the app. The ErrorBoundary caches error state that hot-reload can't clear.
450
+
451
+ **snapshot-and-diff.sh hangs on context selector** — When the app has multiple Valdi contexts, pass `--context <device_idx> <context_idx>` to bypass the interactive selector.