mirror of
https://github.com/pbakaus/impeccable.git
synced 2026-09-12 14:16:28 +03:00
* feat(live): manual text-edit panel + Astro inject + stale-lockfile reap Adds a manual text-edit popover under the live-mode bar so users can retype copy directly without going through generate. The footer's "Apply edits" button fires a manual_edits event; the server writes the changes back to source via the new live-edit.mjs deterministic file mutator. Mirrors the wrap+accept flow but skips variant generation. New scripts: - skill/scripts/live-edit.mjs: writes manual_edits back to source - skill/scripts/live-text-rows.js: browser walker that surfaces every pure-text descendant of the picked element as an editable row Touched scripts: - skill/scripts/live-browser.js: text panel UI, CONFIGURING state hook - skill/scripts/live-poll.mjs: manual_edits routing - skill/scripts/live-server.mjs: manual_edits endpoint + handler - skill/scripts/live-wrap.mjs: small adjustments to support the flow Docs + tests: - skill/reference/live.md: manual-edit section - tests/live-edit.test.mjs, tests/live-text-rows.test.mjs Also bundles two live-mode reliability fixes that surfaced during manual testing of the feature: 1. live-inject now emits is:inline when the inject target is a .astro file. Astro otherwise processes the <script> tag and rewrites src to its own bundled URL, so the literal live.js never loads. 2. readLiveServerInfo now probes the lockfile PID with kill(pid, 0) and unlinks the stale lock if dead. Previously a crashed helper left server.json with a dead PID and live-poll reported "Live server not running" forever. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(live): inline contenteditable text editing Replace the text-edit popover panel with inline contenteditable activation. When an element is picked in CONFIGURING, every pure-text descendant becomes contenteditable="true" directly on the page. Each blur-event fires a single-op manual_edits save to source. Esc restores original text and stays in CONFIGURING; successful save exits to PICKING. If Go is clicked while a save is in-flight, the save completes before generate fires. Deleted ~340 lines of panel UI (initTextPanel, openTextPanel, closeTextPanel, renderTextRow, buildTextFooter, etc.). Added enableInlineEdit, disableInlineEdit, onInlineBlur. Server contract unchanged; live-edit.mjs handles per-op saves as before. Tests: 186 pass. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(live): hide annotation overlay during inline edit Annotation overlay's click handler was intercepting clicks on contenteditable text elements. Hide the overlay when inline-edit is enabled to allow text selection and editing. Restore it when exiting inline-edit (if still in CONFIGURING). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(live): edit content badge mode with batched saves Replace automatic inline contenteditable on element pick with an explicit "Edit content" badge. The badge appears at the element's top-right corner when an element is picked. Clicking the badge enters a new EDITING state where: - The contextual bar hides - The annotation overlay hides - The badge morphs to show Cancel + Apply buttons - Text descendants become contenteditable inline Edits are held in memory (input event tracking) until Apply is clicked, which fires a single batched manual_edits event with all ops. Cancel discards drafts without saving. This eliminates the annotation overlay interference that prevented clicking on text elements. The EDITING state integrates with the main state machine and handles all exits (Esc, click-outside, teardown) cleanly. All 186 tests pass. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(live): use row.el.tagName for tag in applyEditing op The applyEditing function was trying to use row.tag which doesn't exist on the row object. The tag should be the tagName of the text element itself (row.el.tagName.toLowerCase()). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(live): Edit content badge styling + auto-focus + separate buttons - Edit content button now matches Go button styling (BP.accent background, BP.mark text, FONT, transitions, hover effects) - Auto-focus first editable element when entering editing mode (50ms timeout) - Separate Cancel and Apply buttons with 8px gap (no divider) - Cancel uses muted styling (BP.hairline background, BP.textDim text) - Apply keeps brand accent styling - Remove all focus rings and outlines on edit badge buttons (no blue ring/outline in EDITING mode) Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com> * feat(live): Subtle button UI + cursor positioning + better copy - Change badge buttons to use impeccable-button aesthetic (ink background, surface text, hover to accent) - Removes aggressive styling conflict with Go button - No animations; simple 150ms background transition - Matches site design language (padding 0.625rem 1.5rem, 0.8125rem font, letter-spacing 0.03em) - Shorter, clearer button copy: "Edit" instead of "Edit content", "Save" instead of "Apply" - Fix cursor positioning: cursor now appears at END of text, not beginning - Use Selection API to collapse cursor to end of contenteditable element - Improves UX for immediate continuation of text - Update live.md documentation to reflect new button labels Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com> * fix(live): Use site design system colors for edit badge buttons - Edit/Save buttons: oklch(10% 0 0) background → oklch(60% 0.25 350) on hover - Cancel button: oklch(55% 0 0) background → oklch(65% 0 0) on hover - All buttons: 6px border-radius (matches Go button), oklch(98% 0 0) text - Smooth transition: 0.3s cubic-bezier(0.16, 1, 0.3, 1) (--ease-out) - Uses site color palette instead of live-overlay constants Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com> * fix(live): Match slop-callout style for edit badge buttons - Use exact .slop-callout aesthetic: paper background, accent border + text, uppercase 10px (0.625rem) - 600 weight, 0.06em letter-spacing, 4px 8px padding, 6px border-radius - Box-shadow: 0 2px 8px rgba(0,0,0,0.1) matches site callouts - Hover: inverts to filled background (accent fill, paper text) - Cancel uses ash color variant for muted state, Save uses accent - Smooth 0.3s cubic-bezier(0.16, 1, 0.3, 1) transition on background and color Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(live): Pill-shaped edit badge buttons, 2px padding, no uppercase - Border-radius: 999px (pill shape) - Padding: 2px 8px (more compact) - Removed text-transform: uppercase Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(live): Cancel button uses mist border + ash text - Border: 1px solid oklch(92% 0 0) (--color-mist) - Color: oklch(55% 0 0) (--color-ash) - Hover: inverts to ash background with paper text Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(live): Remove blue focus outline from contenteditable elements in EDITING mode - Add inline outline: none on each row's element when contenteditable activates - Inject [data-impeccable-editable] CSS rule to override browser default focus ring - Use !important to win against site styles that re-apply focus outlines - Cleanup restores outline/data-attribute on disable Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(live): Decouple manual edits from agent/poll pipeline Manual text edits now POST directly to a new /manual-edit endpoint that runs live-edit.mjs synchronously and returns the result. The event is never enqueued, never reaches the poll loop, never reaches the agent. Why: every Save was costing an LLM turn. The poll script would dequeue the manual_edits event, run live-edit.mjs deterministically, post a completion ack, then print the event JSON to stdout. The Claude agent would read that output and decide "loop and re-poll". Zero real work for the agent but every Save burned context. Changes: - live-server.mjs: new POST /manual-edit handler that runs live-edit.mjs synchronously and returns the result. Does not enqueue, does not log to session store. Defense-in-depth: /events rejects manual_edits. - live-browser.js: applyEditing() POSTs to /manual-edit instead of sendEvent({type: 'manual_edits'}). - live-poll.mjs: removed manual_edits handler branch (dead code now). - reference/live.md: removed "Handle manual_edits" section; replaced with a one-line note that manual edits are server-direct. The HMR-triggered page reload remains (dev server detects source file change) but that is a separate dev-server behavior, not our pipeline. resumeSession() already restores variants and selection after reload. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(live): Stash manual edits server-side; commit via AI on request Decouples manual-edit Save from source file writes. Save now stashes to .impeccable/live/pending-manual-edits.json with no HMR refresh. The user explicitly asks the AI to commit when ready. Why: even with the prior /manual-edit fix, every Save still wrote to source and triggered the dev server's HMR/full reload. The page flash was the actual user pain. Now there's zero source touch on Save, and the user controls when the dev server reloads. Server (live-server.mjs): - /manual-edit-stash POST: append to buffer file. Returns {ok, pendingCount, totalCount, perPage}. - /manual-edit-stash GET: query counts by page for counter UI. - /manual-edit-discard POST: drop entries (all if no pageUrl). - Old /manual-edit returns 410 Gone (defense in depth). - Buffer ops merge by (pageUrl, ref): keep first originalText, update newText. CLIs: - live-commit-manual-edits.mjs: read buffer, shell out to live-edit.mjs per entry, truncate succeeded entries, surface failures. - live-discard-manual-edits.mjs: truncate buffer (optionally scoped by page). - Both take optional --page-url=<url>. Browser (live-browser.js): - applyEditing() POSTs to /manual-edit-stash, no source write. - Pending pill (• N staged) + trash icon next to Exit in global bar. - One-time onboarding toast on first Save: "Saved. Tell the AI to commit when ready." - Counter persists across reloads via GET /manual-edit-stash on init. - Trash icon: confirm dialog scoped to current page, then POST /manual-edit-discard. Variant pipeline interaction: - live-wrap.mjs: when wrapping an element, apply pending manual edits to the source range so the wrap block's "original" variant reflects the user's edited DOM (their pre-Go view), not the raw source. - live-accept.mjs: after accept writes the variant to source, scrub buffer ops whose originalText no longer appears in that file. The accept embodies the manual edit; the pending op is consumed. - Variant discard does NOT touch the buffer. Reference docs: - reference/live.md: full commit/discard contract, trigger guidance (narrow action-verb intent), do-not-auto-commit rule. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(live): Staged-edits pill becomes an "Apply" button Click the "• N staged" pill → confirm dialog "Apply N staged edits to source? The page will reload." → POST /manual-edit-commit on the server, which shells out to live-commit-manual-edits.mjs. Same path the AI uses, just triggered from the overlay. Trash icon stays for discard. The AI-driven commit path also stays (useful for inspecting failures or scripting). The pill is now the primary apply affordance because it removes the chat-context-switch for the common case. Pill styling: pointer cursor, accent border + text at rest, fills on hover (accent bg, paper text). Tooltip: "Click to apply staged edits to source". First-save toast updated: "Saved. Click the 'staged' badge to apply, or ask the AI." Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * chore(live): gitignore pending-manual-edits.json runtime buffer Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore: drop stray site/ test edits from PR Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(live): Pill label reads "Apply N staged" Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(live): Manual edit ops use the leaf element's locator, not parent's Multi-row inline editing captures each contenteditable leaf (row.el) but the op was being built with selectedElement.id / classList — i.e. the parent card, not the editable text node. live-edit.mjs then searched source for the parent's class on the leaf's tag (e.g. <span class= "foundation-card">), found nothing, and silently failed. Use row.el's own id / classList instead. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(live): Climb to nearest classed ancestor when leaf has no locator A bare <em>/<strong>/etc. with no id or class produced ops the CLI rejected with insufficient_locator. Prefer the leaf's own id/class; if neither exists, walk up to the nearest ancestor with one and adopt its tag + locator. Text-replace still works because the CLI narrows by originalText inside the matched element's source range. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(live): Make mixed-content paragraphs editable The text-rows walker skips elements with mixed children (text + element + text), so paragraphs like "Some text <code>x</code> more text" or "Body text · <a>link</a>" exposed zero rows for the surrounding copy. At edit time, wrap each non-whitespace direct text-node child in a marker span so the walker emits a row for it. Unwrap on save/cancel. The locator climbs to the parent's class as before, and live-edit narrows by originalText inside that parent's source range. hasTextRows now uses a lightweight subtree check that matches the new wrap+walk path so the edit affordance shows up on mixed-content elements. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(live): Address Cursor Bugbot findings (CB-2 through CB-6) CB-2 - Escape reverted DOM text but inlineEditDrafts retained the pre-revert value; clicking Apply afterwards committed the undone edit. Clear the draft entry when restoring innerText. CB-3 - The scrub gate !result.handled || result.handled !== false was a tautology that ran the scrub regardless of accept outcome. Use the intended result.handled !== false. CB-4 - The buffer-aware "original" content step in live-wrap iterated every entry in the buffer with no pageUrl filter, so an edit on /a could leak into a wrap call on /b. Add --page-url to the CLI; filter by it; skip the buffer-aware step entirely when omitted. live.md updated. CB-5 - removeEntries returned entry count while truncateBuffer returned op count, causing the discard CLI and HTTP endpoint to report mixed units. Make removeEntries return ops removed. CB-6 - applyTextReplace used string truthiness to gate prepending content above the edit, which silently dropped a leading empty line when the file started with '\n'. Gate on the line index instead, and mirror the fix on the trailing-empty-line side. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(live): A3+A4 data-integrity guards, A6 test coverage A3 — applyTextReplace refuses with text_ambiguous_in_block when originalText appears more than once in the matched element block. Refusing is safer than picking the first indexOf hit when we can't tell which leaf the user edited; user can rephrase one occurrence. A4 — newText is rejected if it contains <, >, {, }, or a backtick. Two layers: server-side validator in /manual-edit-stash returns 400, CLI-side guard in applyTextReplace returns invalid_chars_in_newText. Browser surfaces the specific reason via toast. The shared char list lives in live-edit.mjs (validateNewTextChars). reference/live.md documents the rule. A6 — New test files cover the orchestration gap: - live-manual-edits-buffer.test.mjs (17 tests across read/stage/ remove/find/count/truncate; pins removeEntries returns OPS count) - live-wrap-buffer-aware.test.mjs (3 tests; CB-4 regression test) - live-commit-manual-edits.test.mjs (4 tests; partial-failure, --page-url scope, no_pending_edits) - live-discard-manual-edits.test.mjs (3 tests; CB-5 unit consistency) - live-accept-scrub.test.mjs (4 tests; keep/drop/prune) Plus 2 new cases in live-edit.test.mjs for A3 and A4. Side-effect refactors: - scrubManualEditsAgainstFile accepts cwd for unit-testing and is exported. - Failed-op entries in live-edit.mjs now propagate forbidden and occurrences fields so callers can surface specifics. 41 tests across the 6 affected files pass; full suite green at 186/186. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore: drop .claude/pr-review.md from PR Local review notes belong in the working tree, not the PR diff. Kept in the file system; just untracked. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore: drop stray site/ test edits from PR (round 2) Live-inject script tag and the "Impeccable Works!" / "WHAT'S INCLUDED IN THE BOX" / "Wow Impeccable. ---- " strings were test edits that slipped back into the branch. Restore both files to match main. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(live): Disable Edit badge while variants are generating Clicking Edit during GENERATING would open inline text editing on the same DOM region the variant wrapper is about to land in, racing the HMR and the mutation observer. The badge now switches to an 'idle-disabled' rendering (ash + mist, not-allowed cursor, disabled attribute, tooltip) the moment state transitions into GENERATING. Returns to 'idle' on the normal CONFIGURING re-entry paths. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(live): live-wrap refuses without --page-url when buffer has pending edits When a manual edit is staged ("Impeccable Works!") but not yet committed, the buffer holds the user's edited DOM while source still has the un- edited text ("Impeccable"). live-wrap's buffer-aware step exists to rewrite the wrap block's <div data-impeccable-variant="original"> to match the staged DOM, but per CB-4 it is gated by --page-url. When the agent invoking live-wrap omits --page-url, the buffer-aware step silently no-op'd and the variant authoring saw stale source — the user's manual edit appeared lost. Make the silent no-op a loud error: when buffer.entries.length > 0 and --page-url is missing, exit 1 with { error: 'missing_page_url_with_pending_edits', pendingEntries, hint }. Empty buffer = no risk = no requirement, so existing flows without pending edits keep working. Updated reference/live.md to flag --page-url as required when the buffer has entries. Added regression test in live-wrap-buffer-aware.test.mjs. live-wrap.test.mjs gained a buffer- clear hook so any leftover .impeccable/live/pending-manual-edits.json from local dev doesn't trip the new check. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * change back * chore: drop stray site/ test edits from PR (round 3) Live-inject script tag in Base.astro slipped back in via git add -A while a local live server was running. Restore both site/ files to main. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * Fix live manual edit staging * Rename live edit copy badge * Use sentence case for live edit copy badge * Move copy edit apply control outside live bar * Improve live copy edit apply flow * Clean up live copy edit AI apply flow * Polish live copy edit docs and toast * Fix staged copy edit review issues * Fix CI jsdom dependency * Fix Cursor Bot live edit findings * Fix remaining live edit review issues * Fix Bugbot staged edit edge cases * Fix latest Bugbot live edit edges * Fix remaining Bugbot wrap and discard issues * Fix live copy edit safety contracts * Fix copy edit rollback coverage * Fix live manual copy edit apply flow * Adjust live pending dock offset * feat(live): route manual-edit Apply through the chat agent Make the staged copy-edit Apply work when no CLI AI runner is authenticated by routing the batch through the active chat session, and surface runner failures clearly instead of opaque exit codes. - live-poll: add --reply --data '<json>' so the chat agent can return a structured manual_edit_apply result (the documented flag was missing, so the server resolved with an empty object) - live-server: manual_edit_apply event + deferred map, chat-vs-subprocess dispatch in /manual-edit-commit, resolve the deferred from the ack - live-copy-edit-agent: chat provider, extractRunnerErrorMessage and commandAuthed pre-flight, diagnostic describeNoProviderError; drop the stale CLAUDE_CODE_SIMPLE and --no-session-persistence flags so headless CLAUDE_CODE_OAUTH_TOKEN auth works - live-browser: clear pendingApplyInFlight on commit_done and add a watchdog so a missed signal can no longer freeze element picking - reference/live.md: tight Handle manual_edit_apply handler plus a separate diagnostics reference section; advertise the event in the opening contract and dispatch table Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * Add live manual edit apply coverage * Fix manual edit apply review issues * Fix manual edit review follow-ups * Fix manual apply poll acknowledgements * Fix manual apply failed-entry rollback * Clarify manual apply LLM prompt * Fix stale manual apply discard events * Fix manual apply dynamic source edits * Fix large manual apply chunks * Clarify manual edit apply is first-class work * Clarify manual apply resume flow * Compact live manual apply evidence * Reject malformed manual apply replies * Recover legacy manual apply summaries * Fix Astro live script injection * Add live manual edit apply coverage * Slim live manual apply flow * Slim manual edit test dependencies * Stabilize real browser LLM smoke * Generalize manual edit LLM prompt examples * Remove retired live edit wrapper * Inline live text row walker * Slim manual edit prompts * Drop AGENTS doc churn * Stabilize live manual apply prompts * Stabilize manual apply visible Haiku flow * Add hard framework manual edit coverage * Stabilize manual edit LLM retries * Fix manual apply transaction rollback * Fix live shader text capture * Clean up manual apply runtime artifacts * Fix live manual edit apply reliability * Clean up manual apply coverage * Slim manual apply test cleanup * Fix manual edit prompt contract test * Align manual edit cancel hover * Fix live loading shader capture * Fix manual apply review findings * Restore live e2e tests for CI * Fix live loading shader halftone * Tune live loading shader dots * Restore main live shader behavior * Fix manual apply review findings * Fix manual apply bot follow-ups * Clarify manual apply rollback changes * Fix manual apply state naming * Address PR review cleanup * Fix manual apply review follow-ups * Fix multiline manual apply verification * Restore inline drafts when hiding live bar --------- Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
1531 lines
57 KiB
JavaScript
1531 lines
57 KiB
JavaScript
import { describe, it, beforeEach, afterEach } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import os from 'node:os';
|
|
import { execFileSync } from 'node:child_process';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { writeBuffer, readBuffer } from '../skill/scripts/live-manual-edits-buffer.mjs';
|
|
import { buildManualEditEvidence } from '../skill/scripts/live-manual-edit-evidence.mjs';
|
|
import { commitManualEdits } from '../skill/scripts/live-commit-manual-edits.mjs';
|
|
import {
|
|
buildCopyEditBatchPrompt,
|
|
runCopyEditPostApplyChecks,
|
|
} from '../skill/scripts/live-copy-edit-agent.mjs';
|
|
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
const REPO_ROOT = path.resolve(__dirname, '..');
|
|
const SCRIPT = path.join(REPO_ROOT, 'skill/scripts/live-commit-manual-edits.mjs');
|
|
const COMMIT_SOURCE = fs.readFileSync(SCRIPT, 'utf-8');
|
|
|
|
let tmpDir;
|
|
|
|
beforeEach(() => {
|
|
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'commit-test-'));
|
|
fs.mkdirSync(path.join(tmpDir, 'src'), { recursive: true });
|
|
});
|
|
|
|
afterEach(() => {
|
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
});
|
|
|
|
function entry({ id, pageUrl = '/', element = { tagName: 'h1' }, ops }) {
|
|
return {
|
|
id,
|
|
pageUrl,
|
|
element,
|
|
ops,
|
|
stagedAt: '2026-05-19T19:00:23.395Z',
|
|
};
|
|
}
|
|
|
|
function runCommit(extraArgs = [], env = {}) {
|
|
const stdout = execFileSync('node', [SCRIPT, ...extraArgs], {
|
|
encoding: 'utf-8',
|
|
cwd: tmpDir,
|
|
env: {
|
|
...process.env,
|
|
IMPECCABLE_LIVE_COPY_AGENT: 'mock',
|
|
...env,
|
|
},
|
|
});
|
|
return JSON.parse(stdout.trim());
|
|
}
|
|
|
|
describe('live-commit-manual-edits.mjs batched AI apply', () => {
|
|
it('accumulates warnings returned by repair attempts', () => {
|
|
assert.match(
|
|
COMMIT_SOURCE,
|
|
/currentWarnings = \[\.\.\.currentWarnings, \.\.\.\(repairResult\.warnings \|\| \[\]\)\]/,
|
|
'repair agent warnings should be merged into the final manual Apply result instead of being dropped',
|
|
);
|
|
});
|
|
|
|
it('batches staged edits and clears successful entries only after AI success', () => {
|
|
fs.writeFileSync(path.join(tmpDir, 'src', 'page.html'), '<h1 class="hero">Hello</h1>\n');
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({
|
|
id: 'e1',
|
|
ops: [{ ref: 'div>h1.1', tag: 'h1', classes: ['hero'], originalText: 'Welcome', newText: 'Hello' }],
|
|
}),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['e1'],
|
|
files: ['src/page.html'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.count, 1);
|
|
assert.equal(result.cleared, 1);
|
|
assert.equal(result.failed.length, 0);
|
|
assert.deepEqual(result.files, ['src/page.html']);
|
|
assert.equal(readBuffer(tmpDir).entries.length, 0);
|
|
assert.match(fs.readFileSync(path.join(tmpDir, 'src', 'page.html'), 'utf-8'), /Hello/);
|
|
});
|
|
|
|
it('keeps failed entries staged when the AI reports partial success', () => {
|
|
fs.writeFileSync(path.join(tmpDir, 'src', 'a.html'), '<h1>A new</h1>\n');
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({ id: 'a', pageUrl: '/a', ops: [{ ref: 'a', tag: 'h1', originalText: 'A original', newText: 'A new' }] }),
|
|
entry({ id: 'b', pageUrl: '/a', ops: [{ ref: 'b', tag: 'h1', originalText: 'B original', newText: 'B new' }] }),
|
|
entry({ id: 'c', pageUrl: '/a', ops: [{ ref: 'c', tag: 'h1', originalText: 'C original', newText: 'C new' }] }),
|
|
],
|
|
});
|
|
|
|
const result = runCommit(['--page-url=/a'], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'partial',
|
|
appliedEntryIds: ['a'],
|
|
failed: [{ entryId: 'b', reason: 'ambiguous duplicate card text' }],
|
|
files: ['src/a.html'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 1);
|
|
assert.equal(result.applied.length, 1);
|
|
assert.equal(result.failed.length, 2);
|
|
assert.deepEqual(result.failed.map((item) => [item.id, item.reason]), [
|
|
['c', 'not_reported_applied'],
|
|
['b', 'ambiguous duplicate card text'],
|
|
]);
|
|
assert.equal(readBuffer(tmpDir).entries.map((item) => item.id).join(','), 'b,c');
|
|
});
|
|
|
|
it('rolls back when a failed multi-op entry leaves one op in source', () => {
|
|
const file = path.join(tmpDir, 'src', 'page.html');
|
|
const before = [
|
|
'<h1 class="hero">Old title</h1>',
|
|
'<p class="tagline">Original tagline</p>',
|
|
'<p class="hero-hook">Original hook</p>',
|
|
'',
|
|
].join('\n');
|
|
fs.writeFileSync(file, before);
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({
|
|
id: 'title',
|
|
ops: [{
|
|
ref: 'body>h1.hero',
|
|
tag: 'h1',
|
|
classes: ['hero'],
|
|
originalText: 'Old title',
|
|
newText: 'New title',
|
|
sourceHint: { file: 'src/page.html', line: 1, column: 1 },
|
|
}],
|
|
}),
|
|
entry({
|
|
id: 'combo',
|
|
ops: [
|
|
{
|
|
ref: 'body>p.tagline',
|
|
tag: 'p',
|
|
classes: ['tagline'],
|
|
originalText: 'Original tagline',
|
|
newText: 'New tagline from failed entry',
|
|
sourceHint: { file: 'src/page.html', line: 2, column: 1 },
|
|
},
|
|
{
|
|
ref: 'body>p.hero-hook',
|
|
tag: 'p',
|
|
classes: ['hero-hook'],
|
|
originalText: 'Original hook',
|
|
newText: 'New hook from failed entry',
|
|
sourceHint: { file: 'src/page.html', line: 3, column: 1 },
|
|
},
|
|
],
|
|
}),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_WRITES: JSON.stringify({
|
|
'src/page.html': [
|
|
'<h1 class="hero">New title</h1>',
|
|
'<p class="tagline">New tagline from failed entry</p>',
|
|
'<p class="hero-hook">Original hook</p>',
|
|
'',
|
|
].join('\n'),
|
|
}),
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'partial',
|
|
appliedEntryIds: ['title'],
|
|
failed: [{ entryId: 'combo', reason: 'hook source conflict' }],
|
|
files: ['src/page.html'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.equal(
|
|
result.failed.some((item) => item.id === 'combo' && item.reason === 'failed_entry_source_changed'),
|
|
true,
|
|
);
|
|
assert.equal(
|
|
result.failed.some((item) => item.id === 'title' && item.reason === 'rolled_back_due_to_failed_entry_source_changed'),
|
|
true,
|
|
);
|
|
assert.deepEqual(result.rolledBackFiles, ['src/page.html']);
|
|
assert.equal(fs.readFileSync(file, 'utf-8'), before);
|
|
assert.equal(readBuffer(tmpDir).entries.map((item) => item.id).join(','), 'title,combo');
|
|
});
|
|
|
|
it('rolls back when an omitted entry is changed in a reported file', () => {
|
|
const file = path.join(tmpDir, 'src', 'page.html');
|
|
const before = [
|
|
'<h1 class="hero">Old title</h1>',
|
|
'<span class="secondary-action">Learn more</span>',
|
|
'',
|
|
].join('\n');
|
|
fs.writeFileSync(file, before);
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({
|
|
id: 'title',
|
|
ops: [{
|
|
ref: 'body>h1.hero',
|
|
tag: 'h1',
|
|
classes: ['hero'],
|
|
originalText: 'Old title',
|
|
newText: 'New title',
|
|
sourceHint: { file: 'src/page.html', line: 1, column: 1 },
|
|
}],
|
|
}),
|
|
entry({
|
|
id: 'secondary',
|
|
ops: [{
|
|
ref: 'body>span.secondary-action',
|
|
tag: 'span',
|
|
classes: ['secondary-action'],
|
|
originalText: 'Learn more',
|
|
newText: 'Omitted secondary action',
|
|
sourceHint: { file: 'src/page.html', line: 2, column: 1 },
|
|
}],
|
|
}),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_WRITES: JSON.stringify({
|
|
'src/page.html': [
|
|
'<h1 class="hero">New title</h1>',
|
|
'<span class="secondary-action">Omitted secondary action</span>',
|
|
'',
|
|
].join('\n'),
|
|
}),
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['title'],
|
|
files: ['src/page.html'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.equal(
|
|
result.failed.some((item) => item.id === 'secondary' && item.reason === 'failed_entry_source_changed'),
|
|
true,
|
|
);
|
|
assert.equal(
|
|
result.failed.some((item) => item.id === 'title' && item.reason === 'rolled_back_due_to_failed_entry_source_changed'),
|
|
true,
|
|
);
|
|
assert.deepEqual(result.rolledBackFiles, ['src/page.html']);
|
|
assert.equal(fs.readFileSync(file, 'utf-8'), before);
|
|
assert.equal(readBuffer(tmpDir).entries.map((item) => item.id).join(','), 'title,secondary');
|
|
});
|
|
|
|
it('treats entries reported as both applied and failed as a malformed result', () => {
|
|
fs.writeFileSync(path.join(tmpDir, 'src', 'a.html'), '<h1>A new</h1>\n');
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({ id: 'a', ops: [{ ref: 'a', tag: 'h1', originalText: 'A original', newText: 'A new' }] }),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'partial',
|
|
appliedEntryIds: ['a'],
|
|
failed: [{ entryId: 'a', reason: 'ambiguous after edit' }],
|
|
files: ['src/a.html'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.equal(result.failed[0].reason, 'conflicting_apply_result');
|
|
assert.equal(readBuffer(tmpDir).entries.map((item) => item.id).join(','), 'a');
|
|
});
|
|
|
|
it('treats done without explicit appliedEntryIds as failed and keeps staged entries', () => {
|
|
fs.writeFileSync(path.join(tmpDir, 'src', 'page.html'), '<h1>Hello</h1>\n');
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({ id: 'e1', ops: [{ ref: 'a', tag: 'h1', originalText: 'Welcome', newText: 'Hello' }] }),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
files: ['src/page.html'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.equal(result.failed[0].reason, 'missing_applied_entry_ids');
|
|
assert.equal(readBuffer(tmpDir).entries.length, 1);
|
|
});
|
|
|
|
it('fails source verification when applied IDs are reported but newText is absent', () => {
|
|
fs.writeFileSync(path.join(tmpDir, 'src', 'page.html'), '<h1 class="hero">Welcome</h1>\n');
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({ id: 'e1', ops: [{ ref: 'a', tag: 'h1', classes: ['hero'], originalText: 'Welcome', newText: 'Hello' }] }),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['e1'],
|
|
files: ['src/page.html'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.equal(result.failed.length, 1);
|
|
assert.equal(result.failed[0].reason, 'source_verification_failed');
|
|
assert.equal(readBuffer(tmpDir).entries.length, 1);
|
|
});
|
|
|
|
it('does not verify success from newText appearing elsewhere in the same file', () => {
|
|
fs.writeFileSync(path.join(tmpDir, 'src', 'page.html'), '<h1 class="hero">Welcome</h1>\n<p>Hello</p>\n');
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({
|
|
id: 'e1',
|
|
ops: [{
|
|
ref: 'body>h1.hero',
|
|
tag: 'h1',
|
|
classes: ['hero'],
|
|
originalText: 'Welcome',
|
|
newText: 'Hello',
|
|
sourceHint: { file: 'src/page.html', line: 1, column: 1 },
|
|
}],
|
|
}),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['e1'],
|
|
files: ['src/page.html'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.equal(result.reason, 'manual_edit_repair_needs_decision');
|
|
assert.equal(result.failed[0].reason, 'source_verification_failed');
|
|
assert.equal(result.failed[0].checks[0].failures[0].detail, 'source_hint_still_contains_original_text');
|
|
assert.equal(readBuffer(tmpDir).entries.length, 1);
|
|
});
|
|
|
|
it('keeps source writes for repair when source verification fails', () => {
|
|
const file = path.join(tmpDir, 'src', 'page.html');
|
|
const before = '<h1 class="hero">Welcome</h1>\n<p>Elsewhere</p>\n';
|
|
fs.writeFileSync(file, before);
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({
|
|
id: 'e1',
|
|
ops: [{
|
|
ref: 'body>h1.hero',
|
|
tag: 'h1',
|
|
classes: ['hero'],
|
|
originalText: 'Welcome',
|
|
newText: 'Hello',
|
|
sourceHint: { file: 'src/page.html', line: 1, column: 1 },
|
|
}],
|
|
}),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_WRITES: JSON.stringify({
|
|
'src/page.html': '<h1 class="hero">Welcome</h1>\n<p>Hello</p>\n',
|
|
}),
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['e1'],
|
|
files: ['src/page.html'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.equal(result.reason, 'manual_edit_repair_needs_decision');
|
|
assert.equal(result.failed[0].reason, 'source_verification_failed');
|
|
assert.equal(result.rolledBackFiles, undefined);
|
|
assert.equal(fs.readFileSync(file, 'utf-8'), '<h1 class="hero">Welcome</h1>\n<p>Hello</p>\n');
|
|
assert.equal(readBuffer(tmpDir).entries.length, 1);
|
|
});
|
|
|
|
it('verifies copy inside a multi-line element when the source hint points to the opening tag', () => {
|
|
const file = path.join(tmpDir, 'site', 'pages', 'index.astro');
|
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
fs.writeFileSync(file, [
|
|
'<section>',
|
|
' <p class="hero-rebuild-body">',
|
|
' Fresh visual vocabulary for teams',
|
|
' working in production code.',
|
|
' </p>',
|
|
'</section>',
|
|
'',
|
|
].join('\n'));
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({
|
|
id: 'p1',
|
|
ops: [{
|
|
ref: 'body>p.hero-rebuild-body',
|
|
tag: 'p',
|
|
classes: ['hero-rebuild-body'],
|
|
originalText: 'Your AI ships generic frontend by default.',
|
|
newText: 'Fresh visual vocabulary for teams working in production code.',
|
|
sourceHint: { file: 'site/pages/index.astro', line: 2, column: 3 },
|
|
}],
|
|
}),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['p1'],
|
|
files: ['site/pages/index.astro'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 1);
|
|
assert.equal(result.applied.length, 1);
|
|
assert.equal(readBuffer(tmpDir).entries.length, 0);
|
|
});
|
|
|
|
it('deduplicates failed entries across repeated repair attempts', async () => {
|
|
const file = path.join(tmpDir, 'src', 'page.html');
|
|
fs.writeFileSync(file, '<h1 class="hero">Welcome</h1>\n');
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({
|
|
id: 'e1',
|
|
ops: [{
|
|
ref: 'body>h1.hero',
|
|
tag: 'h1',
|
|
classes: ['hero'],
|
|
originalText: 'Welcome',
|
|
newText: 'Hello',
|
|
sourceHint: { file: 'src/page.html', line: 1, column: 1 },
|
|
}],
|
|
}),
|
|
],
|
|
});
|
|
let calls = 0;
|
|
|
|
const result = await commitManualEdits({
|
|
cwd: tmpDir,
|
|
provider: 'chat',
|
|
env: { IMPECCABLE_LIVE_MANUAL_EDIT_REPAIR_ATTEMPTS: '2' },
|
|
applyBatchToSource: async (_batch, { repair } = {}) => {
|
|
calls += 1;
|
|
if (!repair) {
|
|
return {
|
|
status: 'done',
|
|
appliedEntryIds: ['e1'],
|
|
failed: [],
|
|
files: ['src/page.html'],
|
|
};
|
|
}
|
|
return {
|
|
status: 'partial',
|
|
appliedEntryIds: [],
|
|
failed: [{ entryId: 'e1', reason: 'still cannot verify source' }],
|
|
files: ['src/page.html'],
|
|
};
|
|
},
|
|
});
|
|
|
|
assert.equal(calls, 3);
|
|
assert.equal(result.reason, 'manual_edit_repair_needs_decision');
|
|
assert.deepEqual(result.failed.map((item) => item.id), ['e1']);
|
|
assert.equal(readBuffer(tmpDir).entries.length, 1);
|
|
});
|
|
|
|
it('does not roll back unrelated project changes made during Apply', () => {
|
|
const pageFile = path.join(tmpDir, 'src', 'page.html');
|
|
const notesFile = path.join(tmpDir, 'src', 'notes.html');
|
|
const beforePage = '<h1 class="hero">Welcome</h1>\n';
|
|
const beforeNotes = '<p>Do not touch</p>\n';
|
|
fs.writeFileSync(pageFile, beforePage);
|
|
fs.writeFileSync(notesFile, beforeNotes);
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({
|
|
id: 'e1',
|
|
ops: [{
|
|
ref: 'body>h1.hero',
|
|
tag: 'h1',
|
|
classes: ['hero'],
|
|
originalText: 'Welcome',
|
|
newText: 'Hello',
|
|
sourceHint: { file: 'src/page.html', line: 1, column: 1 },
|
|
}],
|
|
}),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_WRITES: JSON.stringify({
|
|
'src/page.html': '<h1 class="hero">Hello</h1>\n',
|
|
'src/notes.html': '<p>User changed this while Apply was running</p>\n',
|
|
}),
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['e1'],
|
|
files: ['src/page.html'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 1);
|
|
assert.equal(result.applied.length, 1);
|
|
assert.equal(result.failed.length, 0);
|
|
assert.equal(result.unreportedFiles, undefined);
|
|
assert.equal(fs.readFileSync(pageFile, 'utf-8'), '<h1 class="hero">Hello</h1>\n');
|
|
assert.equal(fs.readFileSync(notesFile, 'utf-8'), '<p>User changed this while Apply was running</p>\n');
|
|
assert.equal(readBuffer(tmpDir).entries.length, 0);
|
|
});
|
|
|
|
it('fails instead of clearing when Apply changes an unreported Apply-owned source file', () => {
|
|
const pageFile = path.join(tmpDir, 'src', 'page.html');
|
|
const notesFile = path.join(tmpDir, 'src', 'notes.html');
|
|
const beforePage = '<h1 class="hero">Welcome</h1>\n';
|
|
const beforeNotes = '<h1 class="hero">Welcome</h1>\n';
|
|
fs.writeFileSync(pageFile, beforePage);
|
|
fs.writeFileSync(notesFile, beforeNotes);
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({
|
|
id: 'e1',
|
|
ops: [{
|
|
ref: 'body>h1.hero:nth-of-type(1)',
|
|
tag: 'h1',
|
|
classes: ['hero'],
|
|
originalText: 'Welcome',
|
|
newText: 'Hello',
|
|
sourceHint: { file: 'src/notes.html', line: 1, column: 1 },
|
|
}],
|
|
}),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_WRITES: JSON.stringify({
|
|
'src/page.html': '<h1 class="hero">Hello</h1>\n',
|
|
'src/notes.html': '<h1 class="hero">Hello</h1>\n',
|
|
}),
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['e1'],
|
|
files: ['src/page.html'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.equal(result.failed[0].reason, 'unreported_source_changes');
|
|
assert.deepEqual(result.unreportedFiles, ['src/notes.html']);
|
|
assert.deepEqual(new Set(result.rolledBackFiles), new Set(['src/page.html', 'src/notes.html']));
|
|
assert.equal(fs.readFileSync(pageFile, 'utf-8'), beforePage);
|
|
assert.equal(fs.readFileSync(notesFile, 'utf-8'), beforeNotes);
|
|
assert.equal(readBuffer(tmpDir).entries.length, 1);
|
|
});
|
|
|
|
it('does not delete pre-existing reported files that were outside the rollback snapshot', () => {
|
|
const pageFile = path.join(tmpDir, 'src', 'page.html');
|
|
const extraFile = path.join(tmpDir, 'src', 'extra.html');
|
|
const beforePage = '<h1 class="hero">Welcome</h1>\n';
|
|
fs.writeFileSync(pageFile, beforePage);
|
|
fs.writeFileSync(extraFile, '<p>Existing file</p>\n');
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({
|
|
id: 'e1',
|
|
ops: [{
|
|
ref: 'body>h1.hero',
|
|
tag: 'h1',
|
|
classes: ['hero'],
|
|
originalText: 'Welcome',
|
|
newText: 'Hello',
|
|
sourceHint: { file: 'src/page.html', line: 1, column: 1 },
|
|
}],
|
|
}),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_WRITES: JSON.stringify({
|
|
'src/page.html': '<h1 class="hero">Hello</h1>\n',
|
|
'src/extra.html': '<p>Existing file changed outside snapshot</p>\n',
|
|
}),
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'error',
|
|
message: 'agent failed after editing',
|
|
files: ['src/page.html', 'src/extra.html'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.deepEqual(result.rolledBackFiles, ['src/page.html']);
|
|
assert.equal(fs.existsSync(extraFile), true);
|
|
assert.equal(fs.readFileSync(pageFile, 'utf-8'), beforePage);
|
|
assert.equal(fs.readFileSync(extraFile, 'utf-8'), '<p>Existing file changed outside snapshot</p>\n');
|
|
assert.equal(result.rollbackFailures.some((item) => item.file === 'src/extra.html' && item.reason === 'no_snapshot'), true);
|
|
assert.equal(readBuffer(tmpDir).entries.length, 1);
|
|
});
|
|
|
|
it('verifies against reported files before failing a stale source hint window', () => {
|
|
fs.mkdirSync(path.join(tmpDir, 'site/pages'), { recursive: true });
|
|
fs.writeFileSync(path.join(tmpDir, 'site/pages/index.astro'), '<h1 class="hero">Welcome</h1>\n');
|
|
fs.writeFileSync(path.join(tmpDir, 'src/page.html'), '<h1 class="hero">Hello</h1>\n');
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({
|
|
id: 'e1',
|
|
ops: [{
|
|
ref: 'body>h1.hero',
|
|
tag: 'h1',
|
|
classes: ['hero'],
|
|
originalText: 'Welcome',
|
|
newText: 'Hello',
|
|
sourceHint: { file: 'site/pages/index.astro', line: 1, column: 1 },
|
|
}],
|
|
}),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['e1'],
|
|
files: ['src/page.html'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 1);
|
|
assert.equal(result.applied.length, 1);
|
|
assert.equal(result.failed.length, 0);
|
|
assert.equal(readBuffer(tmpDir).entries.length, 0);
|
|
});
|
|
|
|
it('fails source verification for legacy empty newText entries instead of treating them as applied', () => {
|
|
fs.writeFileSync(path.join(tmpDir, 'src', 'page.html'), '<h1 class="hero">Welcome</h1>\n');
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({ id: 'empty', ops: [{ ref: 'a', tag: 'h1', classes: ['hero'], originalText: 'Welcome', newText: '' }] }),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['empty'],
|
|
files: ['src/page.html'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.equal(result.reason, 'manual_edit_repair_needs_decision');
|
|
assert.equal(result.failed.length, 1);
|
|
assert.equal(result.failed[0].reason, 'source_verification_failed');
|
|
assert.equal(result.failed[0].checks[0].failures[0].detail, 'originalText_still_present_in_plausible_source_location');
|
|
assert.equal(readBuffer(tmpDir).entries.length, 1);
|
|
});
|
|
|
|
it('verifies current hero edits against Astro source hints before clearing', () => {
|
|
fs.mkdirSync(path.join(tmpDir, 'site/pages'), { recursive: true });
|
|
const astroPath = path.join(tmpDir, 'site/pages/index.astro');
|
|
const originalHook = "Great design prompts require design vocabulary. Most people don't have it. Impeccable teaches your AI deep design knowledge and gives you 23 commands to steer the result.";
|
|
const writeAstro = ({ title, hook }) => {
|
|
const lines = Array.from({ length: 82 }, () => '');
|
|
lines[67] = ` <h1 class="hero-title-combined">${title}</h1>`;
|
|
lines[70] = ` <p class="hero-hook-text hero-hook-text--full">${hook}</p>`;
|
|
fs.writeFileSync(astroPath, lines.join('\n'));
|
|
};
|
|
|
|
writeAstro({ title: 'Impeccable', hook: originalHook });
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({
|
|
id: 'hero-title',
|
|
ops: [{
|
|
ref: 'body>section#hero>h1',
|
|
tag: 'h1',
|
|
classes: ['hero-title-combined'],
|
|
originalText: 'Impeccable',
|
|
newText: 'Impeccable Wow',
|
|
sourceHint: { file: 'site/pages/index.astro', line: 68, column: 39 },
|
|
}],
|
|
}),
|
|
entry({
|
|
id: 'hero-hook',
|
|
ops: [{
|
|
ref: 'body>section#hero>p:nth-of-type(2)',
|
|
tag: 'p',
|
|
classes: ['hero-hook-text', 'hero-hook-text--full'],
|
|
originalText: originalHook,
|
|
newText: 'YESSSSS',
|
|
sourceHint: { file: 'site/pages/index.astro', line: 71, column: 54 },
|
|
}],
|
|
}),
|
|
],
|
|
});
|
|
|
|
const failed = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['hero-title', 'hero-hook'],
|
|
files: ['site/pages/index.astro'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(failed.cleared, 0);
|
|
assert.equal(failed.applied.length, 0);
|
|
assert.equal(failed.failed.every((item) => item.reason === 'source_verification_failed'), true);
|
|
assert.equal(readBuffer(tmpDir).entries.length, 2);
|
|
|
|
writeAstro({ title: 'Impeccable Wow', hook: 'YESSSSS' });
|
|
const applied = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['hero-title', 'hero-hook'],
|
|
files: ['site/pages/index.astro'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(applied.cleared, 2);
|
|
assert.equal(applied.applied.length, 2);
|
|
assert.equal(applied.failed.length, 0);
|
|
assert.equal(readBuffer(tmpDir).entries.length, 0);
|
|
});
|
|
|
|
it('keeps all entries staged when the AI runner fails', () => {
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({ id: 'e1', ops: [{ ref: 'a', tag: 'h1', originalText: 'A', newText: 'B' }] }),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT: 'off',
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.equal(result.failed.length, 1);
|
|
assert.match(result.failed[0].reason, /No live copy-edit AI runner is available/);
|
|
assert.equal(readBuffer(tmpDir).entries.length, 1);
|
|
});
|
|
|
|
it('rolls back source writes when the AI runner throws after writing', () => {
|
|
const file = path.join(tmpDir, 'src', 'page.html');
|
|
const before = '<h1>Old</h1>\n';
|
|
fs.writeFileSync(file, before);
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({ id: 'e1', ops: [{ ref: 'a', tag: 'h1', originalText: 'Old', newText: 'New' }] }),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_WRITES: JSON.stringify({
|
|
'src/page.html': '<h1>New</h1>\n',
|
|
}),
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: '{not json',
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.match(result.failed[0].reason, /Invalid IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT JSON/);
|
|
assert.deepEqual(result.rolledBackFiles, ['src/page.html']);
|
|
assert.deepEqual(result.rollbackFailures, []);
|
|
assert.equal(fs.readFileSync(file, 'utf-8'), before);
|
|
assert.equal(readBuffer(tmpDir).entries.length, 1);
|
|
});
|
|
|
|
it('rolls back source writes when the AI reports an error', () => {
|
|
const file = path.join(tmpDir, 'src', 'page.html');
|
|
const before = '<h1>Old</h1>\n';
|
|
fs.writeFileSync(file, before);
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({ id: 'e1', ops: [{ ref: 'a', tag: 'h1', originalText: 'Old', newText: 'New' }] }),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_WRITES: JSON.stringify({
|
|
'src/page.html': '<h1>New</h1>\n',
|
|
}),
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'error',
|
|
message: 'could not apply safely',
|
|
failed: [{ entryId: 'e1', reason: 'ambiguous' }],
|
|
files: ['src/page.html'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.equal(result.failed[0].reason, 'ambiguous');
|
|
assert.deepEqual(result.rolledBackFiles, ['src/page.html']);
|
|
assert.deepEqual(result.rollbackFailures, []);
|
|
assert.equal(fs.readFileSync(file, 'utf-8'), before);
|
|
assert.equal(readBuffer(tmpDir).entries.length, 1);
|
|
});
|
|
|
|
it('marks every staged entry failed when the AI reports error without per-entry failures', () => {
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({ id: 'e1', ops: [{ ref: 'a', tag: 'h1', originalText: 'Old', newText: 'New' }] }),
|
|
entry({ id: 'e2', ops: [{ ref: 'b', tag: 'p', originalText: 'Before', newText: 'After' }] }),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'error',
|
|
message: 'could not apply safely',
|
|
files: [],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.deepEqual(result.failed.map((item) => [item.id, item.reason]), [
|
|
['e1', 'could not apply safely'],
|
|
['e2', 'could not apply safely'],
|
|
]);
|
|
assert.equal(readBuffer(tmpDir).entries.length, 2);
|
|
});
|
|
|
|
it('reports no_pending_edits when buffer is empty', () => {
|
|
const result = runCommit();
|
|
|
|
assert.equal(result.reason, 'no_pending_edits');
|
|
assert.equal(result.count, 0);
|
|
assert.equal(result.cleared, 0);
|
|
});
|
|
|
|
it('reports a corrupt pending buffer instead of treating it as empty', () => {
|
|
const bufferPath = path.join(tmpDir, '.impeccable', 'live', 'pending-manual-edits.json');
|
|
fs.mkdirSync(path.dirname(bufferPath), { recursive: true });
|
|
fs.writeFileSync(bufferPath, '{ not valid json');
|
|
|
|
const result = runCommit();
|
|
|
|
assert.equal(result.reason, 'manual_edit_buffer_invalid');
|
|
assert.match(result.message, /manual_edit_buffer_unreadable/);
|
|
assert.equal(result.cleared, 0);
|
|
});
|
|
|
|
it('passes repeated card and dynamic data evidence to the batch prompt path', () => {
|
|
fs.mkdirSync(path.join(tmpDir, 'site/scripts/components'), { recursive: true });
|
|
fs.writeFileSync(path.join(tmpDir, 'site/scripts/data.js'),
|
|
"export const skillFocusAreas = [{ area: 'Color & Contrast', detail: 'Accessibility, systems, theming' }, { area: 'Interaction', detail: 'States' }];\n" +
|
|
"export const dimensionGuidelineCounts = { 'Color & Contrast': 29, 'Interaction': 36 };\n"
|
|
);
|
|
fs.writeFileSync(path.join(tmpDir, 'site/scripts/components/foundation-animations.js'),
|
|
"export const foundationAnimations = { 'Color & Contrast': '<svg>color</svg>', 'Interaction': '<svg>interaction</svg>' };\n"
|
|
);
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({
|
|
id: 'cards',
|
|
element: {
|
|
tagName: 'div',
|
|
classes: ['foundation-card'],
|
|
textContent: 'Color & Contrast 29 Accessibility, systems, theming',
|
|
},
|
|
ops: [
|
|
{
|
|
ref: 'body>main>section#foundation>div.foundation-grid>div:nth-of-type(2)>span.foundation-card-label:nth-of-type(1)',
|
|
contextRef: 'body>main>section#foundation>div.foundation-grid>div:nth-of-type(2)',
|
|
tag: 'span',
|
|
classes: ['foundation-card-label'],
|
|
originalText: 'Color & Contrast',
|
|
newText: 'Color!!!',
|
|
sourceHint: { file: 'site/pages/index.astro', loc: '2:3', line: 2, column: 3 },
|
|
nearbyEditableTexts: [{ text: '29' }, { text: 'Accessibility, systems, theming' }],
|
|
},
|
|
{
|
|
ref: 'body>main>section#foundation>div.foundation-grid>div:nth-of-type(3)>span.foundation-card-label:nth-of-type(1)',
|
|
contextRef: 'body>main>section#foundation>div.foundation-grid>div:nth-of-type(3)',
|
|
tag: 'span',
|
|
classes: ['foundation-card-label'],
|
|
originalText: 'Interaction',
|
|
newText: 'Inter !!!',
|
|
nearbyEditableTexts: [{ text: '36' }, { text: 'States' }],
|
|
},
|
|
],
|
|
}),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'partial',
|
|
appliedEntryIds: [],
|
|
failed: [{ entryId: 'cards', reason: 'ambiguous reference check' }],
|
|
files: [],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.failed.length, 1);
|
|
const candidates = result.failed[0].candidates;
|
|
assert.equal(candidates.some((item) => item.file === 'site/scripts/data.js'), true);
|
|
assert.equal(candidates.some((item) => item.file === 'site/scripts/components/foundation-animations.js'), true);
|
|
assert.equal(readBuffer(tmpDir).entries.length, 1);
|
|
});
|
|
|
|
it('caps weak literal and locator evidence so manual Apply payloads stay compact', () => {
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, 'src', 'page.jsx'),
|
|
Array.from({ length: 30 }, (_, index) => `<span className="metric">${index % 2 === 0 ? '33' : '44'}</span>`).join('\n') + '\n',
|
|
);
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({
|
|
id: 'weak-number',
|
|
element: { tagName: 'span', classes: ['metric'], textContent: '33' },
|
|
ops: [{
|
|
ref: 'body>span.metric:nth-of-type(1)',
|
|
tag: 'span',
|
|
classes: ['metric'],
|
|
originalText: '33',
|
|
newText: '0033',
|
|
}],
|
|
}),
|
|
],
|
|
});
|
|
|
|
const evidence = buildManualEditEvidence({ cwd: tmpDir, pageUrl: '/' });
|
|
const candidate = evidence.candidates[0];
|
|
assert.ok(candidate.textMatches.length <= 4, 'short numeric text matches should be capped aggressively');
|
|
assert.ok(candidate.locatorMatches.length <= 4, 'broad locator matches should not dominate chat payloads');
|
|
});
|
|
|
|
it('verifies coupled label and count edits through same-entry dynamic data evidence', () => {
|
|
fs.mkdirSync(path.join(tmpDir, 'site/scripts/components'), { recursive: true });
|
|
fs.writeFileSync(path.join(tmpDir, 'site/scripts/data.js'),
|
|
"export const skillFocusAreas = [{ area: 'Responsive', detail: 'Fluid layouts, touch targets' }];\n" +
|
|
"export const dimensionGuidelineCounts = { 'Responsive': 23 };\n"
|
|
);
|
|
fs.writeFileSync(path.join(tmpDir, 'site/scripts/components/foundation-animations.js'),
|
|
"export const foundationAnimations = { 'Responsive': '<svg>responsive</svg>' };\n"
|
|
);
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({
|
|
id: 'card',
|
|
element: {
|
|
tagName: 'div',
|
|
classes: ['foundation-card'],
|
|
textContent: 'Responsive 23 Fluid layouts, touch targets',
|
|
},
|
|
ops: [
|
|
{
|
|
ref: 'body>main>section#foundation>div.foundation-grid>div:nth-of-type(4)>span.foundation-card-label:nth-of-type(1)',
|
|
contextRef: 'body>main>section#foundation>div.foundation-grid>div:nth-of-type(4)',
|
|
tag: 'span',
|
|
classes: ['foundation-card-label'],
|
|
originalText: 'Responsive',
|
|
newText: 'ResXXX',
|
|
nearbyEditableTexts: [{ text: '23' }, { text: 'Fluid layouts, touch targets' }],
|
|
},
|
|
{
|
|
ref: 'body>main>section#foundation>div.foundation-grid>div:nth-of-type(4)>span.foundation-card-count:nth-of-type(2)',
|
|
contextRef: 'body>main>section#foundation>div.foundation-grid>div:nth-of-type(4)',
|
|
tag: 'span',
|
|
classes: ['foundation-card-count'],
|
|
originalText: '23',
|
|
newText: '42',
|
|
nearbyEditableTexts: [{ text: 'Responsive' }, { text: 'Fluid layouts, touch targets' }],
|
|
},
|
|
],
|
|
}),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_WRITES: JSON.stringify({
|
|
'site/scripts/data.js':
|
|
"export const skillFocusAreas = [{ area: 'ResXXX', detail: 'Fluid layouts, touch targets' }];\n" +
|
|
"export const dimensionGuidelineCounts = { 'ResXXX': 42 };\n",
|
|
'site/scripts/components/foundation-animations.js':
|
|
"export const foundationAnimations = { 'ResXXX': '<svg>responsive</svg>' };\n",
|
|
}),
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['card'],
|
|
files: ['site/scripts/data.js', 'site/scripts/components/foundation-animations.js'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 2);
|
|
assert.equal(result.applied.length, 2);
|
|
assert.equal(result.failed.length, 0);
|
|
assert.deepEqual(result.rolledBackFiles, undefined);
|
|
assert.equal(readBuffer(tmpDir).entries.length, 0);
|
|
});
|
|
|
|
it('verifies standalone integer count edits from nearby dynamic data context', () => {
|
|
fs.mkdirSync(path.join(tmpDir, 'site/scripts'), { recursive: true });
|
|
const noisyCounts = Array.from({ length: 24 }, (_, index) => ` 'noise-${index}': 23,`).join('\n');
|
|
const before =
|
|
"export const unrelatedCounts = {\n" +
|
|
noisyCounts + "\n" +
|
|
"};\n" +
|
|
"export const skillFocusAreas = [{ area: 'Responsive', detail: 'Fluid layouts, touch targets' }];\n" +
|
|
"export const repeatedMentions = ['Responsive', 'Responsive', 'Responsive', 'Responsive'];\n" +
|
|
"export const dimensionGuidelineCounts = {\n" +
|
|
" 'Responsive': 23,\n" +
|
|
"};\n";
|
|
fs.writeFileSync(path.join(tmpDir, 'site/scripts/data.js'), before);
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({
|
|
id: 'count',
|
|
element: {
|
|
tagName: 'div',
|
|
classes: ['foundation-card'],
|
|
textContent: 'Responsive 23 Fluid layouts, touch targets',
|
|
},
|
|
ops: [
|
|
{
|
|
ref: 'body>main>section#foundation>div.foundation-grid>div:nth-of-type(4)>span.foundation-card-count:nth-of-type(2)',
|
|
contextRef: 'body>main>section#foundation>div.foundation-grid>div:nth-of-type(4)',
|
|
tag: 'span',
|
|
classes: ['foundation-card-count'],
|
|
originalText: '23',
|
|
newText: '47',
|
|
nearbyEditableTexts: [{ text: 'Responsive' }, { text: 'Fluid layouts, touch targets' }],
|
|
},
|
|
],
|
|
}),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_WRITES: JSON.stringify({
|
|
'site/scripts/data.js':
|
|
"export const unrelatedCounts = {\n" +
|
|
noisyCounts + "\n" +
|
|
"};\n" +
|
|
"export const skillFocusAreas = [{ area: 'Responsive', detail: 'Fluid layouts, touch targets' }];\n" +
|
|
"export const repeatedMentions = ['Responsive', 'Responsive', 'Responsive', 'Responsive'];\n" +
|
|
"export const dimensionGuidelineCounts = {\n" +
|
|
" 'Responsive': 47,\n" +
|
|
"};\n",
|
|
}),
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['count'],
|
|
files: ['site/scripts/data.js'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 1);
|
|
assert.equal(result.applied.length, 1);
|
|
assert.equal(result.failed.length, 0);
|
|
assert.equal(readBuffer(tmpDir).entries.length, 0);
|
|
});
|
|
|
|
it('allows non-numeric count display copy when integer source data stays typed', () => {
|
|
fs.writeFileSync(path.join(tmpDir, 'package.json'), JSON.stringify({
|
|
scripts: {
|
|
'impeccable:manual-edit-validate': 'node src/validate.mjs',
|
|
},
|
|
}, null, 2));
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, 'src', 'stats.mjs'),
|
|
"export const stats = { count: 7 };\n",
|
|
);
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, 'src', 'validate.mjs'),
|
|
[
|
|
"import { stats } from './stats.mjs';",
|
|
"if (!Number.isInteger(stats.count)) throw new Error('stats.count must stay integer');",
|
|
"if (stats.countLabel !== '7 seats') throw new Error('stats.countLabel must carry display copy');",
|
|
'',
|
|
].join('\n'),
|
|
);
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({
|
|
id: 'typed-count',
|
|
element: { tagName: 'span', classes: ['stat-count'], textContent: '7' },
|
|
ops: [{
|
|
ref: 'body>main>span.stat-count',
|
|
tag: 'span',
|
|
classes: ['stat-count'],
|
|
originalText: '7',
|
|
newText: '7 seats',
|
|
sourceHint: { file: 'src/stats.mjs', line: 1, column: 31 },
|
|
}],
|
|
}),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_WRITES: JSON.stringify({
|
|
'src/stats.mjs': "export const stats = { count: 7, countLabel: '7 seats' };\n",
|
|
}),
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['typed-count'],
|
|
files: ['src/stats.mjs'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 1);
|
|
assert.equal(result.applied.length, 1);
|
|
assert.equal(result.failed.length, 0);
|
|
assert.equal(fs.readFileSync(path.join(tmpDir, 'src', 'stats.mjs'), 'utf-8'), "export const stats = { count: 7, countLabel: '7 seats' };\n");
|
|
assert.equal(readBuffer(tmpDir).entries.length, 0);
|
|
});
|
|
|
|
it('keeps source for repair when Apply coerces an integer source model into display text that crashes validation', () => {
|
|
const statsFile = path.join(tmpDir, 'src', 'stats.mjs');
|
|
const before = "export const stats = { count: 7 };\n";
|
|
fs.writeFileSync(path.join(tmpDir, 'package.json'), JSON.stringify({
|
|
scripts: {
|
|
'impeccable:manual-edit-validate': 'node src/validate.mjs',
|
|
},
|
|
}, null, 2));
|
|
fs.writeFileSync(statsFile, before);
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, 'src', 'validate.mjs'),
|
|
[
|
|
"import { stats } from './stats.mjs';",
|
|
"if (!Number.isInteger(stats.count)) throw new Error('stats.count must stay integer');",
|
|
'',
|
|
].join('\n'),
|
|
);
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({
|
|
id: 'typed-count',
|
|
element: { tagName: 'span', classes: ['stat-count'], textContent: '7' },
|
|
ops: [{
|
|
ref: 'body>main>span.stat-count',
|
|
tag: 'span',
|
|
classes: ['stat-count'],
|
|
originalText: '7',
|
|
newText: '7 seats',
|
|
sourceHint: { file: 'src/stats.mjs', line: 1, column: 31 },
|
|
}],
|
|
}),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_WRITES: JSON.stringify({
|
|
'src/stats.mjs': "export const stats = { count: '7 seats' };\n",
|
|
}),
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['typed-count'],
|
|
files: ['src/stats.mjs'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.equal(result.reason, 'manual_edit_repair_needs_decision');
|
|
assert.equal(result.failed[0].reason, 'post_apply_validation_failed');
|
|
assert.equal(result.failed[0].checks.some((check) => check.reason === 'manual_edit_validation_failed'), true);
|
|
assert.match(result.failed[0].checks.find((check) => check.reason === 'manual_edit_validation_failed').message, /stats\.count must stay integer/);
|
|
assert.equal(result.rolledBackFiles, undefined);
|
|
assert.equal(fs.readFileSync(statsFile, 'utf-8'), "export const stats = { count: '7 seats' };\n");
|
|
assert.equal(readBuffer(tmpDir).entries.map((item) => item.id).join(','), 'typed-count');
|
|
});
|
|
|
|
it('fails validation and keeps staged entries when touched JS is invalid or markers remain', () => {
|
|
fs.writeFileSync(path.join(tmpDir, 'src', 'broken.js'), "const label = 'XX29';\nconst answer = ;\n// impeccable-carbonize-start\n");
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({ id: 'bad', ops: [{ ref: 'a', tag: 'span', originalText: '29', newText: 'XX29' }] }),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['bad'],
|
|
files: ['src/broken.js'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.equal(
|
|
result.failed.some((item) => item.reason === 'post_apply_validation_failed'),
|
|
true,
|
|
);
|
|
assert.equal(readBuffer(tmpDir).entries.length, 1);
|
|
});
|
|
|
|
it('keeps invalid touched JSON for repair before clearing staged edits', () => {
|
|
const file = path.join(tmpDir, 'src', 'data.json');
|
|
const before = '{"title":"Old"}\n';
|
|
fs.writeFileSync(file, before);
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({ id: 'json', ops: [{ ref: 'a', tag: 'span', originalText: 'Old', newText: 'New', sourceHint: { file: 'src/data.json', line: 1 } }] }),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_WRITES: JSON.stringify({
|
|
'src/data.json': '{"title":"New",}\n',
|
|
}),
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['json'],
|
|
files: ['src/data.json'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.equal(result.reason, 'manual_edit_repair_needs_decision');
|
|
assert.equal(result.failed[0].reason, 'post_apply_validation_failed');
|
|
assert.equal(result.failed[0].checks.some((check) => check.reason === 'invalid_json'), true);
|
|
assert.equal(result.rolledBackFiles, undefined);
|
|
assert.equal(fs.readFileSync(file, 'utf-8'), '{"title":"New",}\n');
|
|
assert.equal(readBuffer(tmpDir).entries.length, 1);
|
|
});
|
|
|
|
it('keeps invalid touched CJS for repair before clearing staged edits', () => {
|
|
const file = path.join(tmpDir, 'src', 'config.cjs');
|
|
const before = "module.exports = { title: 'Old' };\n";
|
|
fs.writeFileSync(file, before);
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({ id: 'cjs', ops: [{ ref: 'a', tag: 'span', originalText: 'Old', newText: 'New', sourceHint: { file: 'src/config.cjs', line: 1 } }] }),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_WRITES: JSON.stringify({
|
|
'src/config.cjs': "module.exports = { title: 'New', broken: };\n",
|
|
}),
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['cjs'],
|
|
files: ['src/config.cjs'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.equal(result.reason, 'manual_edit_repair_needs_decision');
|
|
assert.equal(result.failed[0].reason, 'post_apply_validation_failed');
|
|
assert.equal(result.failed[0].checks.some((check) => check.reason === 'invalid_js'), true);
|
|
assert.equal(result.rolledBackFiles, undefined);
|
|
assert.equal(fs.readFileSync(file, 'utf-8'), "module.exports = { title: 'New', broken: };\n");
|
|
assert.equal(readBuffer(tmpDir).entries.length, 1);
|
|
});
|
|
|
|
it('strips live edit runtime attributes from the copy-edit prompt context', () => {
|
|
const decoratedHtml = '<section><h1 class="hero" contenteditable="true" data-impeccable-editable="true" data-impeccable-original-text="Original" style="user-select: text; cursor: text; outline: none; -webkit-user-modify: read-write-plaintext-only;">Edited</h1></section>';
|
|
const prompt = buildCopyEditBatchPrompt({
|
|
pageUrl: '/',
|
|
entries: [
|
|
entry({
|
|
id: 'clean',
|
|
element: { tagName: 'section', outerHTML: decoratedHtml, textContent: 'Edited' },
|
|
ops: [{
|
|
entryId: 'clean',
|
|
ref: 'body>section>h1:nth-of-type(1)',
|
|
tag: 'h1',
|
|
originalText: 'Original',
|
|
newText: 'Edited',
|
|
leaf: { tagName: 'h1', outerHTML: decoratedHtml, textContent: 'Edited' },
|
|
container: { tagName: 'section', outerHTML: decoratedHtml, textContent: 'Edited' },
|
|
}],
|
|
}),
|
|
],
|
|
candidates: [],
|
|
}, { cwd: tmpDir });
|
|
|
|
assert.match(prompt, /replace only the target text node or source string literal/);
|
|
assert.match(prompt, /do not reformat surrounding markup, indentation, attributes, blank lines, or unrelated whitespace/);
|
|
assert.match(prompt, /Missing sourceHint is not a failure/);
|
|
assert.match(prompt, /objectKeyMatches/);
|
|
assert.match(prompt, /data object or mapped list item/);
|
|
const serializedBatch = prompt.split('Staged copy-edit batch:\n').pop();
|
|
assert.doesNotMatch(serializedBatch, /data-impeccable-original-text|data-impeccable-editable|contenteditable|-webkit-user-modify/);
|
|
assert.match(serializedBatch, /Edited/);
|
|
});
|
|
|
|
it('fails post-apply validation when live edit runtime attributes leak into source', () => {
|
|
fs.writeFileSync(path.join(tmpDir, 'src', 'page.astro'), '<h1 class="hero" data-impeccable-original-text="Original">Edited</h1>\n');
|
|
|
|
const checks = runCopyEditPostApplyChecks({ cwd: tmpDir, files: ['src/page.astro'] });
|
|
|
|
assert.equal(checks.ok, false);
|
|
assert.equal(checks.failures[0].reason, 'leftover_impeccable_marker');
|
|
assert.match(checks.failures[0].marker, /data-impeccable-original-text/);
|
|
});
|
|
|
|
it('keeps verified source edits staged when post-apply validation fails', () => {
|
|
fs.writeFileSync(path.join(tmpDir, 'src', 'broken.js'), "const label = 'XX29';\nconst answer = ;\n");
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({ id: 'bad', ops: [{ ref: 'a', tag: 'span', originalText: '29', newText: 'XX29' }] }),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['bad'],
|
|
files: ['src/broken.js'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.equal(result.failed[0].reason, 'post_apply_validation_failed');
|
|
assert.equal(readBuffer(tmpDir).entries.length, 1);
|
|
});
|
|
|
|
it('keeps touched source files when post-apply validation needs repair', () => {
|
|
const file = path.join(tmpDir, 'src', 'broken.js');
|
|
const before = "const label = 'Old';\n";
|
|
fs.writeFileSync(file, before);
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({ id: 'bad', ops: [{ ref: 'a', tag: 'span', originalText: 'Old', newText: 'New' }] }),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_WRITES: JSON.stringify({
|
|
'src/broken.js': "const label = 'New';\nconst answer = ;\n",
|
|
}),
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['bad'],
|
|
files: ['src/broken.js'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.equal(result.reason, 'manual_edit_repair_needs_decision');
|
|
assert.equal(result.failed[0].reason, 'post_apply_validation_failed');
|
|
assert.equal(result.rolledBackFiles, undefined);
|
|
assert.equal(fs.readFileSync(file, 'utf-8'), "const label = 'New';\nconst answer = ;\n");
|
|
assert.equal(readBuffer(tmpDir).entries.length, 1);
|
|
});
|
|
|
|
it('keeps source for repair when Apply leaks edit-mode contenteditable attributes into source', () => {
|
|
const file = path.join(tmpDir, 'src', 'App.jsx');
|
|
const before = 'export default function App() { return <h1 className="hero">Old</h1>; }\n';
|
|
fs.writeFileSync(file, before);
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({
|
|
id: 'edit-ui',
|
|
ops: [{ ref: 'body>h1.hero', tag: 'h1', classes: ['hero'], originalText: 'Old', newText: 'Old New' }],
|
|
}),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_WRITES: JSON.stringify({
|
|
'src/App.jsx': 'export default function App() { return <h1 className="hero" contenteditable="true" data-impeccable-editable="true" data-impeccable-original-text="Old">Old New</h1>; }\n',
|
|
}),
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['edit-ui'],
|
|
files: ['src/App.jsx'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.equal(result.reason, 'manual_edit_repair_needs_decision');
|
|
assert.equal(result.failed[0].reason, 'post_apply_validation_failed');
|
|
assert.equal(result.failed[0].checks.some((check) => /data-impeccable-(editable|original-text)/.test(check.marker)), true);
|
|
assert.equal(result.rolledBackFiles, undefined);
|
|
assert.match(fs.readFileSync(file, 'utf-8'), /contenteditable="true"/);
|
|
assert.equal(readBuffer(tmpDir).entries.map((item) => item.id).join(','), 'edit-ui');
|
|
});
|
|
|
|
it('keeps source for repair when Apply leaves carbonize or variant scaffolding in source', () => {
|
|
const file = path.join(tmpDir, 'src', 'page.html');
|
|
const before = '<h1 class="hero">Old</h1>\n';
|
|
fs.writeFileSync(file, before);
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({
|
|
id: 'variant-scaffold',
|
|
ops: [{ ref: 'body>h1.hero', tag: 'h1', classes: ['hero'], originalText: 'Old', newText: 'New' }],
|
|
}),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_WRITES: JSON.stringify({
|
|
'src/page.html': [
|
|
'<!-- impeccable-carbonize-start deadbeef -->',
|
|
'<div data-impeccable-variants="deadbeef" data-impeccable-variant-count="3">',
|
|
' <div data-impeccable-variant="original"><h1 class="hero">New</h1></div>',
|
|
'</div>',
|
|
'<!-- impeccable-carbonize-end deadbeef -->',
|
|
'',
|
|
].join('\n'),
|
|
}),
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['variant-scaffold'],
|
|
files: ['src/page.html'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.equal(result.reason, 'manual_edit_repair_needs_decision');
|
|
assert.equal(result.failed[0].reason, 'post_apply_validation_failed');
|
|
assert.equal(
|
|
result.failed[0].checks.some((check) => /impeccable-carbonize-start|data-impeccable-variant/.test(check.marker)),
|
|
true,
|
|
);
|
|
assert.equal(result.rolledBackFiles, undefined);
|
|
assert.match(fs.readFileSync(file, 'utf-8'), /impeccable-carbonize-start/);
|
|
assert.equal(readBuffer(tmpDir).entries.map((item) => item.id).join(','), 'variant-scaffold');
|
|
});
|
|
|
|
it('keeps the whole batch for repair when one applied edit leaves UI scaffolding behind', () => {
|
|
const pageFile = path.join(tmpDir, 'src', 'page.html');
|
|
const cardFile = path.join(tmpDir, 'src', 'card.html');
|
|
const beforePage = '<h1 class="hero">Old title</h1>\n';
|
|
const beforeCard = '<article class="card">Old card</article>\n';
|
|
fs.writeFileSync(pageFile, beforePage);
|
|
fs.writeFileSync(cardFile, beforeCard);
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({
|
|
id: 'title',
|
|
ops: [{ ref: 'body>h1.hero', tag: 'h1', classes: ['hero'], originalText: 'Old title', newText: 'New title' }],
|
|
}),
|
|
entry({
|
|
id: 'card',
|
|
ops: [{ ref: 'body>article.card', tag: 'article', classes: ['card'], originalText: 'Old card', newText: 'New card' }],
|
|
}),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_WRITES: JSON.stringify({
|
|
'src/page.html': '<h1 class="hero">New title</h1>\n',
|
|
'src/card.html': '<article class="card"><span data-impeccable-text-wrap="true">New card</span></article>\n',
|
|
}),
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['title', 'card'],
|
|
files: ['src/page.html', 'src/card.html'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.equal(result.reason, 'manual_edit_repair_needs_decision');
|
|
assert.deepEqual(result.failed.map((item) => item.reason), [
|
|
'post_apply_validation_failed',
|
|
'post_apply_validation_failed',
|
|
]);
|
|
assert.equal(result.failed[0].checks.some((check) => /data-impeccable-text-wrap/.test(check.marker)), true);
|
|
assert.equal(result.rolledBackFiles, undefined);
|
|
assert.equal(fs.readFileSync(pageFile, 'utf-8'), '<h1 class="hero">New title</h1>\n');
|
|
assert.match(fs.readFileSync(cardFile, 'utf-8'), /data-impeccable-text-wrap/);
|
|
assert.deepEqual(readBuffer(tmpDir).entries.map((item) => item.id), ['title', 'card']);
|
|
});
|
|
|
|
it('keeps newly created files for repair when post-apply validation fails', () => {
|
|
const pageFile = path.join(tmpDir, 'src', 'page.html');
|
|
const newFile = path.join(tmpDir, 'src', 'new-broken.js');
|
|
const before = '<h1 class="hero">Old</h1>\n';
|
|
fs.writeFileSync(pageFile, before);
|
|
writeBuffer(tmpDir, {
|
|
entries: [
|
|
entry({ id: 'e1', ops: [{ ref: 'a', tag: 'h1', classes: ['hero'], originalText: 'Old', newText: 'New' }] }),
|
|
],
|
|
});
|
|
|
|
const result = runCommit([], {
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_WRITES: JSON.stringify({
|
|
'src/page.html': '<h1 class="hero">New</h1>\n',
|
|
'src/new-broken.js': 'const answer = ;\n',
|
|
}),
|
|
IMPECCABLE_LIVE_COPY_AGENT_MOCK_RESULT: JSON.stringify({
|
|
status: 'done',
|
|
appliedEntryIds: ['e1'],
|
|
files: ['src/page.html', 'src/new-broken.js'],
|
|
}),
|
|
});
|
|
|
|
assert.equal(result.cleared, 0);
|
|
assert.equal(result.applied.length, 0);
|
|
assert.equal(result.reason, 'manual_edit_repair_needs_decision');
|
|
assert.equal(result.failed[0].reason, 'post_apply_validation_failed');
|
|
assert.equal(result.rolledBackFiles, undefined);
|
|
assert.equal(fs.readFileSync(pageFile, 'utf-8'), '<h1 class="hero">New</h1>\n');
|
|
assert.equal(fs.existsSync(newFile), true);
|
|
assert.equal(readBuffer(tmpDir).entries.length, 1);
|
|
});
|
|
});
|