@bastani/atomic 0.6.5 → 0.6.6-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 (125) hide show
  1. package/.agents/skills/ado-commit/SKILL.md +2 -0
  2. package/.agents/skills/ado-create-pr/SKILL.md +2 -0
  3. package/.agents/skills/advanced-evaluation/SKILL.md +2 -0
  4. package/.agents/skills/ast-grep/SKILL.md +2 -0
  5. package/.agents/skills/bdi-mental-states/SKILL.md +2 -0
  6. package/.agents/skills/bun/SKILL.md +156 -122
  7. package/.agents/skills/context-compression/SKILL.md +2 -0
  8. package/.agents/skills/context-degradation/SKILL.md +2 -0
  9. package/.agents/skills/context-fundamentals/SKILL.md +2 -0
  10. package/.agents/skills/context-optimization/SKILL.md +2 -0
  11. package/.agents/skills/create-spec/SKILL.md +2 -0
  12. package/.agents/skills/docx/SKILL.md +2 -0
  13. package/.agents/skills/evaluation/SKILL.md +2 -0
  14. package/.agents/skills/explain-code/SKILL.md +2 -0
  15. package/.agents/skills/filesystem-context/SKILL.md +2 -0
  16. package/.agents/skills/find-skills/SKILL.md +2 -0
  17. package/.agents/skills/gh-commit/SKILL.md +2 -0
  18. package/.agents/skills/gh-create-pr/SKILL.md +2 -0
  19. package/.agents/skills/hosted-agents/SKILL.md +2 -0
  20. package/.agents/skills/impeccable/SKILL.md +117 -304
  21. package/.agents/skills/impeccable/agents/openai.yaml +4 -0
  22. package/.agents/skills/{adapt/SKILL.md → impeccable/reference/adapt.md} +2 -11
  23. package/.agents/skills/{animate/SKILL.md → impeccable/reference/animate.md} +15 -15
  24. package/.agents/skills/{audit/SKILL.md → impeccable/reference/audit.md} +8 -22
  25. package/.agents/skills/{bolder/SKILL.md → impeccable/reference/bolder.md} +9 -13
  26. package/.agents/skills/impeccable/reference/brand.md +114 -0
  27. package/.agents/skills/{clarify/SKILL.md → impeccable/reference/clarify.md} +2 -11
  28. package/.agents/skills/{colorize/SKILL.md → impeccable/reference/colorize.md} +23 -12
  29. package/.agents/skills/impeccable/reference/craft.md +152 -29
  30. package/.agents/skills/{critique/SKILL.md → impeccable/reference/critique.md} +25 -37
  31. package/.agents/skills/{delight/SKILL.md → impeccable/reference/delight.md} +9 -11
  32. package/.agents/skills/{distill/SKILL.md → impeccable/reference/distill.md} +2 -13
  33. package/.agents/skills/impeccable/reference/document.md +427 -0
  34. package/.agents/skills/impeccable/reference/extract.md +1 -1
  35. package/.agents/skills/{harden/SKILL.md → impeccable/reference/harden.md} +1 -43
  36. package/.agents/skills/{layout/SKILL.md → impeccable/reference/layout.md} +27 -11
  37. package/.agents/skills/impeccable/reference/live.md +594 -0
  38. package/.agents/skills/impeccable/reference/motion-design.md +12 -2
  39. package/.agents/skills/impeccable/reference/onboard.md +234 -0
  40. package/.agents/skills/{optimize/SKILL.md → impeccable/reference/optimize.md} +4 -12
  41. package/.agents/skills/{overdrive/SKILL.md → impeccable/reference/overdrive.md} +9 -21
  42. package/.agents/skills/{critique → impeccable}/reference/personas.md +1 -1
  43. package/.agents/skills/{polish/SKILL.md → impeccable/reference/polish.md} +31 -23
  44. package/.agents/skills/impeccable/reference/product.md +62 -0
  45. package/.agents/skills/{quieter/SKILL.md → impeccable/reference/quieter.md} +7 -11
  46. package/.agents/skills/impeccable/reference/shape.md +151 -0
  47. package/.agents/skills/impeccable/reference/teach.md +156 -0
  48. package/.agents/skills/{typeset/SKILL.md → impeccable/reference/typeset.md} +19 -11
  49. package/.agents/skills/impeccable/reference/typography.md +31 -14
  50. package/.agents/skills/impeccable/scripts/cleanup-deprecated.mjs +87 -17
  51. package/.agents/skills/impeccable/scripts/command-metadata.json +94 -0
  52. package/.agents/skills/impeccable/scripts/design-parser.mjs +820 -0
  53. package/.agents/skills/impeccable/scripts/detect-csp.mjs +198 -0
  54. package/.agents/skills/impeccable/scripts/is-generated.mjs +69 -0
  55. package/.agents/skills/impeccable/scripts/live-accept.mjs +595 -0
  56. package/.agents/skills/impeccable/scripts/live-browser.js +4781 -0
  57. package/.agents/skills/impeccable/scripts/live-inject.mjs +445 -0
  58. package/.agents/skills/impeccable/scripts/live-poll.mjs +186 -0
  59. package/.agents/skills/impeccable/scripts/live-server.mjs +694 -0
  60. package/.agents/skills/impeccable/scripts/live-wrap.mjs +571 -0
  61. package/.agents/skills/impeccable/scripts/live.mjs +247 -0
  62. package/.agents/skills/impeccable/scripts/load-context.mjs +141 -0
  63. package/.agents/skills/impeccable/scripts/modern-screenshot.umd.js +14 -0
  64. package/.agents/skills/impeccable/scripts/pin.mjs +214 -0
  65. package/.agents/skills/init/SKILL.md +2 -0
  66. package/.agents/skills/liteparse/SKILL.md +1 -0
  67. package/.agents/skills/memory-systems/SKILL.md +2 -0
  68. package/.agents/skills/multi-agent-patterns/SKILL.md +2 -0
  69. package/.agents/skills/opentui/SKILL.md +1 -0
  70. package/.agents/skills/pdf/SKILL.md +2 -0
  71. package/.agents/skills/playwright-cli/SKILL.md +51 -5
  72. package/.agents/skills/playwright-cli/references/playwright-tests.md +1 -1
  73. package/.agents/skills/playwright-cli/references/running-code.md +10 -0
  74. package/.agents/skills/playwright-cli/references/session-management.md +56 -0
  75. package/.agents/skills/playwright-cli/references/spec-driven-testing.md +305 -0
  76. package/.agents/skills/playwright-cli/references/test-generation.md +49 -3
  77. package/.agents/skills/pptx/SKILL.md +2 -0
  78. package/.agents/skills/project-development/SKILL.md +2 -0
  79. package/.agents/skills/prompt-engineer/SKILL.md +2 -0
  80. package/.agents/skills/research-codebase/SKILL.md +2 -0
  81. package/.agents/skills/ripgrep/SKILL.md +2 -0
  82. package/.agents/skills/skill-creator/LICENSE.txt +1 -1
  83. package/.agents/skills/skill-creator/SKILL.md +2 -0
  84. package/.agents/skills/sl-commit/SKILL.md +2 -0
  85. package/.agents/skills/sl-submit-diff/SKILL.md +2 -0
  86. package/.agents/skills/tdd/SKILL.md +4 -0
  87. package/.agents/skills/tool-design/SKILL.md +2 -0
  88. package/.agents/skills/typescript-advanced-types/SKILL.md +2 -1
  89. package/.agents/skills/typescript-expert/SKILL.md +7 -1
  90. package/.agents/skills/typescript-react-reviewer/SKILL.md +2 -1
  91. package/.agents/skills/workflow-creator/SKILL.md +75 -72
  92. package/.agents/skills/workflow-creator/references/session-config.md +48 -1
  93. package/.agents/skills/xlsx/SKILL.md +2 -0
  94. package/.opencode/opencode.json +4 -2
  95. package/dist/sdk/runtime/executor.d.ts +8 -0
  96. package/dist/sdk/runtime/executor.d.ts.map +1 -1
  97. package/dist/sdk/runtime/port-discovery.d.ts +71 -0
  98. package/dist/sdk/runtime/port-discovery.d.ts.map +1 -0
  99. package/dist/sdk/runtime/tmux.d.ts +10 -0
  100. package/dist/sdk/runtime/tmux.d.ts.map +1 -1
  101. package/dist/sdk/types.d.ts +1 -0
  102. package/dist/sdk/types.d.ts.map +1 -1
  103. package/dist/sdk/workflows/builtin/deep-research-codebase/opencode/index.d.ts.map +1 -1
  104. package/dist/sdk/workflows/builtin/open-claude-design/opencode/index.d.ts.map +1 -1
  105. package/dist/sdk/workflows/builtin/ralph/claude/index.d.ts.map +1 -1
  106. package/dist/sdk/workflows/builtin/ralph/copilot/index.d.ts.map +1 -1
  107. package/dist/sdk/workflows/builtin/ralph/helpers/prompts.d.ts +15 -0
  108. package/dist/sdk/workflows/builtin/ralph/helpers/prompts.d.ts.map +1 -1
  109. package/dist/sdk/workflows/builtin/ralph/opencode/index.d.ts.map +1 -1
  110. package/package.json +1 -1
  111. package/src/sdk/runtime/executor.test.ts +254 -1
  112. package/src/sdk/runtime/executor.ts +135 -89
  113. package/src/sdk/runtime/port-discovery.test.ts +573 -0
  114. package/src/sdk/runtime/port-discovery.ts +496 -0
  115. package/src/sdk/runtime/tmux.ts +16 -0
  116. package/src/sdk/types.ts +1 -0
  117. package/src/sdk/workflows/builtin/deep-research-codebase/opencode/index.ts +24 -6
  118. package/src/sdk/workflows/builtin/open-claude-design/opencode/index.ts +52 -13
  119. package/src/sdk/workflows/builtin/ralph/claude/index.ts +31 -3
  120. package/src/sdk/workflows/builtin/ralph/copilot/index.ts +16 -0
  121. package/src/sdk/workflows/builtin/ralph/helpers/prompts.ts +70 -3
  122. package/src/sdk/workflows/builtin/ralph/opencode/index.ts +50 -6
  123. package/.agents/skills/shape/SKILL.md +0 -96
  124. /package/.agents/skills/{critique → impeccable}/reference/cognitive-load.md +0 -0
  125. /package/.agents/skills/{critique → impeccable}/reference/heuristics-scoring.md +0 -0
@@ -0,0 +1,571 @@
1
+ /**
2
+ * CLI helper: find an element in source and wrap it in a variant container.
3
+ *
4
+ * Usage:
5
+ * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
6
+ *
7
+ * Searches project files for the element matching the query (class name, ID, or
8
+ * text snippet), wraps it with the variant scaffolding, and prints the file path
9
+ * + line range where the agent should insert variant HTML.
10
+ *
11
+ * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
12
+ */
13
+
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import { isGeneratedFile } from './is-generated.mjs';
17
+
18
+ const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
19
+
20
+ export async function wrapCli() {
21
+ const args = process.argv.slice(2);
22
+
23
+ if (args.includes('--help') || args.includes('-h')) {
24
+ console.log(`Usage: impeccable wrap [options]
25
+
26
+ Find an element in source and wrap it in a variant container.
27
+
28
+ Required:
29
+ --id ID Session ID for the variant wrapper
30
+ --count N Number of expected variants (1-8)
31
+
32
+ Element identification (at least one required):
33
+ --element-id ID HTML id attribute of the element
34
+ --classes A,B,C Comma-separated CSS class names
35
+ --tag TAG Tag name (div, section, etc.)
36
+ --query TEXT Fallback: raw text to search for
37
+
38
+ Optional:
39
+ --file PATH Source file to search in (skips auto-detection)
40
+ --text TEXT Picked element's textContent. Used to disambiguate when
41
+ classes/tag match multiple sibling elements (e.g. a list
42
+ of <Card>s with the same className). Pass the first ~80
43
+ chars of event.element.textContent.
44
+ --help Show this help message
45
+
46
+ Output (JSON):
47
+ { file, startLine, endLine, insertLine, commentSyntax }
48
+
49
+ The agent should insert variant HTML at insertLine.`);
50
+ process.exit(0);
51
+ }
52
+
53
+ const id = argVal(args, '--id');
54
+ const count = parseInt(argVal(args, '--count') || '3');
55
+ const elementId = argVal(args, '--element-id');
56
+ const classes = argVal(args, '--classes');
57
+ const tag = argVal(args, '--tag');
58
+ const query = argVal(args, '--query');
59
+ const filePath = argVal(args, '--file');
60
+ const text = argVal(args, '--text');
61
+
62
+ if (!id) { console.error('Missing --id'); process.exit(1); }
63
+ if (!elementId && !classes && !query) {
64
+ console.error('Need at least one of: --element-id, --classes, --query');
65
+ process.exit(1);
66
+ }
67
+
68
+ // Build search queries in priority order (most specific first)
69
+ const queries = buildSearchQueries(elementId, classes, tag, query);
70
+
71
+ const genOpts = { cwd: process.cwd() };
72
+
73
+ // Find the source file. Generated files are excluded from auto-search so we
74
+ // don't silently write variants into a file the next build will wipe.
75
+ let targetFile = filePath;
76
+ let matchedQuery = null;
77
+ if (!targetFile) {
78
+ for (const q of queries) {
79
+ targetFile = findFileWithQuery(q, process.cwd(), genOpts);
80
+ if (targetFile) { matchedQuery = q; break; }
81
+ }
82
+ if (!targetFile) {
83
+ // Nothing in source. Did the element show up in a generated file? That
84
+ // tells the agent "fall back to the agent-driven flow" vs "element just
85
+ // doesn't exist in this project."
86
+ let generatedHit = null;
87
+ for (const q of queries) {
88
+ generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
89
+ if (generatedHit) break;
90
+ }
91
+ if (generatedHit) {
92
+ console.error(JSON.stringify({
93
+ error: 'element_not_in_source',
94
+ fallback: 'agent-driven',
95
+ generatedMatch: path.relative(process.cwd(), generatedHit),
96
+ hint: 'Element found only in a generated file. See "Handle fallback" in live.md.',
97
+ }));
98
+ } else {
99
+ console.error(JSON.stringify({
100
+ error: 'element_not_found',
101
+ fallback: 'agent-driven',
102
+ hint: 'Element not found in any project file. It may be runtime-injected (JS component, etc.). See "Handle fallback" in live.md.',
103
+ }));
104
+ }
105
+ process.exit(1);
106
+ }
107
+ } else {
108
+ if (isGeneratedFile(targetFile, genOpts)) {
109
+ console.error(JSON.stringify({
110
+ error: 'file_is_generated',
111
+ fallback: 'agent-driven',
112
+ file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
113
+ hint: 'Explicit --file points at a generated file. Writing here gets wiped by the next build. See "Handle fallback" in live.md.',
114
+ }));
115
+ process.exit(1);
116
+ }
117
+ matchedQuery = queries[0];
118
+ }
119
+
120
+ const content = fs.readFileSync(targetFile, 'utf-8');
121
+ const lines = content.split('\n');
122
+
123
+ // Find the element, trying each query in priority order. When `--text` is
124
+ // supplied, collect every candidate the queries surface and disambiguate
125
+ // by the picked element's textContent. Without `--text`, fall back to the
126
+ // legacy first-match behavior so unmodified callers keep working.
127
+ let match = null;
128
+ if (text) {
129
+ const candidates = [];
130
+ for (const q of queries) {
131
+ const all = findAllElements(lines, q, tag);
132
+ for (const c of all) {
133
+ if (!candidates.some((x) => x.startLine === c.startLine)) {
134
+ candidates.push(c);
135
+ }
136
+ }
137
+ // Once a more-specific query (ID, full className combo) yielded a unique
138
+ // result, stop — falling through to the loose tag+single-class query
139
+ // would readmit the siblings we just disambiguated past.
140
+ if (candidates.length === 1) break;
141
+ }
142
+ if (candidates.length === 0) {
143
+ console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
144
+ process.exit(1);
145
+ }
146
+ if (candidates.length === 1) {
147
+ match = candidates[0];
148
+ } else {
149
+ const filtered = filterByText(candidates, lines, text);
150
+ if (filtered.length === 1) {
151
+ match = filtered[0];
152
+ } else if (filtered.length === 0) {
153
+ // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the
154
+ // browser-side textContent doesn't appear literally in source. Fall
155
+ // back to first-match rather than refusing — this is the same
156
+ // behavior unmodified callers see, just preserved.
157
+ match = candidates[0];
158
+ } else {
159
+ // Multiple candidates ALSO match the text. Truly ambiguous — refuse
160
+ // rather than pick wrong, and hand the agent the candidate locations
161
+ // so it can disambiguate by reading the file.
162
+ console.error(JSON.stringify({
163
+ error: 'element_ambiguous',
164
+ fallback: 'agent-driven',
165
+ file: path.relative(process.cwd(), targetFile),
166
+ candidates: filtered.map((c) => ({
167
+ startLine: c.startLine + 1,
168
+ endLine: c.endLine + 1,
169
+ })),
170
+ hint: 'Multiple source elements match both classes/tag and textContent. Pass --element-id, a more specific --text, or write the wrapper manually. See "Handle fallback" in live.md.',
171
+ }));
172
+ process.exit(1);
173
+ }
174
+ }
175
+ } else {
176
+ for (const q of queries) {
177
+ match = findElement(lines, q, tag);
178
+ if (match) break;
179
+ }
180
+ if (!match) {
181
+ console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
182
+ process.exit(1);
183
+ }
184
+ }
185
+
186
+ const { startLine, endLine } = match;
187
+ const commentSyntax = detectCommentSyntax(targetFile);
188
+ const isJsx = commentSyntax.open === '{/*';
189
+ const indent = lines[startLine].match(/^(\s*)/)[1];
190
+
191
+ // Extract the original element. Reindent under the wrapper while preserving
192
+ // the relative depth between lines — `l.trimStart()` would strip ALL leading
193
+ // whitespace and collapse e.g. `<aside>`/` <h1>`/`</aside>` (6/8/6 spaces)
194
+ // to a single uniform indent, so on accept/discard the round-trip restores
195
+ // the inner element at its parent's depth instead of nested inside it.
196
+ // Strip only the COMMON minimum leading whitespace across the picked lines;
197
+ // `deindentContent` on the accept side already mirrors this convention.
198
+ const originalLines = lines.slice(startLine, endLine + 1);
199
+ const originalBaseIndent = minLeadingSpaces(originalLines);
200
+ const reindentOriginal = (extra) => originalLines
201
+ .map((l) => (l.trim() === '' ? '' : indent + extra + l.slice(originalBaseIndent)))
202
+ .join('\n');
203
+ const originalIndented = reindentOriginal(' ');
204
+
205
+ // Wrapper attributes differ by syntax. HTML allows plain string attrs;
206
+ // JSX requires object-literal style and parses string attrs as HTML (which
207
+ // either type-errors or renders a literal CSS string).
208
+ const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
209
+
210
+ // JSX/TSX guard: the picked element occupies a single JSX child slot
211
+ // (inside `return (...)`, an array `.map(...)`, an `asChild` branch, or
212
+ // any other expression position). Replacing it with `comment + <div> +
213
+ // comment` yields three adjacent siblings — invalid JSX. We can't use a
214
+ // Fragment `<></>` either: parents that clone children (Radix `asChild`,
215
+ // Headless UI, etc.) hit "Invalid prop supplied to React.Fragment" when
216
+ // they try to pass an `id` through.
217
+ //
218
+ // Solution: keep the wrapper `<div>` as the single JSX-slot child and
219
+ // tuck both marker comments INSIDE it. accept/discard then expands its
220
+ // replacement range to include the wrapper's `<div>` open / close lines
221
+ // so the entire scaffold gets removed cleanly.
222
+ const wrapperLines = isJsx ? [
223
+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
224
+ indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
225
+ indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
226
+ indent + ' <div data-impeccable-variant="original">',
227
+ reindentOriginal(' '),
228
+ indent + ' </div>',
229
+ indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
230
+ indent + ' ' + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
231
+ indent + '</div>',
232
+ ] : [
233
+ indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
234
+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
235
+ indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
236
+ indent + ' <div data-impeccable-variant="original">',
237
+ originalIndented,
238
+ indent + ' </div>',
239
+ indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
240
+ indent + '</div>',
241
+ indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
242
+ ];
243
+
244
+ // Replace the original element with the wrapper
245
+ const newLines = [
246
+ ...lines.slice(0, startLine),
247
+ ...wrapperLines,
248
+ ...lines.slice(endLine + 1),
249
+ ];
250
+ fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
251
+
252
+ // Calculate insert line (the "insert below this line" comment).
253
+ // 0-indexed file position. Both HTML and JSX wrappers have 6 lines above
254
+ // the insert marker (HTML: start-comment + outer-div + Original-comment +
255
+ // original-div + content + close-original-div; JSX: outer-div +
256
+ // start-comment + Original-comment + original-div + content +
257
+ // close-original-div). Multi-line originals push the marker by their
258
+ // extra line count.
259
+ const insertLine = startLine + 6 + (originalLines.length - 1);
260
+
261
+ console.log(JSON.stringify({
262
+ file: path.relative(process.cwd(), targetFile),
263
+ startLine: startLine + 1, // 1-indexed for the agent
264
+ // wrapperLines is an array but one element (the original-content slot)
265
+ // is a `\n`-joined multi-line string, so the actual file-row count is
266
+ // wrapperLines.length + (originalLines.length - 1). Without the offset,
267
+ // endLine pointed inside the wrapper for any picked element that
268
+ // spanned more than one source line.
269
+ endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexed
270
+ insertLine: insertLine + 1, // 1-indexed: where variants go
271
+ commentSyntax: commentSyntax,
272
+ originalLineCount: originalLines.length,
273
+ }));
274
+ }
275
+
276
+ // ---------------------------------------------------------------------------
277
+ // Helpers
278
+ // ---------------------------------------------------------------------------
279
+
280
+ function argVal(args, flag) {
281
+ const idx = args.indexOf(flag);
282
+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
283
+ }
284
+
285
+ /**
286
+ * Build search query strings in priority order (most specific first).
287
+ * ID is most reliable, then specific class combos, then single classes, then raw query.
288
+ */
289
+ function buildSearchQueries(elementId, classes, tag, query) {
290
+ const queries = [];
291
+
292
+ // 1. ID is the most specific
293
+ if (elementId) {
294
+ queries.push('id="' + elementId + '"');
295
+ }
296
+
297
+ // 2. Full class attribute match (for elements with distinctive multi-class combos).
298
+ // Emit both class="..." (HTML) and className="..." (React/JSX) so whichever
299
+ // convention the file uses will match.
300
+ if (classes) {
301
+ const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
302
+ if (classList.length > 1) {
303
+ const joined = classList.join(' ');
304
+ const sorted = [...classList].sort((a, b) => b.length - a.length);
305
+ queries.push('class="' + joined + '"');
306
+ queries.push('className="' + joined + '"');
307
+ queries.push(sorted[0]); // most distinctive single class, fallback
308
+ } else if (classList.length === 1) {
309
+ queries.push(classList[0]);
310
+ }
311
+ }
312
+
313
+ // 3. Tag + class combo (e.g., <section class="hero">).
314
+ // Same dual-emit for JSX compatibility.
315
+ if (tag && classes) {
316
+ const firstClass = classes.split(',')[0].trim();
317
+ queries.push('<' + tag + ' class="' + firstClass);
318
+ queries.push('<' + tag + ' className="' + firstClass);
319
+ }
320
+
321
+ // 4. Raw fallback query
322
+ if (query) {
323
+ queries.push(query);
324
+ }
325
+
326
+ return queries;
327
+ }
328
+
329
+ function detectCommentSyntax(filePath) {
330
+ const ext = path.extname(filePath).toLowerCase();
331
+ if (ext === '.jsx' || ext === '.tsx') {
332
+ return { open: '{/*', close: '*/}' };
333
+ }
334
+ // HTML, Vue, Svelte, Astro all use HTML comments
335
+ return { open: '<!--', close: '-->' };
336
+ }
337
+
338
+ /**
339
+ * Search project files for the query string (class name, ID, etc.)
340
+ * Returns the first matching file path, or null.
341
+ */
342
+ function findFileWithQuery(query, cwd, genOpts = {}) {
343
+ const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
344
+ const seen = new Set();
345
+
346
+ for (const dir of searchDirs) {
347
+ const absDir = path.join(cwd, dir);
348
+ if (!fs.existsSync(absDir)) continue;
349
+ const result = searchDir(absDir, query, seen, 0, genOpts);
350
+ if (result) return result;
351
+ }
352
+ return null;
353
+ }
354
+
355
+ function searchDir(dir, query, seen, depth, genOpts) {
356
+ if (depth > 5) return null; // don't go too deep
357
+ const realDir = fs.realpathSync(dir);
358
+ if (seen.has(realDir)) return null;
359
+ seen.add(realDir);
360
+
361
+ let entries;
362
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
363
+ catch { return null; }
364
+
365
+ // Check files first
366
+ for (const entry of entries) {
367
+ if (!entry.isFile()) continue;
368
+ const ext = path.extname(entry.name).toLowerCase();
369
+ if (!EXTENSIONS.includes(ext)) continue;
370
+
371
+ const filePath = path.join(dir, entry.name);
372
+ if (!genOpts.includeGenerated && isGeneratedFile(filePath, genOpts)) continue;
373
+ try {
374
+ const content = fs.readFileSync(filePath, 'utf-8');
375
+ if (content.includes(query)) return filePath;
376
+ } catch { /* skip unreadable files */ }
377
+ }
378
+
379
+ // Then recurse into directories. Always skip node_modules and .git (never
380
+ // project content). dist/build/out are left to the isGeneratedFile guard so
381
+ // the includeGenerated second-pass can still find the element there and
382
+ // report `generatedMatch`.
383
+ for (const entry of entries) {
384
+ if (!entry.isDirectory()) continue;
385
+ if (entry.name === 'node_modules' || entry.name === '.git') continue;
386
+ const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1, genOpts);
387
+ if (result) return result;
388
+ }
389
+
390
+ return null;
391
+ }
392
+
393
+ /**
394
+ * Regex that matches a tag opener on a line. Allows the tag name to be
395
+ * followed by whitespace, `>`, `/`, or end-of-line so that multi-line JSX
396
+ * openers (e.g. `<section\n className="..."\n>`) are recognised.
397
+ */
398
+ const OPENER_RE = /<([A-Za-z][A-Za-z0-9]*)(?=[\s/>]|$)/;
399
+
400
+ /**
401
+ * Find the element's start and end line in the file.
402
+ *
403
+ * `query` is a class name, attribute fragment (`class="..."`, `className="..."`,
404
+ * `id="..."`), or a raw text snippet. Because a query can appear on a
405
+ * continuation line of a multi-line tag (e.g. the `className="..."` row of a
406
+ * `<section\n className="..."\n>` JSX tag), we walk backward from the match
407
+ * line to find the actual tag opener. When `tag` is provided, opener candidates
408
+ * must match that tag name.
409
+ */
410
+ /**
411
+ * Return the smallest leading-whitespace count across a set of lines,
412
+ * ignoring blank lines (whose indent isn't load-bearing). Used to compute
413
+ * the common base indent of a multi-line picked element so reindenting
414
+ * under the wrapper preserves the relative depth between lines.
415
+ */
416
+ function minLeadingSpaces(lines) {
417
+ let min = Infinity;
418
+ for (const l of lines) {
419
+ if (l.trim() === '') continue;
420
+ const m = l.match(/^(\s*)/);
421
+ if (m && m[1].length < min) min = m[1].length;
422
+ }
423
+ return min === Infinity ? 0 : min;
424
+ }
425
+
426
+ function findElement(lines, query, tag = null) {
427
+ // Iterate all matches — the first substring hit isn't always the right one.
428
+ for (let i = 0; i < lines.length; i++) {
429
+ if (!lines[i].includes(query)) continue;
430
+
431
+ const stripped = lines[i].trim();
432
+ if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
433
+ // Skip lines already inside a variant wrapper
434
+ if (lines[i].includes('data-impeccable-variant')) continue;
435
+
436
+ const openerLine = findOpenerLine(lines, i, tag);
437
+ if (openerLine === -1) continue;
438
+
439
+ const endLine = findClosingLine(lines, openerLine);
440
+ return { startLine: openerLine, endLine };
441
+ }
442
+
443
+ return null;
444
+ }
445
+
446
+ /**
447
+ * Like findElement, but returns every match. Used for ambiguity detection
448
+ * when the agent passes --text: when the same className appears on multiple
449
+ * sibling elements (a list of cards, repeated section variants, etc.),
450
+ * first-match silently lands on the wrong branch. Returning all matches lets
451
+ * the caller narrow by textContent or fail with a structured ambiguity error.
452
+ */
453
+ function findAllElements(lines, query, tag = null) {
454
+ const out = [];
455
+ const seen = new Set();
456
+ for (let i = 0; i < lines.length; i++) {
457
+ if (!lines[i].includes(query)) continue;
458
+ const stripped = lines[i].trim();
459
+ if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
460
+ if (lines[i].includes('data-impeccable-variant')) continue;
461
+ const openerLine = findOpenerLine(lines, i, tag);
462
+ if (openerLine === -1) continue;
463
+ if (seen.has(openerLine)) continue; // multiple matches inside the same element
464
+ seen.add(openerLine);
465
+ const endLine = findClosingLine(lines, openerLine);
466
+ out.push({ startLine: openerLine, endLine });
467
+ }
468
+ return out;
469
+ }
470
+
471
+ /**
472
+ * Narrow a candidate set to those whose source body matches a meaningful
473
+ * prefix of the picked element's textContent. The compare strips tags and
474
+ * JSX expressions, then checks two whitespace normalizations side-by-side:
475
+ *
476
+ * - single-space ("hero two second card body")
477
+ * - no-whitespace ("herotwosecondcardbody")
478
+ *
479
+ * Both are needed because `el.textContent` concatenates sibling text without
480
+ * inserting whitespace (e.g. `<h1>Hero Two</h1><p>Second…</p>` reads as
481
+ * `"Hero TwoSecond…"`), while the source has whitespace between tags. If
482
+ * EITHER normalization matches, the candidate keeps. A snippet shorter than
483
+ * 8 chars after stripping is too weak to disambiguate — the caller falls
484
+ * back to first-match.
485
+ */
486
+ function filterByText(candidates, lines, text) {
487
+ const trimmed = text.replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 80);
488
+ // Too short to disambiguate. Return [] so the caller's `filtered.length
489
+ // === 0` branch fires (fall back to first-match) — the previous
490
+ // `candidates.slice()` return forced `filtered.length > 1` and surfaced
491
+ // a spurious `element_ambiguous` error on every short-text picker event
492
+ // with multiple candidates.
493
+ if (trimmed.length < 8) return [];
494
+ const targetSpaced = trimmed;
495
+ const targetCompact = trimmed.replace(/\s+/g, '');
496
+
497
+ return candidates.filter((c) => {
498
+ const body = lines.slice(c.startLine, c.endLine + 1).join(' ');
499
+ const inner = body
500
+ .replace(/<[^>]*>/g, ' ') // strip HTML/JSX tags
501
+ .replace(/\{[^}]*\}/g, ' ') // strip JSX expressions
502
+ .toLowerCase();
503
+ const sourceSpaced = inner.replace(/\s+/g, ' ').trim();
504
+ const sourceCompact = inner.replace(/\s+/g, '');
505
+ return sourceSpaced.includes(targetSpaced) || sourceCompact.includes(targetCompact);
506
+ });
507
+ }
508
+
509
+ /**
510
+ * Resolve a match line to the real tag opener. If the match line itself opens
511
+ * a tag, return it. Otherwise walk up to 10 lines backward looking for the
512
+ * first tag opener. If `tag` is specified, the opener must match that tag
513
+ * name; an opener with a different tag name aborts the backward walk for this
514
+ * match (we don't jump across element boundaries).
515
+ *
516
+ * Returns the line index of the opener, or -1 if none can be resolved.
517
+ */
518
+ function findOpenerLine(lines, matchLine, tag) {
519
+ const self = lines[matchLine].match(OPENER_RE);
520
+ if (self) {
521
+ if (!tag || self[1] === tag) return matchLine;
522
+ return -1;
523
+ }
524
+ const MAX_BACKWALK = 10;
525
+ for (let i = matchLine - 1; i >= Math.max(0, matchLine - MAX_BACKWALK); i--) {
526
+ const opener = lines[i].match(OPENER_RE);
527
+ if (!opener) continue;
528
+ if (!tag || opener[1] === tag) return i;
529
+ // Different tag name than requested — abort; we're inside a non-target opener.
530
+ return -1;
531
+ }
532
+ return -1;
533
+ }
534
+
535
+ /**
536
+ * Starting from a line with an opening tag, find the line with the matching
537
+ * closing tag by counting tag nesting depth.
538
+ */
539
+ function findClosingLine(lines, start) {
540
+ const openMatch = lines[start].match(OPENER_RE);
541
+ if (!openMatch) return start; // caller passed a non-opener; nothing to span
542
+
543
+ const tagName = openMatch[1];
544
+ let depth = 0;
545
+ const openRe = new RegExp('<' + tagName + '(?=[\\s/>]|$)', 'g');
546
+ const selfCloseRe = new RegExp('<' + tagName + '[^>]*/>', 'g');
547
+ const closeRe = new RegExp('</' + tagName + '\\s*>', 'g');
548
+
549
+ for (let i = start; i < lines.length; i++) {
550
+ const line = lines[i];
551
+ const opens = (line.match(openRe) || []).length;
552
+ const selfCloses = (line.match(selfCloseRe) || []).length;
553
+ const closes = (line.match(closeRe) || []).length;
554
+
555
+ depth += opens - selfCloses - closes;
556
+
557
+ if (depth <= 0) return i;
558
+ }
559
+
560
+ // If we can't find the close, return a reasonable guess
561
+ return Math.min(start + 50, lines.length - 1);
562
+ }
563
+
564
+ // Auto-execute when run directly (node live-wrap.mjs ...)
565
+ const _running = process.argv[1];
566
+ if (_running?.endsWith('live-wrap.mjs') || _running?.endsWith('live-wrap.mjs/')) {
567
+ wrapCli();
568
+ }
569
+
570
+ // Test exports (used by tests/live-wrap.test.mjs)
571
+ export { buildSearchQueries, findElement, findClosingLine, detectCommentSyntax };