The design language that makes your AI harness better at design.
JavaScript
Fix: live-wrap finds where a self-closing element ends (#852) (#916)
Abdul Wahab6e802bd0ed99
diff --git a/crates/live/src/live_insert.rs b/crates/live/src/live_insert.rsindex c3e46c572..929276a33 100644--- a/crates/live/src/live_insert.rs+++ b/crates/live/src/live_insert.rs@@ -244,7 +244,7 @@ fn insert_cli(args: &[String], io: &mut Io) -> i32 {"error": "element_ambiguous","fallback": "agent-driven","file": jsp::relative("/", &cwd, &target_abs),- "candidates": candidates.iter().map(|c| json!({ "startLine": c.start_line + 1, "endLine": c.end_line + 1 })).collect::<Vec<_>>(),+ "candidates": candidates.iter().map(|c| json!({ "startLine": c.start_line + 1, "endLine": c.end_line.map(|e| e + 1) })).collect::<Vec<_>>(),})),);return 1;@@ -260,7 +260,20 @@ fn insert_cli(args: &[String], io: &mut Io) -> i32 {};let start_line = m.start_line;- let end_line = m.end_line;+ let svelte_component = should_use_svelte_component_injection(&target_file, &env);+ let end_line = match m.end_line {+ Some(end) => end,+ // Inserting before a source anchor needs only its start line.+ None if position == "before" && !svelte_component => start_line,+ None => {+ let file = jsp::relative("/", &cwd, &target_abs);+ eprintln(+ io,+ &json_compact(&element_unclosed_error(&file, start_line)),+ );+ return 1;+ }+ };let comment_syntax = detect_comment_syntax(&target_file);let style_mode = detect_style_mode(&target_file);let is_jsx = comment_syntax.0 == "{/*";@@ -271,7 +284,7 @@ fn insert_cli(args: &[String], io: &mut Io) -> i32 {};let rel_target_file = jsp::to_posix(&jsp::relative("/", &cwd, &target_abs));- if should_use_svelte_component_injection(&target_file, &env) {+ if svelte_component {let anchor_end = end_line.min(lines.len() - 1);let session = scaffold_svelte_component_insert_session(&id,diff --git a/crates/live/src/live_wrap.rs b/crates/live/src/live_wrap.rsindex bcd63337e..73b9c94c7 100644--- a/crates/live/src/live_wrap.rs+++ b/crates/live/src/live_wrap.rs@@ -62,7 +62,7 @@ fn nonempty(v: Option<String>) -> Option<String> {fn candidates_json(list: &[ElementMatch]) -> Value {Value::Array(list.iter()- .map(|c| json!({ "startLine": c.start_line + 1, "endLine": c.end_line + 1 }))+ .map(|c| json!({ "startLine": c.start_line + 1, "endLine": c.end_line.map(|e| e + 1) })).collect(),)}@@ -261,7 +261,11 @@ fn wrap_cli(args: &[String], io: &mut Io) -> i32 {}let start_line = m.start_line;- let end_line = m.end_line.min(lines.len() - 1);+ let Some(end_line) = m.end_line else {+ let err = element_unclosed_error(&target_rel_for_errors, start_line);+ eprintln(io, &json_compact(&err));+ return 1;+ };let comment_syntax = detect_comment_syntax(&target_file);let style_mode = detect_style_mode(&target_file);let is_jsx = comment_syntax.0 == "{/*";diff --git a/crates/live/src/wrap_common.rs b/crates/live/src/wrap_common.rsindex 71f1b6a4e..484a9bf9e 100644--- a/crates/live/src/wrap_common.rs+++ b/crates/live/src/wrap_common.rs@@ -132,7 +132,19 @@ pub fn opener_tag(line: &str) -> Option<String> {#[derive(Debug, Clone, Copy, PartialEq)]pub struct ElementMatch {pub start_line: usize,- pub end_line: usize,+ /// None when the element never closes; callers refuse rather than guess.+ pub end_line: Option<usize>,+}++/// The refusal wrap and insert print for a match with no end line.+pub fn element_unclosed_error(file: &str, start_line: usize) -> Value {+ json!({+ "error": "element_unclosed",+ "fallback": "agent-driven",+ "file": file,+ "startLine": start_line + 1,+ "hint": "Found the element's opening tag at startLine but not where it closes. Find its end and write the scaffold manually. See \"Handle fallback\" in live.md.",+ })}fn skip_line(line: &str) -> bool {@@ -155,10 +167,9 @@ pub fn find_element(lines: &[String], query: &str, tag: Option<&str>) -> Option<let Some(opener) = find_opener_line(lines, i, tag) else {continue;};- let end = find_closing_line(lines, opener);return Some(ElementMatch {start_line: opener,- end_line: end,+ end_line: find_closing_line(lines, opener),});}None@@ -185,10 +196,9 @@ pub fn find_all_elements(lines: &[String], query: &str, tag: Option<&str>) -> Vecontinue;}seen.push(opener);- let end = find_closing_line(lines, opener);out.push(ElementMatch {start_line: opener,- end_line: end,+ end_line: find_closing_line(lines, opener),});}out@@ -214,7 +224,12 @@ pub fn filter_by_text(candidates.iter().filter(|c| {- let body = lines[c.start_line..=c.end_line.min(lines.len() - 1)].join(" ");+ // An unclosed element has no end to read up to. For matching only,+ // look ahead a fixed window; nothing is written from this range.+ let end = c+ .end_line+ .unwrap_or_else(|| (c.start_line + 50).min(lines.len() - 1));+ let body = lines[c.start_line..=end].join(" ");let inner = TAG_RE.replace_all(&body, " ");let inner = JSX_EXPR_RE.replace_all(&inner, " ");let inner = inner.to_lowercase();@@ -254,45 +269,95 @@ pub fn find_opener_line(lines: &[String], match_line: usize, tag: Option<&str>)None}-fn count_matches(re: &Regex, line: &str) -> usize {- re.find_iter(line).count()-}--/// JS: findClosingLine(lines, start)-pub fn find_closing_line(lines: &[String], start: usize) -> usize {+/// The line the element opened on `start` closes on. None when it never+/// closes: a guessed end would hand the caller the element's neighbours.+pub fn find_closing_line(lines: &[String], start: usize) -> Option<usize> {let Some(tag_name) = opener_tag(&lines[start]) else {- return start;+ return Some(start);};- let esc = regex::escape(&tag_name);- // JS: new RegExp('<' + tagName + '(?=[\\s/>]|$)', 'g'), no lookahead in- // `regex`: match `<tag` and check the follower by hand.- let open_re = Regex::new(&format!("<{}", esc)).unwrap();- let self_close_re = Regex::new(&format!("<{}[^>]*/>", esc)).unwrap();- let close_re = Regex::new(&format!("</{}{}*>", esc, WS)).unwrap();- let tag_len = tag_name.chars().count();+ // Scan chars with state carried across lines: an opening tag can span+ // lines and hold `>` inside a quoted value or a `{...}` prop (`=>`).+ let name: Vec<char> = tag_name.chars().collect();let mut depth: i64 = 0;+ let mut in_tag = false;+ let mut braces = 0usize;+ let mut quote: Option<char> = None;+ // A closing tag whose `>` sits on the next line (`</section` / `>`).+ let mut pending_close = false;for (i, line) in lines.iter().enumerate().skip(start) {let chars: Vec<char> = line.chars().collect();- let mut opens = 0usize;- for m in open_re.find_iter(line) {- let start_c = line[..m.start()].chars().count();- let after = start_c + 1 + tag_len;- let ok = after >= chars.len()- || is_js_whitespace(chars[after])- || chars[after] == '/'- || chars[after] == '>';- if ok {- opens += 1;+ if std::mem::take(&mut pending_close)+ && chars.iter().find(|c| !is_js_whitespace(**c)) == Some(&'>')+ {+ depth -= 1;+ }+ let mut escaped = false;+ for (j, &c) in chars.iter().enumerate() {+ if in_tag {+ if let Some(q) = quote {+ // A JS string takes backslash escapes; an attribute value+ // does not.+ if escaped {+ escaped = false;+ } else if braces > 0 && c == '\\' {+ escaped = true;+ } else if c == q {+ quote = None;+ }+ } else if c == '{' {+ braces += 1;+ } else if c == '}' {+ braces = braces.saturating_sub(1);+ } else if c == '"' || c == '\'' || c == '`' {+ // Outside `{...}` a quote opens an attribute value. Inside,+ // a backtick opens a template literal, and `"` or `'` open+ // a JS string only when it closes on this line and is no+ // contraction: an apostrophe in a comment or in text is not+ // a delimiter.+ let opens = if braces == 0 {+ c != '`'+ } else {+ c == '`'+ || chars[j + 1..].contains(&c)+ && !(c == '\'' && j > 0 && chars[j - 1].is_alphanumeric())+ };+ if opens {+ quote = Some(c);+ }+ } else if braces == 0 && c == '>' {+ in_tag = false;+ if j > 0 && chars[j - 1] == '/' {+ depth -= 1;+ }+ }+ } else if c == '<' {+ let rest = &chars[j + 1..];+ if rest.first() == Some(&'/') && rest[1..].starts_with(&name) {+ let after = &rest[1 + name.len()..];+ match after.iter().find(|c| !is_js_whitespace(**c)) {+ Some('>') => depth -= 1,+ None => pending_close = true,+ _ => {}+ }+ } else if rest.starts_with(&name) {+ // JS: `(?=[\s/>]|$)`, so `<legend` does not match `<legendary`.+ let k = name.len();+ if k >= rest.len()+ || is_js_whitespace(rest[k])+ || rest[k] == '/'+ || rest[k] == '>'+ {+ depth += 1;+ in_tag = true;+ }+ }}}- let self_closes = count_matches(&self_close_re, line);- let closes = count_matches(&close_re, line);- depth += opens as i64 - self_closes as i64 - closes as i64;if depth <= 0 {- return i;+ return Some(i);}}- (start + 50).min(lines.len().saturating_sub(1))+ None}/// JS: detectCommentSyntax(filePath) → (open, close)@@ -423,4 +488,41 @@ mod tests {let other = lines(&[r#"<Label id="email" />"#]);assert_eq!(find_opener_line(&other, 0, Some("input")), None);}++ #[test]+ fn closing_line_is_the_elements_own_end() {+ let cases = [+ // Self-closing over several lines (#852).+ ("<legend\n className={cn(\"a\", className)}\n {...props}\n/>\n);\n}\n", Some(3)),+ // `>` inside a prop expression, then inside a quoted value.+ ("<input onChange={(e) => set(e.target.value)} />\n<p>a</p>\n<p>b</p>\n", Some(0)),+ ("<input className=\"[&>svg]:size-4\" />\n<p>a</p>\n<p>b</p>\n", Some(0)),+ // An apostrophe inside a prop expression is not a quote, a string is.+ ("<button onClick={() => {\n // don't resubmit\n go();\n}}>\n Go\n</button>\n<p>a</p>\n", Some(5)),+ ("<Field label={\"{\"} />\n<p>a</p>\n<p>b</p>\n", Some(0)),+ ("<Field sql={`\n a {\n`} />\n<p>a</p>\n<p>b</p>\n", Some(2)),+ ("<Field title={`a\\`b`} />\n<p>a</p>\n<p>b</p>\n", Some(0)),+ // Nested same-name tags, and a sibling opened on the closing line.+ ("<section>\n <section>\n x\n </section>\n</section>\n<p>a</p>\n", Some(4)),+ ("<a>x</a> and <a>y\nz</a>\n<p>a</p>\n", Some(1)),+ // A closing tag split before its `>`.+ ("<section>\n x\n</section\n>\n<p>a</p>\n", Some(3)),+ // Never closed: no end line rather than a guessed one.+ ("<img class=\"hero\">\n<p>a</p>\n<p>b</p>\n", None),+ ];+ for (src, end) in cases {+ let lines: Vec<String> = src.lines().map(String::from).collect();+ assert_eq!(find_closing_line(&lines, 0), end, "{src}");+ }+ }++ #[test]+ fn text_filter_reads_an_unclosed_elements_text_past_its_children() {+ let src = "<div class=\"n\">Earlier card</div>\n<div class=\"n\">\n <div class=\"n\">Nested card</div>\n Parent trailing text\n<p>after</p>\n";+ let lines: Vec<String> = src.lines().map(String::from).collect();+ let candidates = find_all_elements(&lines, "class=\"n\"", Some("div"));+ let picked = filter_by_text(&candidates, &lines, "Parent trailing text");+ assert_eq!(picked.len(), 1);+ assert_eq!((picked[0].start_line, picked[0].end_line), (1, None));+ }}diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.mdindex a7496732b..205368765 100644--- a/docs/CLI-CONTRACT.md+++ b/docs/CLI-CONTRACT.md@@ -1660,7 +1660,7 @@ Param kinds: `range` `{id,kind:'range',min,max,step,default,label}` → CSS varSource search (`live/source-search.mjs`): dirs in order `src, app, pages, components, public, views, templates, lib, .`; skip `node_modules, .git, .impeccable` (accept also skips `dist, build`); depth ≤5; realpath cycle guard; files before dirs; extensions = `LIVE_TEMPLATE_EXTENSIONS` (`.html,.jsx,.tsx,.vue,.svelte,.astro,.ex,.heex,.eex`) + `.impeccable/config.json`/`config.local.json` `detector.extensions`; suffix match. Wrap additionally rejects generated files (`isGeneratedFile`: `git check-ignore --quiet` exit 0 **[spawns git]** or first 300 bytes match `/@generated\b/i`, `/\bGENERATED\s+FILE\b/`, `/\bAUTO-?GENERATED\b/i`, `/\bDO\s+NOT\s+EDIT\b/i`).-Search queries built from flags in order: `id="<id>"`; if multiple classes: `class="<joined>"`, `className="<joined>"`, then each class longest-first; single class: the class; `<tag class="<first>` and `<tag className="<first>` when tag+classes; raw `--query`. Element location: first line containing query (skipping lines starting with `<!--`,`{/*`,`//` or containing `data-impeccable-variant`), resolve opener (`/<([A-Za-z][A-Za-z0-9]*)(?=[\s/>]|$)/` on the line, else walk back ≤10 lines; a differently-named opener aborts; the opener name is compared to `--tag` ignoring ASCII case, so `--tag input` matches an `<Input>` component), closer by depth counting (`<tag`, `<tag …/>`, `</tag>`), fallback `min(start+50, last)`. With `--text` (≥8 normalized chars): all candidates, filter by text (spaced or compact normalization of tag/JSX-stripped body).+Search queries built from flags in order: `id="<id>"`; if multiple classes: `class="<joined>"`, `className="<joined>"`, then each class longest-first; single class: the class; `<tag class="<first>` and `<tag className="<first>` when tag+classes; raw `--query`. Element location: first line containing query (skipping lines starting with `<!--`,`{/*`,`//` or containing `data-impeccable-variant`), resolve opener (`/<([A-Za-z][A-Za-z0-9]*)(?=[\s/>]|$)/` on the line, else walk back ≤10 lines; a differently-named opener aborts; the opener name is compared to `--tag` ignoring ASCII case, so `--tag input` matches an `<Input>` component), closer by same-name depth counting (`<tag`, `<tag …/>`, `</tag>`) over a character scan that follows each opening tag to its own `>` across lines, skipping quoted values and `{…}` expressions inside it (inside `{…}` a backtick opens a template literal that may span lines; `"` or `'` counts as a string only when it closes on the same line and is not an apostrophe after a letter or digit; backslash escapes apply inside those strings; comments inside `{…}` are not lexed, so a quote or backtick in one is read as a delimiter); a `</tag` whose `>` starts the next line closes there; depth is tested at end of line. No fallback: an element that never closes has no end line, so wrap, insert `after`, and insert at either position on the Svelte component path exit 1 with `element_unclosed`; insert `before` proceeds from the start line, and `candidates[].endLine` is `null`. With `--text` (≥8 normalized chars): all candidates, filter by text (spaced or compact normalization of tag/JSX-stripped body; an unclosed candidate's body is `start..min(start+50, last)`, used for matching only).#### 8. Svelte component preview (`live/svelte-component.mjs`, `live/svelte-ast.mjs`)@@ -1801,13 +1801,13 @@ Conventions: every script's "run directly" guard is `process.argv[1]` ending wit#### `live-wrap.mjs` -> `impeccable wrap`- Invoked from live.md Handle generate step 2 and preflight (`--defer-source-write`).- Args: `--id ID` (req), `--count N` (default 3), `--element-id`, `--classes "a,b"` (comma or space separated), `--tag`, `--query`, `--file PATH`, `--text`, `--page-url URL`, `--defer-source-write`, `--target`, `--help`. Both `--flag value` and `--flag=value` forms accepted. Missing id → `Missing --id` exit 1; none of id/classes/query → `Need at least one of: --element-id, --classes, --query` exit 1.-- stderr JSON errors, exit 1: `{error:'element_not_in_source', fallback:'agent-driven', generatedMatch:rel, hint}`, `{error:'element_not_found', fallback:'agent-driven', hint}`, `{error:'file_is_generated', fallback:'agent-driven', file, hint}`, `{error:'Found file but could not locate element in <abs>. Searched for: q1, q2'}`, `{error:'element_ambiguous', fallback:'agent-driven', reason?:'rendered_text_not_in_source', file, candidates:[{startLine,endLine}], hint}`, `{error:'missing_page_url_with_pending_edits', pendingEntries:N, hint}`, `{error:'manual_edit_buffer_apply_failed', pendingOps:[{entryId,ref,originalText,reason:'ambiguous_or_unmatched_pending_edit'}], hint}`.+- stderr JSON errors, exit 1: `{error:'element_not_in_source', fallback:'agent-driven', generatedMatch:rel, hint}`, `{error:'element_not_found', fallback:'agent-driven', hint}`, `{error:'file_is_generated', fallback:'agent-driven', file, hint}`, `{error:'Found file but could not locate element in <abs>. Searched for: q1, q2'}`, `{error:'element_ambiguous', fallback:'agent-driven', reason?:'rendered_text_not_in_source', file, candidates:[{startLine,endLine}], hint}`, `{error:'element_unclosed', fallback:'agent-driven', file, startLine, hint}` (opener found, no end line), `{error:'missing_page_url_with_pending_edits', pendingEntries:N, hint}`, `{error:'manual_edit_buffer_apply_failed', pendingOps:[{entryId,ref,originalText,reason:'ambiguous_or_unmatched_pending_edit'}], hint}`.- With `--page-url`, buffered manual edits for that page whose text sits in the picked range are applied to the wrapper's "original" copy (source untouched).- stdout success JSON: `{file, sourceFile?, previewMode?:'svelte-component', previewFallback?:{from:'svelte-component', reason}, sourceWritten?:false, wrapperBlock?, replaceStartLine?, replaceEndLine?, componentDir?, propContract?, componentStubMarkup?, sourceStartLine?, sourceEndLine?, startLine, endLine, insertLine, commentSyntax:{open,close}, styleMode:'scoped'|'astro-global-prefixed'|'svelte-component', styleTag:string|null, cssSelectorPrefixExamples:[], cssAuthoring:{…}, originalLineCount}`. Non-deferred, non-svelte: writes the wrapper into the file. Svelte: `file` = manifest path, `startLine=endLine=insertLine=1`.- Tests: `tests/live-wrap.test.mjs`, `tests/live-wrap-buffer-aware.test.mjs`, `tests/live-source-search.test.mjs`, `tests/framework-fixtures.test.mjs` (wrapCases), `tests/live-svelte-ast.test.mjs`.#### `live-insert.mjs` -> `impeccable insert`-- Args as wrap plus `--position before|after` (required: `Missing --position (before | after)`, `Invalid --position: X`); no `--page-url`. Errors like wrap (`element_not_in_source`/`element_not_found` with `hint:'See "Handle fallback" in live.md.'`, `file_is_generated`, `element_ambiguous` without hint).+- Args as wrap plus `--position before|after` (required: `Missing --position (before | after)`, `Invalid --position: X`); no `--page-url`. Errors like wrap (`element_not_in_source`/`element_not_found` with `hint:'See "Handle fallback" in live.md.'`, `file_is_generated`, `element_ambiguous` without hint, `element_unclosed` as wrap).- Output: `{mode:'insert', position, file, sourceWritten?:false, wrapperBlock?, replaceStartLine?, replaceEndLine? (= replaceStartLine-1), insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring}`; svelte: `{mode:'insert', position, file:<manifest>, sourceFile, previewMode:'svelte-component', componentDir, propContract:[], insertLine:1, sourceInsertLine, anchorStartLine, anchorEndLine, commentSyntax, styleMode:'svelte-component', styleTag:null, cssSelectorPrefixExamples:[], cssAuthoring}`.- Tests: `tests/live-insert.test.mjs`, `tests/live-insert-ui.test.mjs`, `tests/live-e2e/agent-insert.test.mjs`, e2e insert fixtures.diff --git a/tests/oracle/cases/live-wrap.mjs b/tests/oracle/cases/live-wrap.mjsindex 136553a3b..a8515c1b3 100644--- a/tests/oracle/cases/live-wrap.mjs+++ b/tests/oracle/cases/live-wrap.mjs@@ -9,6 +9,24 @@ const F = LIVE_FILES;const W = (id, workspace, args, extra = {}) => ({ id, verb: 'live-wrap', workspace, args, files: [...F, ...(extra.snap || [])], ...extra });const I = (id, workspace, args, extra = {}) => ({ id, verb: 'live-insert', workspace, args, files: [...F, ...(extra.snap || [])], ...extra });const buffered = (ws, ops, pageUrl = '/') => writeBuffer(ws, [{ id: 'e1', pageUrl, element: { tagName: 'p' }, ops, stagedAt: '2026-08-01T00:00:00.000Z' }]);+// Two components in one file; the first returns a multi-line self-closing tag.+const FIELD_TSX = `export function FieldLegend(props) {+ return (+ <legend+ className="field-legend"+ {...props}+ />+ );+}++export function FieldGroup({ children }) {+ return <div className="field-group">{children}</div>;+}+`;+// An img that never closes, then a twin that does: the first stays the match.+const UNCLOSED = {+ snap: ['src/**'], setup: (ws) => write(ws, 'src/void.html', '<main>\n <img class="void-hero" src="/a.png">\n <img class="void-hero" src="/b.png" />\n</main>\n'),+};export default [// --- argument / usage paths ---@@ -20,6 +38,7 @@ export default [W('live-wrap-element-not-in-source', 'live-html', ['--id', 'ab12cd34', '--classes', 'built-title']),W('live-wrap-file-is-generated', 'live-html', ['--id', 'ab12cd34', '--classes', 'built-title', '--file', 'dist/generated.html']),W('live-wrap-file-element-missing', 'live-html', ['--id', 'ab12cd34', '--classes', 'hero-title', '--file', 'src/cards.html']),+ W('live-wrap-file-element-unclosed', 'live-html', ['--id', 'ab12cd34', '--classes', 'void-hero', '--tag', 'img', '--file', 'src/void.html'], UNCLOSED),// --- HTML replace wrappers ---W('live-wrap-html-by-id', 'live-html', ['--id', 'ab12cd34', '--count', '3', '--element-id', 'hero'], { snap: ['index.html'] }),W('live-wrap-html-by-classes-tag', 'live-html', ['--id', 'ab12cd34', '--classes', 'hero-title', '--tag', 'h1'], { snap: ['index.html'] }),@@ -40,6 +59,9 @@ export default [W('live-wrap-jsx-deferred', 'live-vite', ['--id', 'ab12cd34', '--classes', 'hero-title', '--tag', 'h1', '--defer-source-write'], { snap: ['src/**'] }),W('live-wrap-jsx-mapped-item', 'live-vite', ['--id', 'ab12cd34', '--classes', 'item-row', '--tag', 'li', '--text', 'First'], { snap: ['src/**'] }),W('live-wrap-tsx-multiline', 'live-vite', ['--id', 'ab12cd34', '--classes', 'panel', '--tag', 'section'], { snap: ['src/**'] }),+ W('live-wrap-tsx-multiline-self-closing', 'live-vite', ['--id', 'ab12cd34', '--classes', 'field-legend', '--tag', 'legend'], {+ snap: ['src/**'], setup: (ws) => write(ws, 'src/Field.tsx', FIELD_TSX),+ }),W('live-wrap-tsx-component-tag-case', 'live-vite', ['--id', 'ab12cd34', '--count', '1', '--element-id', 'password', '--tag', 'input', '--file', 'src/Login.tsx', '--defer-source-write'], {snap: ['src/Login.tsx'],setup: (ws) => write(ws, 'src/Login.tsx', 'export function Login() {\n return (\n <form>\n <Input id="password" type="password" required />\n </form>\n );\n}\n'),@@ -89,6 +111,8 @@ export default [I('live-insert-html-deferred', 'live-html', ['--id', 'ab12cd34', '--position', 'after', '--classes', 'side-note', '--tag', 'aside', '--defer-source-write'], { snap: ['index.html'] }),I('live-insert-html-text-ambiguous', 'live-html', ['--id', 'ab12cd34', '--position', 'after', '--classes', 'card-body', '--tag', 'p', '--text', 'card body copy', '--file', 'src/cards.html'], { snap: ['src/**'] }),I('live-insert-html-text-picks', 'live-html', ['--id', 'ab12cd34', '--position', 'before', '--classes', 'card', '--tag', 'div', '--text', 'Gamma card Third card body copy.', '--file', 'src/cards.html'], { snap: ['src/**'] }),+ I('live-insert-html-unclosed-before', 'live-html', ['--id', 'ab12cd34', '--position', 'before', '--classes', 'void-hero', '--tag', 'img', '--file', 'src/void.html'], UNCLOSED),+ I('live-insert-html-unclosed-after', 'live-html', ['--id', 'ab12cd34', '--position', 'after', '--classes', 'void-hero', '--tag', 'img', '--file', 'src/void.html'], UNCLOSED),I('live-insert-jsx-after', 'live-vite', ['--id', 'ab12cd34', '--position', 'after', '--element-id', 'features'], { snap: ['src/**'] }),I('live-insert-jsx-before-deferred', 'live-vite', ['--id', 'ab12cd34', '--position', 'before', '--classes', 'hero-title', '--tag', 'h1', '--defer-source-write'], { snap: ['src/**'] }),I('live-insert-astro-after', 'live-astro', ['--id', 'ab12cd34', '--position', 'after', '--element-id', 'features'], { snap: ['src/**'] }),diff --git a/tests/oracle/golden/live-insert-html-unclosed-after.json b/tests/oracle/golden/live-insert-html-unclosed-after.jsonnew file mode 100644index 000000000..d65984c11--- /dev/null+++ b/tests/oracle/golden/live-insert-html-unclosed-after.json@@ -0,0 +1,11 @@+{+ "stdout": "",+ "stderr": "{\"error\":\"element_unclosed\",\"fallback\":\"agent-driven\",\"file\":\"src/void.html\",\"startLine\":2,\"hint\":\"Found the element's opening tag at startLine but not where it closes. Find its end and write the scaffold manually. See \\\"Handle fallback\\\" in live.md.\"}\n",+ "exit": 1,+ "signal": null,+ "files": {+ ".impeccable/live/config.json": "{\n \"files\": [\"index.html\", \"public/**/*.html\"],\n \"insertBefore\": \"</body>\",\n \"commentSyntax\": \"html\"\n}\n",+ "src/cards.html": "<section class=\"cards\">\n <div class=\"card\">\n <h3 class=\"card-title\">Alpha card</h3>\n <p class=\"card-body\">First card body copy.</p>\n </div>\n <div class=\"card\">\n <h3 class=\"card-title\">Beta card</h3>\n <p class=\"card-body\">Second card body copy.</p>\n </div>\n <div class=\"card\">\n <h3 class=\"card-title\">Gamma card</h3>\n <p class=\"card-body\">Third card body copy.</p>\n </div>\n</section>\n",+ "src/void.html": "<main>\n <img class=\"void-hero\" src=\"/a.png\">\n <img class=\"void-hero\" src=\"/b.png\" />\n</main>\n"+ }+}diff --git a/tests/oracle/golden/live-insert-html-unclosed-before.json b/tests/oracle/golden/live-insert-html-unclosed-before.jsonnew file mode 100644index 000000000..6c0a93496--- /dev/null+++ b/tests/oracle/golden/live-insert-html-unclosed-before.json@@ -0,0 +1,11 @@+{+ "stdout": "{\"mode\":\"insert\",\"position\":\"before\",\"file\":\"src/void.html\",\"insertLine\":5,\"commentSyntax\":{\"open\":\"<!--\",\"close\":\"-->\"},\"styleMode\":\"scoped\",\"styleTag\":\"<style data-impeccable-css=\\\"SESSION_ID\\\">\",\"cssSelectorPrefixExamples\":[],\"cssAuthoring\":{\"mode\":\"scoped\",\"styleTag\":\"<style data-impeccable-css=\\\"SESSION_ID\\\">\",\"strategy\":\"scope-rule\",\"rulePattern\":\"@scope ([data-impeccable-variant=\\\"N\\\"]) { :scope > .variant-class { ... } }\",\"selectorExamples\":[\"@scope ([data-impeccable-variant=\\\"1\\\"]) { :scope > .variant-class { ... } }\",\"@scope ([data-impeccable-variant=\\\"2\\\"]) { :scope > .variant-class { ... } }\",\"@scope ([data-impeccable-variant=\\\"3\\\"]) { :scope > .variant-class { ... } }\"],\"requirements\":[\"Use @scope blocks keyed to each [data-impeccable-variant=\\\"N\\\"] wrapper.\",\"Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.\",\"Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.\"],\"forbidden\":[\"Do not use global [data-impeccable-variant=\\\"N\\\"] selector prefixes for this styleMode.\",\"Do not add is:inline to the style tag for this styleMode.\"]}}\n",+ "stderr": "",+ "exit": 0,+ "signal": null,+ "files": {+ ".impeccable/live/config.json": "{\n \"files\": [\"index.html\", \"public/**/*.html\"],\n \"insertBefore\": \"</body>\",\n \"commentSyntax\": \"html\"\n}\n",+ "src/cards.html": "<section class=\"cards\">\n <div class=\"card\">\n <h3 class=\"card-title\">Alpha card</h3>\n <p class=\"card-body\">First card body copy.</p>\n </div>\n <div class=\"card\">\n <h3 class=\"card-title\">Beta card</h3>\n <p class=\"card-body\">Second card body copy.</p>\n </div>\n <div class=\"card\">\n <h3 class=\"card-title\">Gamma card</h3>\n <p class=\"card-body\">Third card body copy.</p>\n </div>\n</section>\n",+ "src/void.html": "<main>\n <!-- impeccable-variants-start ab12cd34 -->\n <div data-impeccable-variants=\"ab12cd34\" data-impeccable-mode=\"insert\" data-impeccable-variant-count=\"3\" style=\"display: contents\">\n <!-- Variants: insert below this line -->\n </div>\n <!-- impeccable-variants-end ab12cd34 -->\n <img class=\"void-hero\" src=\"/a.png\">\n <img class=\"void-hero\" src=\"/b.png\" />\n</main>\n"+ }+}diff --git a/tests/oracle/golden/live-wrap-file-element-unclosed.json b/tests/oracle/golden/live-wrap-file-element-unclosed.jsonnew file mode 100644index 000000000..d65984c11--- /dev/null+++ b/tests/oracle/golden/live-wrap-file-element-unclosed.json@@ -0,0 +1,11 @@+{+ "stdout": "",+ "stderr": "{\"error\":\"element_unclosed\",\"fallback\":\"agent-driven\",\"file\":\"src/void.html\",\"startLine\":2,\"hint\":\"Found the element's opening tag at startLine but not where it closes. Find its end and write the scaffold manually. See \\\"Handle fallback\\\" in live.md.\"}\n",+ "exit": 1,+ "signal": null,+ "files": {+ ".impeccable/live/config.json": "{\n \"files\": [\"index.html\", \"public/**/*.html\"],\n \"insertBefore\": \"</body>\",\n \"commentSyntax\": \"html\"\n}\n",+ "src/cards.html": "<section class=\"cards\">\n <div class=\"card\">\n <h3 class=\"card-title\">Alpha card</h3>\n <p class=\"card-body\">First card body copy.</p>\n </div>\n <div class=\"card\">\n <h3 class=\"card-title\">Beta card</h3>\n <p class=\"card-body\">Second card body copy.</p>\n </div>\n <div class=\"card\">\n <h3 class=\"card-title\">Gamma card</h3>\n <p class=\"card-body\">Third card body copy.</p>\n </div>\n</section>\n",+ "src/void.html": "<main>\n <img class=\"void-hero\" src=\"/a.png\">\n <img class=\"void-hero\" src=\"/b.png\" />\n</main>\n"+ }+}diff --git a/tests/oracle/golden/live-wrap-tsx-multiline-self-closing.json b/tests/oracle/golden/live-wrap-tsx-multiline-self-closing.jsonnew file mode 100644index 000000000..5bae739b9--- /dev/null+++ b/tests/oracle/golden/live-wrap-tsx-multiline-self-closing.json@@ -0,0 +1,13 @@+{+ "stdout": "{\"file\":\"src/Field.tsx\",\"startLine\":3,\"endLine\":14,\"insertLine\":12,\"commentSyntax\":{\"open\":\"{/*\",\"close\":\"*/}\"},\"styleMode\":\"scoped\",\"styleTag\":\"<style data-impeccable-css=\\\"SESSION_ID\\\">\",\"cssSelectorPrefixExamples\":[],\"cssAuthoring\":{\"mode\":\"scoped\",\"styleTag\":\"<style data-impeccable-css=\\\"SESSION_ID\\\">\",\"strategy\":\"scope-rule\",\"rulePattern\":\"@scope ([data-impeccable-variant=\\\"N\\\"]) { :scope > .variant-class { ... } }\",\"selectorExamples\":[\"@scope ([data-impeccable-variant=\\\"1\\\"]) { :scope > .variant-class { ... } }\",\"@scope ([data-impeccable-variant=\\\"2\\\"]) { :scope > .variant-class { ... } }\",\"@scope ([data-impeccable-variant=\\\"3\\\"]) { :scope > .variant-class { ... } }\"],\"requirements\":[\"Use @scope blocks keyed to each [data-impeccable-variant=\\\"N\\\"] wrapper.\",\"Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.\",\"Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.\"],\"forbidden\":[\"Do not use global [data-impeccable-variant=\\\"N\\\"] selector prefixes for this styleMode.\",\"Do not add is:inline to the style tag for this styleMode.\"]},\"originalLineCount\":4}\n",+ "stderr": "",+ "exit": 0,+ "signal": null,+ "files": {+ ".impeccable/live/config.json": "{\n \"files\": [\"index.html\"],\n \"insertBefore\": \"</body>\",\n \"commentSyntax\": \"html\"\n}\n",+ "src/App.jsx": "export default function App() {\n return (\n <main className=\"page\">\n <h1 className=\"hero-title\">Vite Fixture</h1>\n <p className=\"hero-hook\">Minimal React tree for oracle live-mode goldens.</p>\n <section id=\"features\" className=\"feature-grid\">\n <article className=\"feature-card\">One</article>\n <article className=\"feature-card\">Two</article>\n </section>\n <ul className=\"item-list\">\n {items.map((item) => (\n <li key={item.id} className=\"item-row\">{item.title}</li>\n ))}\n </ul>\n </main>\n );\n}\n\nconst items = [\n { id: 1, title: 'First' },\n { id: 2, title: 'Second' },\n];\n",+ "src/Field.tsx": "export function FieldLegend(props) {\n return (\n <div data-impeccable-variants=\"ab12cd34\" data-impeccable-variant-count=\"3\" style={{ display: \"contents\" }}>\n {/* impeccable-variants-start ab12cd34 */}\n {/* Original */}\n <div data-impeccable-variant=\"original\">\n <legend\n className=\"field-legend\"\n {...props}\n />\n </div>\n {/* Variants: insert below this line */}\n {/* impeccable-variants-end ab12cd34 */}\n </div>\n );\n}\n\nexport function FieldGroup({ children }) {\n return <div className=\"field-group\">{children}</div>;\n}\n",+ "src/main.jsx": "import { createRoot } from 'react-dom/client';\nimport App from './App.jsx';\n\ncreateRoot(document.getElementById('root')).render(<App />);\n",+ "src/Panel.tsx": "type PanelProps = { title: string; children?: React.ReactNode };\n\nexport function Panel({ title, children }: PanelProps) {\n return (\n <section className=\"panel\">\n <header className=\"panel-header\">\n <h2 className=\"panel-title\">{title}</h2>\n </header>\n <div className=\"panel-body\">{children}</div>\n </section>\n );\n}\n"+ }+}