@juangcarmona/lighthouse-sdlc 0.30.3 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -224,3 +224,36 @@ The [telemetry contract](telemetry.md) covers collection from first startup, nat
224
224
  ## Engineering practice evidence
225
225
 
226
226
  The [practice evidence contract](practice-evidence.md) defines versioned source observations and common cumulative levels. Measurement integrity, native execution, hosting enforcement and current certification remain separate checks.
227
+
228
+ ## Required visual capture coverage
229
+
230
+ New implementation admissions use visual request version 2. Before requesting visual work, the maintainer commits `.lighthouse/visual-evidence.json` with `schemaVersion: 1` and either `defaults` or `issues` keyed by issue number. Each selected plan has `server: {command, port}` and `required`, an independent list of one to six before/candidate captures. The port is 1024–65535; the server must listen on `0.0.0.0` in its isolated container. For example, an issue entry can contain:
231
+
232
+ ```json
233
+ {
234
+ "schemaVersion": 1,
235
+ "issues": {
236
+ "18": {
237
+ "server": {"command": ["node", "server.mjs", "--host", "0.0.0.0", "--port", "4173"], "port": 4173},
238
+ "required": [{
239
+ "id": "items-new-wide",
240
+ "kind": "candidate",
241
+ "view": "/items",
242
+ "route": "/items/",
243
+ "state": "Empty list",
244
+ "viewport": {"width": 1280, "height": 720},
245
+ "appearance": "light",
246
+ "themeSelector": "html",
247
+ "steps": [],
248
+ "assertions": [{"selector": "main", "text": "No items yet"}]
249
+ }]
250
+ }
251
+ }
252
+ }
253
+ ```
254
+
255
+ Each required identity includes all fields shown above. `appearance` is `light`, `dark`, `system-light` or `system-dark` and sets the browser's preferred color scheme. The required `themeSelector` identifies the product's Lighthouse-themed root; the trusted driver verifies its actual `data-lh-theme` is `light`, `dark` or `system` as declared. This initial route requires that existing UI appearance contract; a preferred browser color scheme alone is insufficient. Use bounded `click`, `select` or `fill` steps with a CSS `selector` and, for selection/input, `value`; assert the product's actual theme attribute or control state when relevant. Assertions require a visible selector and can additionally match an exact `attribute`/`value` or contained `text`. There are at most twelve steps and twelve assertions per capture. Routes stay on the isolated product origin. Declare a matching `before` item for an existing view; the host captures it from the admitted source, and the candidate declares `baseline: existing`. New views instead give a concrete `baselineReason`. Product-specific state and appearance choices remain product-owned.
256
+
257
+ The host ignores agent-supplied PNGs for version-2 implementation evidence and captures the actual source/candidate snapshots through separate credential-free server and Chromium containers on an internal network. The browser uses a trusted Node/Chromium driver without importing candidate dependencies. Source, styles, scripts, relevant configuration/assets, modes and planning files contribute to the capture-time identity; the publisher compares it against the assessed Git trees before writing. Only exact host-generated OpenSpec scaffold bytes at this issue's metadata path may be inert. Missing required identities, failed browser/state execution, stale inputs or unavailable protected-branch publication prevent complete visual evidence and retain the existing failure handoff/history.
258
+
259
+ This initial route supports tracked source runnable with the selected image. Ignored dependencies, generated builds, authentication, auxiliary services, remote fonts/assets and additional interaction actions are outside its capture surface. Their absence cannot be reported as a successful capture. Nonvisual implementations can still explain not-applicability when no required plan is admitted. A visual implementation without independently admitted requirements blocks until the maintainer configures them and requests a fresh execution. Read-only planning still uses isolated proposed examples. Earlier requests and receipts remain readable with their original agent-declared provenance. Source implementation, release, workflow adoption, native qualification, visual judgement and owner acceptance remain separate.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juangcarmona/lighthouse-sdlc",
3
- "version": "0.30.3",
3
+ "version": "0.31.0",
4
4
  "type": "module",
5
5
  "description": "Provider-neutral SDLC skills, commands and route contracts for Lighthouse adopters",
6
6
  "repository": {
@@ -39,6 +39,12 @@ Refinement defines the views and later capture/acceptance criteria. Proposal mak
39
39
 
40
40
  ## Implementation
41
41
 
42
+ For `request.visualEvidence.schemaVersion: 2`, inspect `request.visualEvidence.requirements` and `contract.visualCapture` first. The host admits those requirements from `.lighthouse/visual-evidence.json` at the source revision, independently of your returned item list. Return every required `id`, `kind`, `view`, `state`, `viewport` and `appearance` exactly. The host also verifies `data-lh-theme` on the admitted `themeSelector`; preference alone cannot prove the product's appearance. Before/candidate pairs use the same appearance as well as view/state/viewport. A candidate with an admitted before pair uses `baseline: existing`; a new view uses `baseline: new` and a reason. Do not remove required identities or replace them with a not-applicable assessment. If the required state cannot run, return unavailable with a blocked result and the maintainer action.
43
+
44
+ The host independently captures admitted-before and final-candidate snapshots with its trusted Chromium driver after source verification. Agent PNGs, a final-tree attachment and completion booleans cannot replace that execution. `path` is optional for this version; the host retains the actual PNG under its existing content-addressed evidence path. Keep application changes consistent with the admitted route and bounded state steps/assertions. Missing requirements need a maintainer to review and commit the configuration, then admit a new request; do not generate or edit authority during the current run. The initial isolated route supports source runnable from its tracked snapshot in the selected image, without dependency installation, generated build output, authentication, services or external assets. Unsupported or failed execution is unavailable.
45
+
46
+ The following Playwright file route describes earlier admitted requests. Their original receipt and publication checks remain supported, with explicit agent-declared provenance and no new capture-time freshness claim.
47
+
42
48
  Use Playwright from the adopter's installed browser tooling. Reuse its existing capture scripts when applicable; otherwise use a small capture within the authorized implementation scope. Use the Chromium included in the worker image at `/usr/bin/chromium` when needed. Follow the [managed command slot](../implement/SKILL.md#workspace-command-slot), including starting and stopping the preview server inside the same command. Capture the actual running product, never a separate mock page standing in for it.
43
49
 
44
50
  Save viewport PNGs under `/output/evidence/visual/`. Use `path: "visual/<file>.png"` relative to `/output/evidence`; never an absolute filesystem path or an invented public URL. Each PNG must be at most 2 MiB and match the declared viewport. Use `fullPage: false`. Keep the final candidate unchanged after capturing, except for host-owned OpenSpec metadata. Exclude credentials, private customer data and browser storage from evidence.
@@ -62,4 +68,4 @@ For each changed existing view, take a `before` capture from the admitted source
62
68
 
63
69
  The trusted publisher verifies retained bytes and their request/candidate binding, then publishes content-addressed PNGs and a report on the adopter's explicitly adopted, protected evidence branch. The issue and delivery PR embed commit-pinned image URLs. Do not call `safeoutputs`, upload credentials or push an assets branch from the agent container. Missing publication configuration or permissions are concrete maintainer blockers; a runner path alone is not a delivered image.
64
70
 
65
- Keep feedback on the same issue before a PR exists and on that PR afterward. A correction produces new evidence for its current candidate and preserves historical images. Required owner visual acceptance stays explicit in `pendingReview`; a generated image, test pass or hosted report cannot supply it. The host's integrity checks prove file identity and source binding, not that an agent's claimed screenshot independently establishes the running product's behavior.
71
+ Keep feedback on the same issue before a PR exists and on that PR afterward. A correction produces new evidence for its current candidate and preserves historical images. Required owner visual acceptance stays explicit in `pendingReview`; a generated image, test pass or hosted report cannot supply it. For version-2 implementation requests the publisher also compares independently captured rendering inputs against the assessed source/candidate trees and requires every admitted capture identity. Historical agent-declared captures retain their narrower provenance. Neither route proves visual quality or user acceptance.
@@ -137,6 +137,7 @@ export async function hostContractMain(args) {
137
137
  console.log(JSON.stringify({ instructions: skill, request, issue, predecessor, continuity: retainedChangeContext(request, issue), output: '/output/envelope.json', contract: {
138
138
  ...(request.instructionReview === 1 ? { instructionReview: instructionReviewContract } : {}),
139
139
  ...(request.processGuardReview === 1 ? { processGuards: processGuardContract } : {}),
140
+ ...(request.visualEvidence?.schemaVersion === 2 ? { visualCapture: { requirements: request.visualEvidence.requirements, producer: 'The host captures the admitted before source and final candidate independently. Supplied PNGs and completion booleans cannot replace that capture. Missing required views, states, appearances or viewports block completion; absent admitted requirements need a maintainer configuration change before visual implementation can pass.' } } : {}),
140
141
  resultSchema,
141
142
  ...(productWorker ? { productChangeSchema: JSON.parse(await readFile(new URL('../schemas/product-change.schema.json', import.meta.url), 'utf8')) } : {}),
142
143
  envelope: { schemaVersion: 1, result: { schemaVersion: 1, ...(request.client ? { input: { client: structuredClone(request.client) } } : {}), runId: request.runId, stage: request.stage, gate: stages.stages.find((s) => s.id === request.stage)?.gate, status: 'passed', evidence: [], missingEvidence: [], unavailableChecks: [], pendingReview: [], nextAction: 'await owner decision', output: {} }, effect: { type: 'issue-comment', body: 'Triage assessment or refined story, or a precise clarification question.' } },
@@ -11,7 +11,7 @@ export { taskDigest } from './digests.mjs';
11
11
  import { taskDigest } from './digests.mjs';
12
12
  export { repositoryApiUrl, createIssueApi } from './github-rest.mjs';
13
13
  import { createIssueApi } from './github-rest.mjs';
14
- import { visualStages } from './visual-evidence.mjs';
14
+ import { visualStages, loadVisualRequirements } from './visual-evidence.mjs';
15
15
  import { publishVisualEvidence } from './visual-publication.mjs';
16
16
  import { createTelemetry, telemetryContext, routingReason } from './telemetry.mjs';
17
17
  import { ciRepairAfterChecks, ciRepairKey, validateCiRepairChanges, signalCurrentCiRepair } from './ci-repair.mjs';
@@ -623,7 +623,7 @@ async function main(command) {
623
623
  if (epicPrerequisites) snapshot.epicPrerequisites = epicPrerequisites;
624
624
  await output('source_revision', revision.sha);
625
625
  telemetry.bind(telemetryContext(env, snapshot));
626
- if (!productWorker && visualStages.has(stage)) { snapshot.visualEvidence = { schemaVersion: 1 }; snapshot.repositoryId = repository.id; }
626
+ if (!productWorker && visualStages.has(stage)) { snapshot.visualEvidence = stage === 'implement' ? { schemaVersion: 2, requirements: await loadVisualRequirements(api, revision.sha, issueNumber) } : { schemaVersion: 1 }; snapshot.repositoryId = repository.id; }
627
627
  await writeFile(join(dir, 'request.json'), JSON.stringify(snapshot));
628
628
  if (seed) await writeFile(join(dir, 'seed.json'), JSON.stringify(seed));
629
629
  await writeFile(join(dir, 'issue.json'), JSON.stringify({ ...issue, ownerAnswers: answers.map(c => ({ id: c.id, updatedAt: c.updated_at, body: c.body, url: c.html_url, author: c.user.login })) }));
@@ -8,7 +8,7 @@ import { promisify } from 'node:util';
8
8
  import { createHash } from 'node:crypto';
9
9
  import { reviewOutputProtocol, reviewTemplate, reviewEnvelope } from './independent-review.mjs';
10
10
  import { retainVisualEvidence } from './visual-evidence.mjs';
11
- import { renderVisualProposal } from './visual-render.mjs';
11
+ import { renderVisualProposal, captureVisualProduct } from './visual-render.mjs';
12
12
  import { createRequire } from 'node:module';
13
13
  import { synchronizedSource, synchronizationDigest } from './source-sync.mjs';
14
14
  import { sourceFiles, collectChanges, isVerificationOnlyCorrection, materializeCandidate, validateChanges, changesDigest, withinScope } from './implementation.mjs';
@@ -196,7 +196,7 @@ async function main() {
196
196
  let name;
197
197
  const harness = resolve(dirname(fileURLToPath(import.meta.url)), '..');
198
198
  const runtimeReceipt = { ...await harnessIdentity(harness), image: config.image, limits, environment: environmentReceipt(selected), model: modelSelection.model, modelExecution: modelExecutionReceipt(modelSelection, request.modelSelection), engine: 'OpenCode 2.1.0', isolation: 'Docker; no AWF egress filtering', skills: await readdir(join(harness, 'skills')), sourceRevision: request.sourceRevision, seed: request.implementation?.policy.seed ?? null, seedDigest: request.seedDigest ?? null, phases: {} };
199
- let phase = 'preflight', evidenceRetained = false, visualCandidateTree = null;
199
+ let phase = 'preflight', evidenceRetained = false, visualCandidateTree = null, visualFiles = null, visualMetadata = null;
200
200
  const phaseStarted = new Map();
201
201
  const recordPhase = async status => { runtimeReceipt.phases[phase] = status; if (status === 'running') phaseStarted.set(phase, Date.now()); telemetry.emit('execution.phase', { phase, status, durationMs: phaseStarted.has(phase) ? Date.now() - phaseStarted.get(phase) : null }); await writeFile(join(runDir, 'runtime.json'), JSON.stringify(runtimeReceipt)); };
202
202
  const docker = args => runOwnedDocker(config, args, { stdio: 'ignore', timeout: 30000 });
@@ -426,7 +426,10 @@ async function main() {
426
426
  if (metadata) {
427
427
  candidateFiles.set(metadata.path, { content: metadata.content, mode: metadata.mode });
428
428
  runtimeReceipt.planningMetadata = { provider: '@fission-ai/openspec@1.15.0', path: metadata.path, origin: metadata.origin, sha256: createHash('sha256').update(metadata.content).digest('hex') };
429
+ // Only exact provider-scaffold bytes, never the planning directory, are inert.
430
+ if (metadata.origin === 'provider-scaffold') visualMetadata = { path: metadata.path, blobs: [createHash('sha1').update(`blob ${metadata.content.length}\0`).update(metadata.content).digest('hex')] };
429
431
  }
432
+ visualFiles = candidateFiles;
430
433
  const changes = metadata ? collectChanges(baseline, candidateFiles, request.implementation.policy, request.epicProduct) : modelChanges;
431
434
  if (request.sourceSynchronization && changes.length) throw Error('Synchronized verification cannot include model file changes');
432
435
  const verification = verificationIntegrity(baseline, candidateFiles, request.implementation.policy, request.issue);
@@ -460,7 +463,7 @@ async function main() {
460
463
  }
461
464
  if (!reviewOutput && request.worker !== 'independent-review') {
462
465
  try {
463
- await retainVisualEvidence(request, envelope, join(output, 'evidence'), runDir, { candidateTree: visualCandidateTree, render: item => renderVisualProposal(item, { config, directory: dir, deadline: budget.deadline }) });
466
+ await retainVisualEvidence(request, envelope, join(output, 'evidence'), runDir, { candidateTree: visualCandidateTree, sourceFiles: baseline, candidateFiles: visualFiles, inertMetadata: visualMetadata, capture: (files, item, server) => captureVisualProduct(files, item, server, { config, directory: dir, deadline: budget.deadline }), render: item => renderVisualProposal(item, { config, directory: dir, deadline: budget.deadline }) });
464
467
  } catch (error) {
465
468
  const reason = redactLog(`Visual evidence could not be retained: ${error.message}`).slice(0, 500);
466
469
  envelope.result.output.visualEvidence = { schemaVersion: 1, status: 'unavailable', reason, items: [] };
@@ -10,6 +10,48 @@ const record = value => value && typeof value === 'object' && !Array.isArray(val
10
10
  const text = value => typeof value === 'string' && value.trim() && value.length <= 500;
11
11
  const exact = (value, allowed) => record(value) && Object.keys(value).every(key => allowed.includes(key));
12
12
  const relative = path => typeof path === 'string' && path.length <= 180 && /^[a-zA-Z0-9][a-zA-Z0-9._/-]*\.png$/.test(path) && path.split('/').every(part => part && !['.', '..', '.git'].includes(part));
13
+ const appearances = ['light', 'dark', 'system-light', 'system-dark'];
14
+ const identity = item => JSON.stringify([item.kind, item.view, item.state, item.viewport?.width, item.viewport?.height, item.appearance]);
15
+
16
+ export function validateVisualRequirements(plan) {
17
+ if (!exact(plan, ['server', 'required']) || !exact(plan.server, ['command', 'port']) || !Array.isArray(plan.server.command) || !plan.server.command.length || plan.server.command.length > 30 || plan.server.command.some(arg => typeof arg !== 'string' || !arg || arg.length > 1000 || /[\0\r\n]/.test(arg)) || !Number.isSafeInteger(plan.server.port) || plan.server.port < 1024 || plan.server.port > 65535 || !Array.isArray(plan.required) || !plan.required.length || plan.required.length > 6) throw Error('Invalid admitted visual capture requirements');
18
+ const ids = new Set(), identities = new Set();
19
+ for (const item of plan.required) {
20
+ if (!exact(item, ['id', 'kind', 'view', 'state', 'viewport', 'appearance', 'themeSelector', 'route', 'steps', 'assertions']) || !/^[a-z][a-z0-9-]{0,47}$/.test(item.id ?? '') || ids.has(item.id) || !['before', 'candidate'].includes(item.kind) || !text(item.view) || !text(item.state) || !exact(item.viewport, ['width', 'height']) || ![item.viewport.width, item.viewport.height].every(n => Number.isSafeInteger(n) && n >= 240 && n <= 2560) || !appearances.includes(item.appearance) || !text(item.themeSelector) || typeof item.route !== 'string' || !/^\/(?!\/)[a-zA-Z0-9/_?=&.%~-]*$/.test(item.route) || item.route.length > 500 || !Array.isArray(item.steps) || item.steps.length > 12 || !Array.isArray(item.assertions) || !item.assertions.length || item.assertions.length > 12) throw Error('Invalid required visual view, state, appearance or viewport');
21
+ for (const step of item.steps) if (!exact(step, ['action', 'selector', 'value']) || !['click', 'select', 'fill'].includes(step.action) || !text(step.selector) || step.action !== 'click' && !text(step.value) || step.action === 'click' && step.value !== undefined) throw Error('Invalid bounded visual state step');
22
+ for (const assertion of item.assertions) if (!exact(assertion, ['selector', 'attribute', 'value', 'text']) || !text(assertion.selector) || assertion.attribute !== undefined && (!text(assertion.attribute) || !text(assertion.value)) || assertion.attribute === undefined && assertion.value !== undefined || assertion.text !== undefined && !text(assertion.text)) throw Error('Invalid required visual state assertion');
23
+ if (identities.has(identity(item))) throw Error('Duplicate required visual identity');
24
+ ids.add(item.id); identities.add(identity(item));
25
+ }
26
+ if (!plan.required.some(item => item.kind === 'candidate')) throw Error('Visual requirements need a candidate capture');
27
+ return plan;
28
+ }
29
+
30
+ export async function loadVisualRequirements(api, revision, issue) {
31
+ const file = await api(`contents/.lighthouse/visual-evidence.json?ref=${revision}`, 'GET', undefined, true);
32
+ if (!file) return null;
33
+ if (file.type !== 'file' || file.encoding !== 'base64' || file.size > 32000) throw Error('Invalid visual requirements source');
34
+ const bytes = Buffer.from(file.content, 'base64');
35
+ if (bytes.length > 32000) throw Error('Visual requirements exceed bounds');
36
+ const config = JSON.parse(bytes);
37
+ if (!exact(config, ['schemaVersion', 'defaults', 'issues']) || config.schemaVersion !== 1 || config.issues !== undefined && (!record(config.issues) || Object.keys(config.issues).length > 100 || Object.keys(config.issues).some(key => !/^[1-9]\d*$/.test(key)))) throw Error('Invalid visual requirements configuration');
38
+ const plan = config.issues?.[issue] ?? config.defaults;
39
+ return plan === undefined ? null : validateVisualRequirements(plan);
40
+ }
41
+
42
+ // Every admitted source/style/script/config/asset is an input, including planning files.
43
+ export function visualInputIdentity(entries, inertMetadata = null) {
44
+ const rows = entries instanceof Map ? [...entries].map(([path, file]) => ({ path, mode: file.mode, type: 'blob', sha: createHash('sha1').update(`blob ${file.content.length}\0`).update(file.content).digest('hex') })) : entries.filter(entry => entry.type !== 'tree');
45
+ if (inertMetadata && (!/^openspec\/changes\/issue-[1-9]\d*-proposal\/\.openspec\.yaml$/.test(inertMetadata.path ?? '') || !Array.isArray(inertMetadata.blobs) || !inertMetadata.blobs.length || inertMetadata.blobs.length > 2 || inertMetadata.blobs.some(sha => !/^[a-f0-9]{40}$/.test(sha)))) throw Error('Invalid host-owned inert metadata boundary');
46
+ const inputs = rows.filter(entry => {
47
+ if (entry.type !== 'blob' || !['100644', '100755'].includes(entry.mode) || !/^[a-f0-9]{40}$/.test(entry.sha)) throw Error('Unsupported visual rendering input');
48
+ if (entry.path !== inertMetadata?.path) return true;
49
+ if (entry.mode !== '100644' || !inertMetadata.blobs.includes(entry.sha)) throw Error('Host-owned visual metadata changed unexpectedly');
50
+ return false;
51
+ }).map(({ path, mode, sha }) => [path, mode, sha]).sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
52
+ if (!inputs.length) throw Error('Visual rendering inputs are empty');
53
+ return sha256(JSON.stringify(inputs));
54
+ }
13
55
 
14
56
  export function validateVisualEvidence(value, request) {
15
57
  if (value === undefined && !request.visualEvidence) return [];
@@ -18,21 +60,33 @@ export function validateVisualEvidence(value, request) {
18
60
  if (value.status !== 'provided' && value.items.length || value.status === 'provided' && !value.items.length) errors.push('Visual evidence status and items disagree');
19
61
  const ids = new Set();
20
62
  for (const item of value.items) {
21
- if (!exact(item, ['id', 'kind', 'view', 'state', 'viewport', 'path', 'html', 'revision', 'baseline', 'baselineReason']) || !/^[a-z][a-z0-9-]{0,47}$/.test(item.id ?? '') || ids.has(item.id) || !['proposal', 'before', 'candidate'].includes(item.kind) || !text(item.view) || !text(item.state) || !exact(item.viewport, ['width', 'height']) || ![item.viewport.width, item.viewport.height].every(n => Number.isSafeInteger(n) && n >= 240 && n <= 2560)) {
63
+ if (!exact(item, ['id', 'kind', 'view', 'state', 'viewport', 'appearance', 'path', 'html', 'revision', 'baseline', 'baselineReason']) || !/^[a-z][a-z0-9-]{0,47}$/.test(item.id ?? '') || ids.has(item.id) || !['proposal', 'before', 'candidate'].includes(item.kind) || !text(item.view) || !text(item.state) || !exact(item.viewport, ['width', 'height']) || ![item.viewport.width, item.viewport.height].every(n => Number.isSafeInteger(n) && n >= 240 && n <= 2560) || item.appearance !== undefined && !appearances.includes(item.appearance)) {
22
64
  errors.push('Invalid visual evidence item, identity or viewport'); continue;
23
65
  }
24
66
  ids.add(item.id);
25
67
  if (item.html !== undefined) {
26
68
  if (item.kind !== 'proposal' || item.path !== undefined || typeof item.html !== 'string' || !item.html.trim() || Buffer.byteLength(item.html) > 16000) errors.push('Only a bounded proposed design can use inline HTML');
27
- } else if (!relative(item.path)) errors.push('Visual captures need a safe relative PNG path');
69
+ } else if (!relative(item.path) && !(item.path === undefined && request.stage === 'implement' && request.visualEvidence?.schemaVersion === 2)) errors.push('Visual captures need a safe relative PNG path');
28
70
  if (item.kind === 'candidate' && request.stage !== 'implement') errors.push('Only implementation can produce candidate captures');
29
71
  if (item.kind === 'before' && item.revision !== request.sourceRevision || item.kind !== 'before' && item.revision !== undefined) errors.push('Before captures must name the admitted source revision; candidate identity belongs to the host');
30
72
  if (item.kind === 'candidate') {
31
73
  if (!['existing', 'new'].includes(item.baseline) || item.baseline === 'new' && !text(item.baselineReason)) errors.push('Candidate captures need an existing baseline or a reason for a new view');
32
- if (item.baseline === 'existing' && !value.items.some(before => before?.kind === 'before' && before.view === item.view && before.state === item.state && before.viewport?.width === item.viewport.width && before.viewport?.height === item.viewport.height)) errors.push('An existing view needs a matching before capture');
74
+ if (item.baseline === 'existing' && !value.items.some(before => before?.kind === 'before' && before.view === item.view && before.state === item.state && before.viewport?.width === item.viewport.width && before.viewport?.height === item.viewport.height && before.appearance === item.appearance)) errors.push('An existing view needs a matching before capture');
33
75
  } else if (item.baseline !== undefined || item.baselineReason !== undefined) errors.push('Only candidate captures can declare a baseline');
34
76
  }
35
77
  if (request.stage === 'implement' && value.status === 'provided' && !value.items.some(item => item?.kind === 'candidate')) errors.push('Visual implementation needs actual candidate captures');
78
+ if (request.stage === 'implement' && request.visualEvidence?.schemaVersion === 2) {
79
+ const plan = request.visualEvidence.requirements;
80
+ let validPlan = false;
81
+ try { if (plan) { validateVisualRequirements(plan); validPlan = true; } else if (value.status === 'provided') throw Error('Admit independent visual capture requirements before claiming complete evidence'); }
82
+ catch (error) { errors.push(error.message); }
83
+ if (plan && value.status === 'not-applicable') errors.push('Required visual captures cannot be marked not-applicable');
84
+ if (validPlan && value.status === 'provided' && (value.items.length !== plan.required.length || plan.required.some(required => !value.items.some(item => item?.id === required.id && identity(item) === identity(required))))) errors.push('Missing or mismatched required visual view, state, appearance or viewport');
85
+ if (validPlan && value.status === 'provided') for (const item of value.items.filter(item => item?.kind === 'candidate')) {
86
+ const paired = plan.required.some(before => before.kind === 'before' && identity({ ...before, kind: 'candidate' }) === identity(item));
87
+ if (item.baseline !== (paired ? 'existing' : 'new')) errors.push('Candidate baseline differs from the admitted coverage');
88
+ }
89
+ }
36
90
  if (['refine', 'propose'].includes(request.stage) && value.status === 'provided' && !value.items.some(item => item?.kind === 'proposal')) errors.push('Visual planning needs a concrete proposed example');
37
91
  try { validatePublishable({ 'visual-assessment.json': JSON.stringify(value) }); } catch (error) { errors.push(error.message); }
38
92
  return errors;
@@ -63,21 +117,33 @@ export async function readVisualFile(root, path, maximum = 2 * 1024 * 1024) {
63
117
  } finally { await file.close(); }
64
118
  }
65
119
 
66
- export async function retainVisualEvidence(request, envelope, output, runDir, { render, candidateTree = null } = {}) {
120
+ export async function retainVisualEvidence(request, envelope, output, runDir, { render, candidateTree = null, capture, sourceFiles, candidateFiles, inertMetadata = null } = {}) {
67
121
  const value = envelope.result.output?.visualEvidence;
68
122
  if (!visualStages.has(request.stage) || request.worker === 'product-change' || value === undefined && !request.visualEvidence) return;
69
123
  const errors = validateVisualEvidence(value, request);
70
124
  if (errors.length) throw Error(errors.join('\n'));
71
125
  const items = [];
126
+ const trusted = request.stage === 'implement' && request.visualEvidence?.schemaVersion === 2 && value.status === 'provided';
127
+ const plan = request.visualEvidence?.requirements;
128
+ if (trusted && (typeof capture !== 'function' || !(candidateFiles instanceof Map) || !(sourceFiles instanceof Map) || !/^[a-f0-9]{40}$/.test(candidateTree ?? ''))) throw Error('Trusted visual capture and rendering inputs are unavailable');
129
+ const capturePolicy = trusted ? { requirementsSha256: sha256(JSON.stringify(plan)), inertMetadata } : undefined;
72
130
  await mkdir(join(runDir, 'evidence', 'visual'), { recursive: true });
73
131
  for (const item of value.items) {
74
- const bytes = validatePng(item.html === undefined ? await readVisualFile(output, item.path) : await render(item), item.viewport);
132
+ let captured, inputSha256;
133
+ if (trusted) {
134
+ const inputs = item.kind === 'before' ? sourceFiles : candidateFiles, inert = item.kind === 'before' ? null : inertMetadata;
135
+ inputSha256 = visualInputIdentity(inputs, inert);
136
+ captured = await capture(inputs, plan.required.find(required => required.id === item.id), plan.server);
137
+ if (inputSha256 !== visualInputIdentity(inputs, inert)) throw Error('Rendering inputs changed after visual capture');
138
+ if (!text(captured?.browser) || captured.url !== `http://product:${plan.server.port}${plan.required.find(required => required.id === item.id).route}`) throw Error('Trusted browser capture did not complete');
139
+ }
140
+ const bytes = validatePng(trusted ? captured.png : item.html === undefined ? await readVisualFile(output, item.path) : await render(item), item.viewport);
75
141
  const digest = sha256(bytes), path = `evidence/visual/${digest}.png`;
76
142
  await writeFile(join(runDir, path), bytes, { mode: 0o600 });
77
143
  const { html, path: originalPath, ...metadata } = item;
78
- items.push({ ...metadata, path, sha256: digest, bytes: bytes.length, producer: html === undefined ? 'agent-declared capture' : 'isolated proposed-design renderer', ...(html === undefined ? {} : { htmlSha256: sha256(html) }) });
144
+ items.push({ ...metadata, path, sha256: digest, bytes: bytes.length, producer: trusted ? 'isolated host browser capture' : html === undefined ? 'agent-declared capture' : 'isolated proposed-design renderer', ...(trusted ? { capture: { inputSha256, browser: captured.browser, url: captured.url } } : {}), ...(html === undefined ? {} : { htmlSha256: sha256(html) }) });
79
145
  }
80
- const receipt = { schemaVersion: 1, repository: request.repository, issue: request.issue, runId: request.runId, workflowRunId: String(request.workflowRunId), attempt: Number(request.attempt), stage: request.stage, sourceRevision: request.sourceRevision, candidateTree, assessmentSha256: sha256(JSON.stringify(value)), status: value.status, reason: value.reason, items };
146
+ const receipt = { schemaVersion: 1, repository: request.repository, issue: request.issue, runId: request.runId, workflowRunId: String(request.workflowRunId), attempt: Number(request.attempt), stage: request.stage, sourceRevision: request.sourceRevision, candidateTree, assessmentSha256: sha256(JSON.stringify(value)), ...(capturePolicy ? { capturePolicy } : {}), status: value.status, reason: value.reason, items };
81
147
  await writeFile(join(runDir, 'visual-evidence.json'), JSON.stringify(receipt));
82
148
  return receipt;
83
149
  }
@@ -1,7 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { isDeepStrictEqual } from 'node:util';
3
3
  import { loadProfile, evidenceProtection } from './completion-state.mjs';
4
- import { readVisualFile, validatePng, validateVisualEvidence } from './visual-evidence.mjs';
4
+ import { readVisualFile, validatePng, validateVisualEvidence, visualInputIdentity } from './visual-evidence.mjs';
5
5
  import { validatePublishable } from './process-publication.mjs';
6
6
 
7
7
  const digest = value => createHash('sha256').update(value).digest('hex');
@@ -16,11 +16,26 @@ export async function publishVisualEvidence(api, request, envelope, directory, {
16
16
  const receipt = JSON.parse(await readVisualFile(directory, 'visual-evidence.json', 32000));
17
17
  if (receipt.schemaVersion !== 1 || receipt.repository !== request.repository || receipt.issue !== request.issue || receipt.runId !== request.runId || receipt.workflowRunId !== String(request.workflowRunId) || receipt.attempt !== Number(request.attempt) || receipt.stage !== request.stage || receipt.sourceRevision !== request.sourceRevision || receipt.candidateTree !== candidateTree || receipt.assessmentSha256 !== digest(JSON.stringify(assessment)) || receipt.items?.length !== assessment.items.length) throw Error('Visual evidence does not bind this request and candidate');
18
18
  if (!/^[a-f0-9]{40}$/.test(request.sourceRevision) || request.stage === 'implement' && !/^[a-f0-9]{40}$/.test(candidateTree ?? '') || !Number.isSafeInteger(request.issue) || request.issue < 1 || !/^[1-9]\d*$/.test(String(request.workflowRunId)) || !Number.isSafeInteger(Number(request.attempt)) || Number(request.attempt) < 1) throw Error('Invalid visual publication identity');
19
+ const trusted = request.stage === 'implement' && request.visualEvidence?.schemaVersion === 2;
20
+ let sourceInput, candidateInput;
21
+ if (trusted) {
22
+ const plan = request.visualEvidence.requirements, inert = receipt.capturePolicy?.inertMetadata;
23
+ if (receipt.capturePolicy?.requirementsSha256 !== digest(JSON.stringify(plan)) || inert && inert.path !== `openspec/changes/issue-${request.issue}-proposal/.openspec.yaml`) throw Error('Visual capture requirements or inert boundary changed');
24
+ const source = await api(`git/commits/${request.sourceRevision}`);
25
+ const before = await api(`git/trees/${source.tree.sha}?recursive=1`), candidate = await api(`git/trees/${candidateTree}?recursive=1`);
26
+ if (before.truncated || candidate.truncated || !Array.isArray(before.tree) || !Array.isArray(candidate.tree) || before.tree.length > 10000 || candidate.tree.length > 10000) throw Error('Visual rendering inputs are unavailable or exceed bounds');
27
+ sourceInput = visualInputIdentity(before.tree);
28
+ candidateInput = visualInputIdentity(candidate.tree, inert);
29
+ }
19
30
  const files = new Map();
20
31
  for (const [index, item] of receipt.items.entries()) {
21
- const { path, sha256, bytes, producer, htmlSha256, ...metadata } = item;
32
+ const { path, sha256, bytes, producer, htmlSha256, capture, ...metadata } = item;
22
33
  const { html, path: originalPath, ...expected } = assessment.items[index];
23
- if (!isDeepStrictEqual(metadata, expected) || path !== `evidence/visual/${sha256}.png` || !/^[a-f0-9]{64}$/.test(sha256) || producer !== (html === undefined ? 'agent-declared capture' : 'isolated proposed-design renderer') || htmlSha256 !== (html === undefined ? undefined : digest(html))) throw Error('Visual receipt metadata changed');
34
+ if (!isDeepStrictEqual(metadata, expected) || path !== `evidence/visual/${sha256}.png` || !/^[a-f0-9]{64}$/.test(sha256) || producer !== (trusted ? 'isolated host browser capture' : html === undefined ? 'agent-declared capture' : 'isolated proposed-design renderer') || htmlSha256 !== (html === undefined ? undefined : digest(html))) throw Error('Visual receipt metadata changed');
35
+ if (trusted) {
36
+ const required = request.visualEvidence.requirements.required.find(required => required.id === item.id);
37
+ if (capture?.inputSha256 !== (item.kind === 'before' ? sourceInput : candidateInput) || typeof capture.browser !== 'string' || !/^(?:HeadlessChrome|Chrome)\/[\d.]+$/.test(capture.browser) || capture.url !== `http://product:${request.visualEvidence.requirements.server.port}${required.route}`) throw Error('Visual capture is stale, incomplete or lacks trusted browser provenance');
38
+ } else if (capture !== undefined || receipt.capturePolicy !== undefined) throw Error('Unexpected trusted visual capture metadata');
24
39
  const content = validatePng(await readVisualFile(directory, path), item.viewport);
25
40
  if (content.length !== bytes || digest(content) !== sha256) throw Error('Visual capture content changed');
26
41
  files.set(`${sha256}.png`, content);
@@ -30,7 +45,7 @@ export async function publishVisualEvidence(api, request, envelope, directory, {
30
45
  const profile = await loadProfile(api, request.repository, request.baseRevision ?? request.sourceRevision);
31
46
  if (profile.evidenceBranch === repository.default_branch) throw Error('Visual evidence branch must be separate from source');
32
47
  const prefix = `visual/issue-${request.issue}/runs/${request.workflowRunId}/attempt-${request.attempt}`;
33
- const report = `# Visual evidence for #${request.issue}\n\nStage: ${request.stage}. Source: \`${request.sourceRevision}\`. Candidate tree: \`${candidateTree ?? 'not an implementation'}\`.\n\n${escape(assessment.reason)}\n\n${receipt.items.map(item => `## ${escape(item.id)}: ${item.kind}\n\nView: ${escape(item.view)}. State: ${escape(item.state)}. Viewport: ${item.viewport.width} × ${item.viewport.height}. Producer: ${item.producer}.\n\n![${escape(item.view)} — ${item.kind}](${item.sha256}.png)\n`).join('\n')}\nProposed designs are illustrative. Candidate captures are agent-declared; the host verifies their bytes and binds them to the independently checked candidate tree. Images grant no visual acceptance, merge or release approval.\n`;
48
+ const report = `# Visual evidence for #${request.issue}\n\nStage: ${request.stage}. Source: \`${request.sourceRevision}\`. Candidate tree: \`${candidateTree ?? 'not an implementation'}\`.\n\n${escape(assessment.reason)}\n\n${receipt.items.map(item => `## ${escape(item.id)}: ${item.kind}\n\nView: ${escape(item.view)}. State: ${escape(item.state)}. Viewport: ${item.viewport.width} × ${item.viewport.height}. Appearance: ${escape(item.appearance ?? 'undeclared historical capture')}. Producer: ${item.producer}.${item.capture ? ` Rendering inputs: \`${item.capture.inputSha256}\`. Browser: ${escape(item.capture.browser)}.` : ''}\n\n![${escape(item.view)} — ${item.kind}](${item.sha256}.png)\n`).join('\n')}\nProposed designs are illustrative. ${trusted ? 'The isolated host browser executed the admitted routes and state assertions against source snapshots. Rendering-input identities match the assessed trees.' : 'Historical candidate captures are agent-declared; the host verifies their bytes and final-tree attachment, without capture-time freshness or independent browser proof.'} Images grant no visual acceptance, merge or release approval.\n`;
34
49
  const textFiles = validatePublishable({ 'report.md': report, 'receipt.json': JSON.stringify(receipt, null, 2) + '\n' });
35
50
  for (const [name, content] of Object.entries(textFiles)) files.set(name, Buffer.from(content));
36
51
  const branch = profile.evidenceBranch;
@@ -1,5 +1,9 @@
1
- import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
2
- import { join } from 'node:path';
1
+ import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
2
+ import { tmpdir } from 'node:os';
3
+ import { join, dirname } from 'node:path';
4
+ import { spawn } from 'node:child_process';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { setTimeout as sleep } from 'node:timers/promises';
3
7
  import { runOwnedDocker } from './execution-cleanup.mjs';
4
8
 
5
9
  // Proposed designs receive no repository, engine credentials, network or JavaScript.
@@ -19,3 +23,155 @@ export async function renderVisualProposal(item, { config, directory, deadline }
19
23
  await rm(root, { recursive: true, force: true });
20
24
  }
21
25
  }
26
+
27
+ // The product server never shares a filesystem, credentials or DevTools with the browser.
28
+ export async function captureVisualProduct(files, item, server, { config, directory, deadline, run: execute = (args, options) => runOwnedDocker(config, args, options) }) {
29
+ const timeout = Math.min(30000, deadline - Date.now());
30
+ if (timeout <= 0) throw Error('Execution deadline reached before product capture');
31
+ const root = await mkdtemp(join(directory, 'visual-product-'));
32
+ const name = `${config.resourceOwner.prefix}-capture-${item.id}`, network = `${name}-network`, product = `${name}-product`;
33
+ const run = (args, options = {}) => execute(args, { timeout: Math.max(1, Math.min(timeout, deadline - Date.now())), stdio: 'pipe', ...options });
34
+ let networkAttempted = false, productAttempted = false, browserAttempted = false;
35
+ let failure;
36
+ try {
37
+ await chmod(root, 0o755);
38
+ const directories = new Set([root]);
39
+ for (const [path, file] of files) {
40
+ if (!/^[a-zA-Z0-9._/-]+$/.test(path) || path.split('/').some(part => !part || ['.', '..', '.git'].includes(part)) || !['100644', '100755'].includes(file.mode)) throw Error('Unsafe visual product source');
41
+ let parent = root;
42
+ for (const part of path.split('/').slice(0, -1)) {
43
+ parent = join(parent, part);
44
+ if (!directories.has(parent)) { await mkdir(parent); await chmod(parent, 0o755); directories.add(parent); }
45
+ }
46
+ await writeFile(join(root, path), file.content);
47
+ await chmod(join(root, path), file.mode === '100755' ? 0o555 : 0o444);
48
+ }
49
+ const policy = join(root, '..', `${name}.json`);
50
+ await writeFile(policy, JSON.stringify(item), { mode: 0o444 });
51
+ await chmod(policy, 0o444);
52
+ const limits = ['--user', `${config.uid}:${config.uid}`, '--cpus', '2', '--memory', '1g', '--pids-limit', '256', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', '--read-only', '--tmpfs', '/tmp:rw,exec,size=256m,mode=1777', '--env', 'HOME=/tmp'];
53
+ networkAttempted = true; run(['network', 'create', '--internal', network]);
54
+ productAttempted = true;
55
+ run(['run', '--detach', '--rm', '--init', '--name', product, '--network', network, '--network-alias', 'product', ...limits, '--mount', `type=bind,src=${root},dst=/workspace,readonly`, '--workdir', '/workspace', '--entrypoint', server.command[0], config.image, ...server.command.slice(1)]);
56
+ browserAttempted = true;
57
+ const result = run(['run', '--rm', '--init', '--name', name, '--network', network, ...limits, '--mount', `type=bind,src=${fileURLToPath(new URL('../', import.meta.url))},dst=/harness,readonly`, '--mount', `type=bind,src=${policy},dst=/input.json,readonly`, '--entrypoint', 'node', config.image, '/harness/src/visual-render.mjs', 'capture-browser', '/input.json', `http://product:${server.port}`], { maxBuffer: 4 * 1024 * 1024 });
58
+ const captured = JSON.parse(result.toString('utf8'));
59
+ return { ...captured, png: Buffer.from(captured.png, 'base64') };
60
+ } catch (error) { failure = error; throw error; }
61
+ finally {
62
+ const cleanupFailures = [];
63
+ for (const [attempted, args] of [[browserAttempted, ['rm', '-f', name]], [productAttempted, ['rm', '-f', product]], [networkAttempted, ['network', 'rm', network]]]) {
64
+ if (attempted) try { run(args, { timeout: 30000 }); } catch { cleanupFailures.push(args[0]); }
65
+ }
66
+ if (!cleanupFailures.length) {
67
+ await rm(join(root, '..', `${name}.json`), { force: true });
68
+ await rm(root, { recursive: true, force: true });
69
+ }
70
+ if (cleanupFailures.length) throw Error(`${failure ? failure.message + '; ' : ''}Visual resource cleanup failed; operator must reconcile the retained capture workspace`, { cause: failure });
71
+ }
72
+ }
73
+
74
+ // Uses only Node and the image's Chromium; never imports a candidate browser library.
75
+ export async function captureBrowser(item, origin, { executable = '/usr/bin/chromium', timeout = 25000 } = {}) {
76
+ const url = `${origin}${item.route}`, deadline = Date.now() + timeout;
77
+ if (new URL(url).origin !== origin || new URL(url).href !== url) throw Error('Visual route changed its admitted identity');
78
+ for (;;) {
79
+ try {
80
+ const response = await fetch(url, { signal: AbortSignal.timeout(Math.max(1, Math.min(1000, deadline - Date.now()))), redirect: 'error' });
81
+ await response.body?.cancel();
82
+ if (response.ok) break;
83
+ } catch { /* The host-owned server may still be starting. */ }
84
+ if (Date.now() >= deadline) throw Error('Required visual route is unavailable');
85
+ await sleep(100);
86
+ }
87
+ const profile = await mkdtemp(join(tmpdir(), 'lighthouse-visual-browser-'));
88
+ const browser = spawn(executable, ['--headless', '--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage', '--no-first-run', '--no-default-browser-check', `--user-data-dir=${profile}`, '--remote-debugging-pipe'], { stdio: ['ignore', 'ignore', 'ignore', 'pipe', 'pipe'] });
89
+ let id = 0, pendingBytes = '', session, closed = false;
90
+ const pending = new Map(), failures = [];
91
+ const fail = message => { closed = true; for (const waiter of pending.values()) waiter.reject(Error(message)); pending.clear(); };
92
+ browser.on('error', () => fail('Trusted Chromium could not start'));
93
+ browser.on('exit', () => fail('Trusted Chromium exited before capture completed'));
94
+ browser.stdio[3].on('error', () => fail('Trusted Chromium command pipe failed'));
95
+ const send = (method, params = {}, target = session) => new Promise((resolve, reject) => {
96
+ if (closed) return reject(Error('Trusted Chromium is unavailable'));
97
+ const command = ++id;
98
+ pending.set(command, { resolve, reject });
99
+ browser.stdio[3].write(JSON.stringify({ id: command, method, params, ...(target ? { sessionId: target } : {}) }) + '\0');
100
+ });
101
+ browser.stdio[4].setEncoding('utf8');
102
+ browser.stdio[4].on('data', chunk => {
103
+ pendingBytes += chunk;
104
+ if (pendingBytes.length > 4 * 1024 * 1024) { fail('Trusted Chromium response exceeds bounds'); return; }
105
+ let end;
106
+ while ((end = pendingBytes.indexOf('\0')) >= 0) {
107
+ let message;
108
+ try { message = JSON.parse(pendingBytes.slice(0, end)); } catch { fail('Invalid trusted Chromium response'); return; }
109
+ pendingBytes = pendingBytes.slice(end + 1);
110
+ if (message.id) {
111
+ const waiter = pending.get(message.id); pending.delete(message.id);
112
+ if (message.error) waiter?.reject(Error('Trusted browser command failed')); else waiter?.resolve(message.result);
113
+ }
114
+ if (message.method === 'Runtime.exceptionThrown' || message.method === 'Network.loadingFailed') failures.push(message.method);
115
+ if (message.method === 'Network.responseReceived' && message.params.response.status >= 400 && message.params.type !== 'Other') failures.push('Required browser resource failed');
116
+ if (message.method === 'Fetch.requestPaused') {
117
+ const request = message.params, allowed = request.request.url.startsWith(origin + '/') || /^(data:|about:blank$)/.test(request.request.url);
118
+ if (!allowed) failures.push('Browser requested an unadmitted origin');
119
+ send(allowed ? 'Fetch.continueRequest' : 'Fetch.failRequest', { requestId: request.requestId, ...(allowed ? {} : { errorReason: 'BlockedByClient' }) }).catch(() => {});
120
+ }
121
+ }
122
+ });
123
+ const timer = setTimeout(() => { fail('Trusted browser capture timed out'); browser.kill('SIGKILL'); }, Math.max(1, deadline - Date.now()));
124
+ try {
125
+ const version = await send('Browser.getVersion', {}, null);
126
+ const { targetId } = await send('Target.createTarget', { url: 'about:blank' }, null);
127
+ session = (await send('Target.attachToTarget', { targetId, flatten: true }, null)).sessionId;
128
+ for (const method of ['Page.enable', 'Runtime.enable', 'Network.enable']) await send(method);
129
+ await send('Fetch.enable', { patterns: [{ urlPattern: '*' }] });
130
+ await send('Emulation.setDeviceMetricsOverride', { ...item.viewport, deviceScaleFactor: 1, mobile: false });
131
+ await send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: item.appearance.endsWith('dark') ? 'dark' : 'light' }, { name: 'prefers-reduced-motion', value: 'reduce' }] });
132
+ const navigation = await send('Page.navigate', { url });
133
+ if (navigation.errorText) throw Error('Required visual route failed in the browser');
134
+ const evaluate = async expression => {
135
+ const result = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
136
+ if (result.exceptionDetails) throw Error('Required visual state failed');
137
+ return result.result.value;
138
+ };
139
+ // Page.navigate can finish before the new execution context exists.
140
+ while (!await evaluate(`location.href === ${JSON.stringify(url)} && document.readyState === 'complete'`)) await sleep(30);
141
+ const apply = async ({ steps, assertions }) => {
142
+ for (const step of steps) {
143
+ const element = document.querySelector(step.selector);
144
+ if (!element || !element.getClientRects().length) throw Error('State step target is absent');
145
+ if (step.action === 'click') element.click();
146
+ else { element.value = step.value; element.dispatchEvent(new Event(step.action === 'select' ? 'change' : 'input', { bubbles: true })); }
147
+ }
148
+ await document.fonts.ready;
149
+ return new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => {
150
+ resolve(assertions.every(assertion => {
151
+ const element = document.querySelector(assertion.selector);
152
+ return element && element.getClientRects().length > 0 && getComputedStyle(element).visibility !== 'hidden' && (assertion.attribute === undefined || element.getAttribute(assertion.attribute) === assertion.value) && (assertion.text === undefined || element.textContent.includes(assertion.text));
153
+ }));
154
+ })));
155
+ };
156
+ if (!await evaluate(`(${apply.toString()})(${JSON.stringify({ steps: item.steps, assertions: [...item.assertions, { selector: item.themeSelector, attribute: 'data-lh-theme', value: item.appearance.startsWith('system-') ? 'system' : item.appearance }] })})`)) throw Error('Required visual state or appearance was not reached');
157
+ if (failures.length) throw Error('Browser execution failed: ' + [...new Set(failures)].join(', '));
158
+ const screenshot = await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false, clip: { x: 0, y: 0, ...item.viewport, scale: 1 } });
159
+ if (failures.length) throw Error('Browser execution failed during capture');
160
+ return { browser: version.product, url, png: Buffer.from(screenshot.data, 'base64') };
161
+ } finally {
162
+ if (!closed) try { await send('Browser.close', {}, null); } catch { /* Exit can precede the close response. */ }
163
+ clearTimeout(timer); fail('Trusted browser capture finished');
164
+ if (browser.exitCode === null && browser.signalCode === null) {
165
+ const exited = new Promise(resolve => browser.once('close', resolve));
166
+ const kill = setTimeout(() => browser.kill('SIGKILL'), 1000);
167
+ await exited; clearTimeout(kill);
168
+ }
169
+ await rm(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
170
+ }
171
+ }
172
+
173
+ if (process.argv[1] === fileURLToPath(import.meta.url) && process.argv[2] === 'capture-browser') {
174
+ const item = JSON.parse(await readFile(process.argv[3], 'utf8'));
175
+ const result = await captureBrowser(item, process.argv[4]);
176
+ process.stdout.write(JSON.stringify({ ...result, png: result.png.toString('base64') }));
177
+ }