dsh-knowhub 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/README.md +11 -2
  2. package/cordis.patch.yml +10 -0
  3. package/lib/host/model.js +1 -1
  4. package/lib/host/pipeline/incremental.js +3 -3
  5. package/lib/host/pipeline/initialize.js +144 -27
  6. package/lib/host/pipeline/model-output.js +2 -2
  7. package/package.json +3 -2
  8. package/skills/archify/LICENSE +202 -0
  9. package/skills/archify/LICENSE-MIT +22 -0
  10. package/skills/archify/NOTICE +26 -0
  11. package/skills/archify/SKILL.md +137 -0
  12. package/skills/archify/THIRD_PARTY_NOTICES.md +78 -0
  13. package/skills/archify/assets/JetBrainsMono-OFL.txt +93 -0
  14. package/skills/archify/assets/template.html +14768 -0
  15. package/skills/archify/bin/archify.mjs +7289 -0
  16. package/skills/archify/bin/delivery-update.mjs +92 -0
  17. package/skills/archify/bin/finalize.mjs +1055 -0
  18. package/skills/archify/bin/open-artifact.mjs +146 -0
  19. package/skills/archify/bin/preview.mjs +970 -0
  20. package/skills/archify/bin/recover-output.mjs +41 -0
  21. package/skills/archify/bin/visual-check.mjs +2780 -0
  22. package/skills/archify/brand-marks/README.md +31 -0
  23. package/skills/archify/brand-marks/catalog.json +131 -0
  24. package/skills/archify/delta/architecture-delta.mjs +1318 -0
  25. package/skills/archify/examples/agent-run.lifecycle.json +55 -0
  26. package/skills/archify/examples/agent-tool-call.workflow.json +74 -0
  27. package/skills/archify/examples/archify-dev-activity.timeline.json +176 -0
  28. package/skills/archify/examples/archify-repository.tree.json +197 -0
  29. package/skills/archify/examples/async-job-roundtrip.sequence.json +56 -0
  30. package/skills/archify/examples/brand-aware-delivery.architecture.json +34 -0
  31. package/skills/archify/examples/cache-miss-request.sequence.json +77 -0
  32. package/skills/archify/examples/checkout-platform.base.architecture.json +32 -0
  33. package/skills/archify/examples/checkout-platform.head.architecture.json +32 -0
  34. package/skills/archify/examples/checkout-request.waterfall.json +20 -0
  35. package/skills/archify/examples/delivery.explainer.json +155 -0
  36. package/skills/archify/examples/deployment-release.lifecycle.json +72 -0
  37. package/skills/archify/examples/event-stream.dataflow.json +52 -0
  38. package/skills/archify/examples/example-rebuild.waterfall.json +212 -0
  39. package/skills/archify/examples/holiday-planning.workflow.json +143 -0
  40. package/skills/archify/examples/incident-response.workflow.json +59 -0
  41. package/skills/archify/examples/locales/de.json +463 -0
  42. package/skills/archify/examples/locales/fr.json +463 -0
  43. package/skills/archify/examples/locales/fr.partial.json +22 -0
  44. package/skills/archify/examples/locales/it.json +463 -0
  45. package/skills/archify/examples/locales/ja.json +463 -0
  46. package/skills/archify/examples/locales/pt.json +463 -0
  47. package/skills/archify/examples/locales/ru.json +463 -0
  48. package/skills/archify/examples/orders.erd.json +337 -0
  49. package/skills/archify/examples/payment-incident.timeline.json +24 -0
  50. package/skills/archify/examples/payment-platform.tree.json +22 -0
  51. package/skills/archify/examples/payment-processors.class.json +177 -0
  52. package/skills/archify/examples/payments.class.json +85 -0
  53. package/skills/archify/examples/product-analytics.dataflow.json +71 -0
  54. package/skills/archify/examples/production-deployment.architecture.json +51 -0
  55. package/skills/archify/examples/release-delivery.workflow.json +57 -0
  56. package/skills/archify/examples/subscription-billing.erd.json +548 -0
  57. package/skills/archify/examples/web-app.architecture.json +41 -0
  58. package/skills/archify/explainer/browser-check.mjs +208 -0
  59. package/skills/archify/explainer/charts.mjs +70 -0
  60. package/skills/archify/explainer/check.mjs +167 -0
  61. package/skills/archify/explainer/diagrams.mjs +517 -0
  62. package/skills/archify/explainer/diff.mjs +124 -0
  63. package/skills/archify/explainer/inline.mjs +155 -0
  64. package/skills/archify/explainer/layout.mjs +35 -0
  65. package/skills/archify/explainer/page-bundle.mjs +16 -0
  66. package/skills/archify/explainer/parse.mjs +300 -0
  67. package/skills/archify/explainer/patch.mjs +117 -0
  68. package/skills/archify/explainer/prepare.mjs +131 -0
  69. package/skills/archify/explainer/reader.css +472 -0
  70. package/skills/archify/explainer/reader.js +666 -0
  71. package/skills/archify/explainer/render.mjs +224 -0
  72. package/skills/archify/explainer/revision.mjs +20 -0
  73. package/skills/archify/explainer/sources.mjs +318 -0
  74. package/skills/archify/explainer/validate.mjs +138 -0
  75. package/skills/archify/explainer/vendor/pele/LICENSE +40 -0
  76. package/skills/archify/explainer/vendor/pele/README.md +5 -0
  77. package/skills/archify/explainer/vendor/pele/chunks/3DKXF73K.js +4 -0
  78. package/skills/archify/explainer/vendor/pele/chunks/42UTT654.js +3 -0
  79. package/skills/archify/explainer/vendor/pele/chunks/DKTLEL5E.js +1 -0
  80. package/skills/archify/explainer/vendor/pele/chunks/EEIX5ZYH.js +2 -0
  81. package/skills/archify/explainer/vendor/pele/chunks/EJ5KOXYD.js +25 -0
  82. package/skills/archify/explainer/vendor/pele/chunks/GUJTEFZK.js +1 -0
  83. package/skills/archify/explainer/vendor/pele/chunks/IZOKQ2GT.js +4 -0
  84. package/skills/archify/explainer/vendor/pele/chunks/L4LY553T.js +3 -0
  85. package/skills/archify/explainer/vendor/pele/chunks/MSKIJHB2.js +2 -0
  86. package/skills/archify/explainer/vendor/pele/chunks/RVARI57O.js +1 -0
  87. package/skills/archify/explainer/vendor/pele/chunks/UKSIWDDN.js +2 -0
  88. package/skills/archify/explainer/vendor/pele/chunks/UPTXNAXN.js +2 -0
  89. package/skills/archify/explainer/vendor/pele/chunks/XTDUIGUI.js +9 -0
  90. package/skills/archify/explainer/vendor/pele/chunks/YAYTP6L5.js +9 -0
  91. package/skills/archify/explainer/vendor/pele/core.js +1 -0
  92. package/skills/archify/explainer/vendor/pele/diagrams/pie.js +1 -0
  93. package/skills/archify/explainer/vendor/pele/diagrams/quadrantChart.js +1 -0
  94. package/skills/archify/explainer/vendor/pele/diagrams/radar.js +1 -0
  95. package/skills/archify/explainer/vendor/pele/diagrams/sankey.js +1 -0
  96. package/skills/archify/explainer/vendor/pele/diagrams/venn.js +1 -0
  97. package/skills/archify/explainer/vendor/pele/diagrams/xychart.js +1 -0
  98. package/skills/archify/explainer/writing.mjs +139 -0
  99. package/skills/archify/locales/README.md +40 -0
  100. package/skills/archify/locales/ar.json +488 -0
  101. package/skills/archify/locales/en.json +488 -0
  102. package/skills/archify/locales/es.json +488 -0
  103. package/skills/archify/locales/ko.json +488 -0
  104. package/skills/archify/locales/manifest.json +10 -0
  105. package/skills/archify/locales/zh-CN.json +488 -0
  106. package/skills/archify/locales/zh-TW.json +488 -0
  107. package/skills/archify/migrations/workflow-v2.mjs +280 -0
  108. package/skills/archify/package.json +17 -0
  109. package/skills/archify/recipes/scenarios.mjs +455 -0
  110. package/skills/archify/references/architecture-layout-repair.md +18 -0
  111. package/skills/archify/references/authoring-contract.md +645 -0
  112. package/skills/archify/references/authoring-defaults.md +57 -0
  113. package/skills/archify/references/brand-marks.md +119 -0
  114. package/skills/archify/references/delivery-contract.md +665 -0
  115. package/skills/archify/references/explainer-authoring.md +274 -0
  116. package/skills/archify/references/repository-authoring.md +126 -0
  117. package/skills/archify/references/update-awareness.md +13 -0
  118. package/skills/archify/references/viewer-runtime.md +52 -0
  119. package/skills/archify/renderers/architecture/grid.mjs +62 -0
  120. package/skills/archify/renderers/architecture/labels.mjs +2 -0
  121. package/skills/archify/renderers/architecture/render-architecture.mjs +1204 -0
  122. package/skills/archify/renderers/architecture/routing.mjs +1469 -0
  123. package/skills/archify/renderers/class/README.md +130 -0
  124. package/skills/archify/renderers/class/render-class.mjs +1095 -0
  125. package/skills/archify/renderers/dataflow/README.md +176 -0
  126. package/skills/archify/renderers/dataflow/dataflow-compiler.mjs +1605 -0
  127. package/skills/archify/renderers/dataflow/joint-label-routing.mjs +165 -0
  128. package/skills/archify/renderers/dataflow/label-capacity.mjs +81 -0
  129. package/skills/archify/renderers/dataflow/render-dataflow.mjs +23 -0
  130. package/skills/archify/renderers/erd/README.md +246 -0
  131. package/skills/archify/renderers/erd/grid.mjs +150 -0
  132. package/skills/archify/renderers/erd/render-erd.mjs +1588 -0
  133. package/skills/archify/renderers/explainer/render-explainer.mjs +42 -0
  134. package/skills/archify/renderers/lifecycle/README.md +104 -0
  135. package/skills/archify/renderers/lifecycle/render-lifecycle.mjs +1134 -0
  136. package/skills/archify/renderers/sequence/README.md +146 -0
  137. package/skills/archify/renderers/sequence/render-sequence.mjs +1105 -0
  138. package/skills/archify/renderers/shared/atomic-output.mjs +1982 -0
  139. package/skills/archify/renderers/shared/automatic-labels.mjs +290 -0
  140. package/skills/archify/renderers/shared/brand-marks.mjs +706 -0
  141. package/skills/archify/renderers/shared/cli.mjs +430 -0
  142. package/skills/archify/renderers/shared/desktop-readability.mjs +132 -0
  143. package/skills/archify/renderers/shared/diagnostics.mjs +0 -0
  144. package/skills/archify/renderers/shared/engineering-profiles.mjs +157 -0
  145. package/skills/archify/renderers/shared/generated-brand-marks.mjs +2003 -0
  146. package/skills/archify/renderers/shared/generated-validators.mjs +279 -0
  147. package/skills/archify/renderers/shared/geometry.mjs +2073 -0
  148. package/skills/archify/renderers/shared/i18n.mjs +328 -0
  149. package/skills/archify/renderers/shared/layout-report.mjs +57 -0
  150. package/skills/archify/renderers/shared/legend.mjs +227 -0
  151. package/skills/archify/renderers/shared/node-card-style.mjs +32 -0
  152. package/skills/archify/renderers/shared/output-path.mjs +440 -0
  153. package/skills/archify/renderers/shared/owned-temp-directory.mjs +82 -0
  154. package/skills/archify/renderers/shared/path-semantics.mjs +1017 -0
  155. package/skills/archify/renderers/shared/portable-path.mjs +408 -0
  156. package/skills/archify/renderers/shared/repository-evidence.mjs +394 -0
  157. package/skills/archify/renderers/shared/repository-location.mjs +71 -0
  158. package/skills/archify/renderers/shared/route-quality.mjs +670 -0
  159. package/skills/archify/renderers/shared/sidecar-path.mjs +38 -0
  160. package/skills/archify/renderers/shared/software-notices.mjs +6 -0
  161. package/skills/archify/renderers/shared/spatial-grid.mjs +66 -0
  162. package/skills/archify/renderers/shared/svg-path-analysis.mjs +135 -0
  163. package/skills/archify/renderers/shared/text-fit.mjs +105 -0
  164. package/skills/archify/renderers/shared/utils.mjs +260 -0
  165. package/skills/archify/renderers/shared/validator.mjs +83 -0
  166. package/skills/archify/renderers/timeline/README.md +76 -0
  167. package/skills/archify/renderers/timeline/render-timeline.mjs +576 -0
  168. package/skills/archify/renderers/tree/README.md +96 -0
  169. package/skills/archify/renderers/tree/render-tree.mjs +573 -0
  170. package/skills/archify/renderers/waterfall/README.md +73 -0
  171. package/skills/archify/renderers/waterfall/render-waterfall.mjs +413 -0
  172. package/skills/archify/renderers/workflow/README.md +337 -0
  173. package/skills/archify/renderers/workflow/render-workflow.mjs +47 -0
  174. package/skills/archify/renderers/workflow/workflow-compiler.mjs +5920 -0
  175. package/skills/archify/renderers/workflow/workflow-migration-geometry.mjs +161 -0
  176. package/skills/archify/renderers/workflow/workflow-placement-repair.mjs +94 -0
  177. package/skills/archify/schemas/README.md +258 -0
  178. package/skills/archify/schemas/architecture.schema.json +152 -0
  179. package/skills/archify/schemas/class.schema.json +345 -0
  180. package/skills/archify/schemas/common.schema.json +181 -0
  181. package/skills/archify/schemas/dataflow.schema.json +254 -0
  182. package/skills/archify/schemas/erd.schema.json +381 -0
  183. package/skills/archify/schemas/explainer.schema.json +927 -0
  184. package/skills/archify/schemas/lifecycle.schema.json +179 -0
  185. package/skills/archify/schemas/sequence.schema.json +234 -0
  186. package/skills/archify/schemas/timeline.schema.json +160 -0
  187. package/skills/archify/schemas/tree.schema.json +141 -0
  188. package/skills/archify/schemas/waterfall.schema.json +147 -0
  189. package/skills/archify/schemas/workflow.schema.json +439 -0
  190. package/skills/archify/scripts/check-render-output.mjs +1469 -0
  191. package/skills/archify/scripts/check-update.mjs +1717 -0
  192. package/skills/archify/scripts/delivery-update-child.mjs +26 -0
  193. package/skills/archify/scripts/render-examples.mjs +36 -0
  194. package/skills/archify/scripts/update-contract.mjs +187 -0
  195. package/skills/archify/skill-release.json +10 -0
@@ -0,0 +1,2780 @@
1
+ import { softwareNoticesHtml } from '../renderers/shared/software-notices.mjs';
2
+ import { spawn } from 'node:child_process';
3
+ import { isExplainerHtml } from '../explainer/check.mjs';
4
+ import { EXPLAINER_VIEWPORTS, inspectExplainerBrowser, explainerObservation, explainerObservationDiagnostics } from '../explainer/browser-check.mjs';
5
+ import { createOwnedTempDirectory } from '../renderers/shared/owned-temp-directory.mjs';
6
+ import { createHash } from 'node:crypto';
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import { pathToFileURL } from 'node:url';
11
+ import {
12
+ DESKTOP_READABILITY_VIEWPORT,
13
+ MIN_PROJECTED_NODE_TEXT_PX,
14
+ } from '../renderers/shared/desktop-readability.mjs';
15
+ import {
16
+ backupPublicRegularFileBinding,
17
+ captureAtomicOutput,
18
+ captureRegularFileBinding,
19
+ quarantineRemoveLinkedRegularFileAlias,
20
+ quarantineRemoveRegularFileBinding,
21
+ releaseRegularFileBinding,
22
+ removeEmptyDirectoryWithRetry,
23
+ verifyAtomicOutput,
24
+ verifyRegularFileBinding,
25
+ } from '../renderers/shared/atomic-output.mjs';
26
+ import {
27
+ sameEntry,
28
+ sameLocation,
29
+ sameParent,
30
+ sidecarNamespaceComponentKey,
31
+ } from '../renderers/shared/path-semantics.mjs';
32
+ import {
33
+ boundedSidecarStem,
34
+ sidecarStemFromComponent,
35
+ } from '../renderers/shared/sidecar-path.mjs';
36
+
37
+ export const VISUAL_CHECK_VIEWPORTS = Object.freeze([
38
+ DESKTOP_READABILITY_VIEWPORT,
39
+ Object.freeze({ width: 1600, height: 1000 }),
40
+ Object.freeze({ width: 1920, height: 1080 }),
41
+ Object.freeze({ width: 2048, height: 1320 }),
42
+ ]);
43
+
44
+ export const CAPTURE_VIEWPORTS = Object.freeze([
45
+ VISUAL_CHECK_VIEWPORTS[0],
46
+ VISUAL_CHECK_VIEWPORTS[VISUAL_CHECK_VIEWPORTS.length - 1],
47
+ ]);
48
+ export const THEMES = Object.freeze(['light', 'dark']);
49
+ const EXIT = Object.freeze({ pass: 0, fail: 1, skipped: 2 });
50
+ export const CHROME_NO_SANDBOX_ENV = 'ARCHIFY_CHROME_NO_SANDBOX';
51
+ const VISUAL_SIDECAR_SUFFIXES = Object.freeze([
52
+ '.visual-check.json',
53
+ '.visual-check.html',
54
+ ...CAPTURE_VIEWPORTS.flatMap(({ width, height }) => THEMES.map(
55
+ (theme) => `.visual-check.${width}x${height}.${theme}.png`,
56
+ )),
57
+ ]);
58
+ const visualEvidenceOwnerships = new WeakSet();
59
+ export const CHROME_STARTUP_TIMEOUT_MS = 90000;
60
+
61
+ function sha256(buffer) {
62
+ return createHash('sha256').update(buffer).digest('hex');
63
+ }
64
+
65
+ function htmlEscape(value) {
66
+ return String(value).replace(/[&<>"']/g, (char) => ({
67
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
68
+ })[char]);
69
+ }
70
+
71
+ function pathEntry(file) {
72
+ try {
73
+ return { exists: true, stat: fs.lstatSync(file) };
74
+ } catch (error) {
75
+ if (error?.code === 'ENOENT') return { exists: false };
76
+ return { exists: null, error };
77
+ }
78
+ }
79
+
80
+ function visualEvidencePaths(outputs) {
81
+ return outputs.capture === false ? [] : [outputs.contactSheet, ...outputs.screenshots.map((entry) => entry.path)];
82
+ }
83
+
84
+ function regularFileEvidence(file, { expectedLinks = 1 } = {}) {
85
+ const captured = captureRegularFileBinding(file, {
86
+ subject: 'evidence-file',
87
+ expectedLinks,
88
+ });
89
+ if (captured.status !== 'captured') {
90
+ const systemCode = captured.reason?.systemCode;
91
+ return {
92
+ ok: false,
93
+ reason: systemCode === 'ENOENT'
94
+ ? { code: 'missing-evidence-file' }
95
+ : captured.reason?.code === 'evidence-file-not-regular-file'
96
+ ? { code: 'evidence-path-not-regular-file' }
97
+ : {
98
+ code: 'evidence-file-unreadable',
99
+ ...(systemCode ? { systemCode } : {}),
100
+ ...(captured.reason?.code ? { bindingCode: captured.reason.code } : {}),
101
+ },
102
+ };
103
+ }
104
+ const released = releaseRegularFileBinding(captured.binding);
105
+ if (released.status !== 'released') {
106
+ return {
107
+ ok: false,
108
+ reason: {
109
+ code: 'evidence-file-unreadable',
110
+ ...(released.reason?.systemCode ? { systemCode: released.reason.systemCode } : {}),
111
+ ...(released.reason?.code ? { bindingCode: released.reason.code } : {}),
112
+ },
113
+ };
114
+ }
115
+ return {
116
+ ok: true,
117
+ evidence: {
118
+ file: path.basename(file),
119
+ sha256: captured.content.sha256,
120
+ bytes: captured.content.bytes,
121
+ },
122
+ identity: captured.identity,
123
+ };
124
+ }
125
+
126
+ function readRegularFileContents(file, { subject = 'file' } = {}) {
127
+ const captured = captureRegularFileBinding(file, {
128
+ subject,
129
+ expectedLinks: 1,
130
+ includeContent: true,
131
+ });
132
+ if (captured.status !== 'captured') return { ok: false, reason: captured.reason };
133
+ const released = releaseRegularFileBinding(captured.binding);
134
+ if (released.status !== 'released') return { ok: false, reason: released.reason };
135
+ return {
136
+ ok: true,
137
+ bytes: captured.content.buffer,
138
+ evidence: {
139
+ sha256: captured.content.sha256,
140
+ bytes: captured.content.bytes,
141
+ },
142
+ identity: captured.identity,
143
+ };
144
+ }
145
+
146
+ function regularFileCaptureError(label, captured) {
147
+ const reason = captured?.reason || { code: 'regular-file-capture-failed' };
148
+ const error = new Error(`${label} could not be read safely (${reason.code}).`);
149
+ if (reason.systemCode) error.code = reason.systemCode;
150
+ error.evidenceReason = reason;
151
+ return error;
152
+ }
153
+
154
+ function screenshotKey(width, height, theme) {
155
+ return `${width}x${height}:${theme}`;
156
+ }
157
+
158
+ function resolvedSidecarNamespace(artifact, component) {
159
+ const namespace = sidecarNamespaceComponentKey(path.dirname(artifact), component);
160
+ if (namespace.status === 'resolved') return namespace;
161
+ const error = new Error(
162
+ `Could not establish a stable sidecar namespace (${namespace.reason?.code || 'unknown'}).`,
163
+ );
164
+ error.code = 'ARCHIFY_SIDECAR_NAMESPACE_INDETERMINATE';
165
+ error.sidecarNamespaceReason = namespace.reason;
166
+ throw error;
167
+ }
168
+
169
+ function portableSidecarComponentKey(component) {
170
+ return component
171
+ .normalize('NFC')
172
+ .toLocaleUpperCase('en-US')
173
+ .toLocaleLowerCase('en-US')
174
+ .normalize('NFC');
175
+ }
176
+
177
+ function targetSidecarNamespace(directory, component) {
178
+ const namespace = sidecarNamespaceComponentKey(directory, component);
179
+ if (namespace.status === 'resolved') return namespace.componentKey;
180
+ if (namespace.reason?.code === 'sidecar-directory-missing') {
181
+ // A pure path calculation must not create --out-dir. Use the portable
182
+ // collision envelope until the directory exists and can be probed.
183
+ return portableSidecarComponentKey(component);
184
+ }
185
+ const error = new Error(
186
+ `Could not establish target sidecar semantics (${namespace.reason?.code || 'unknown'}).`,
187
+ );
188
+ error.code = 'ARCHIFY_SIDECAR_NAMESPACE_INDETERMINATE';
189
+ error.sidecarNamespaceReason = namespace.reason;
190
+ throw error;
191
+ }
192
+
193
+ function evidenceSidecarPaths(artifactPath, { outDir, command = 'visual-check', capture = true, captureViewports = CAPTURE_VIEWPORTS } = {}) {
194
+ let artifact = path.resolve(artifactPath);
195
+ try {
196
+ // Existing aliases, including Windows 8.3 spellings, must share the
197
+ // physical artifact's evidence namespace even when the stem is short.
198
+ artifact = fs.realpathSync.native(artifact);
199
+ } catch (error) {
200
+ if (!['ENOENT', 'ENOTDIR', 'ENAMETOOLONG'].includes(error?.code)) throw error;
201
+ // Missing artifacts still need deterministic failure sidecar paths.
202
+ }
203
+ const namespace = resolvedSidecarNamespace(artifact, path.basename(artifact));
204
+ artifact = path.join(namespace.directoryPath, path.basename(artifact));
205
+ const namespaceStem = sidecarStemFromComponent(namespace.componentKey);
206
+ const directory = outDir ? path.resolve(outDir) : path.dirname(artifact);
207
+ const targetComponentKey = outDir
208
+ ? targetSidecarNamespace(directory, namespace.componentKey)
209
+ : namespace.componentKey;
210
+ const portableTargetKey = outDir
211
+ ? portableSidecarComponentKey(namespace.componentKey)
212
+ : namespace.componentKey;
213
+ const targetAliasesSourceSpelling = targetComponentKey !== namespace.componentKey
214
+ || portableTargetKey !== namespace.componentKey;
215
+ const stem = boundedSidecarStem(
216
+ namespaceStem.stem,
217
+ capture ? VISUAL_SIDECAR_SUFFIXES : ['.browser-check.json'],
218
+ targetAliasesSourceSpelling ? {
219
+ force: true,
220
+ hashDomain: `${command}-artifact\0${artifact}\0target-component\0${portableTargetKey}`,
221
+ } : namespaceStem.options,
222
+ );
223
+ const base = path.join(directory, `${stem}.${command}`);
224
+ const screenshots = (capture ? captureViewports : []).flatMap(({ width, height }) => THEMES.map((theme) => ({
225
+ width,
226
+ height,
227
+ theme,
228
+ path: `${base}.${width}x${height}.${theme}.png`,
229
+ })));
230
+ return {
231
+ base, command, capture,
232
+ receipt: `${base}.json`,
233
+ contactSheet: `${base}.html`,
234
+ screenshots,
235
+ };
236
+ }
237
+
238
+ export function sidecarPaths(artifactPath, options = {}) {
239
+ return evidenceSidecarPaths(artifactPath, options);
240
+ }
241
+
242
+ export function browserCheckSidecarPaths(artifactPath, options = {}) {
243
+ return evidenceSidecarPaths(artifactPath, { ...options, command: 'browser-check', capture: false });
244
+ }
245
+
246
+ function evidencePathConflict(artifactPath, outputs, file, reason) {
247
+ const target = file || outputs.receipt;
248
+ const error = `${outputs.command} will not replace the existing unowned evidence path "${target}".`;
249
+ return {
250
+ ok: false,
251
+ error,
252
+ diagnostic: failureDiagnostic({
253
+ code: 'viewer/evidence-path-conflict',
254
+ message: error,
255
+ subject: { artifact: path.resolve(artifactPath), evidencePath: target },
256
+ evidence: { reason },
257
+ supportedFixes: [
258
+ `move the conflicting file aside, or choose a separate --out-dir, then rerun ${outputs.command}`,
259
+ ],
260
+ }),
261
+ };
262
+ }
263
+
264
+ function visualEvidenceOwnershipMatches(ownership, artifactPath, outputs) {
265
+ return visualEvidenceOwnerships.has(ownership)
266
+ && ownership.active
267
+ && sameEntry(ownership.artifact, artifactPath).status === 'match'
268
+ && sameLocation(ownership.receipt, outputs.receipt).status === 'match';
269
+ }
270
+
271
+ function visualEvidenceTargets(outputs) {
272
+ return [
273
+ { kind: 'receipt', path: outputs.receipt },
274
+ ...(outputs.capture === false ? [] : [{ kind: 'contact-sheet', path: outputs.contactSheet }]),
275
+ ...outputs.screenshots.map((entry, index) => ({
276
+ kind: 'screenshot',
277
+ index,
278
+ path: entry.path,
279
+ })),
280
+ ];
281
+ }
282
+
283
+ function evidenceWriteFailure(artifactPath, message, errors) {
284
+ return {
285
+ ok: false,
286
+ error: message,
287
+ diagnostic: failureDiagnostic({
288
+ code: 'viewer/evidence-write',
289
+ message,
290
+ subject: { artifact: path.resolve(artifactPath) },
291
+ evidence: { errors },
292
+ supportedFixes: ['restore write access to the evidence directory and rerun visual-check'],
293
+ }),
294
+ };
295
+ }
296
+
297
+ function fileIdentity(stat) {
298
+ return {
299
+ device: stat.dev,
300
+ inode: stat.ino,
301
+ mode: Number(stat.mode & 0o777n),
302
+ links: stat.nlink,
303
+ };
304
+ }
305
+
306
+ function identityMatches(stat, identity, { directory = false } = {}) {
307
+ return stat.dev === identity.device
308
+ && stat.ino === identity.inode
309
+ && Number(stat.mode & 0o777n) === identity.mode
310
+ && (directory ? stat.isDirectory() : stat.isFile())
311
+ && !stat.isSymbolicLink();
312
+ }
313
+
314
+ function evidenceIdentityMatches(actual, expected, expectedLinks = expected?.links ?? 1) {
315
+ return actual?.device === expected?.device
316
+ && actual?.inode === expected?.inode
317
+ && actual?.mode === expected?.mode
318
+ && BigInt(actual?.links ?? 0) === BigInt(expectedLinks);
319
+ }
320
+
321
+ function stagedOutputs(outputs, stagingDirectory) {
322
+ return {
323
+ receipt: path.join(stagingDirectory, 'receipt.json'),
324
+ contactSheet: path.join(stagingDirectory, 'contact-sheet.html'),
325
+ screenshots: outputs.screenshots.map((entry, index) => ({
326
+ ...entry,
327
+ path: path.join(stagingDirectory, `capture-${index}.png`),
328
+ })),
329
+ };
330
+ }
331
+
332
+ function stagedPathFor(ownership, finalPath) {
333
+ return ownership.stagingPaths.get(finalPath);
334
+ }
335
+
336
+ function registerStagedEvidence(ownership, finalPath) {
337
+ const stagedPath = stagedPathFor(ownership, finalPath);
338
+ let stat;
339
+ try {
340
+ stat = fs.lstatSync(stagedPath, { bigint: true });
341
+ } catch (error) {
342
+ throw new Error(`visual-check could not inspect staged evidence "${stagedPath}": ${error.message}`);
343
+ }
344
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.ino === 0n) {
345
+ throw new Error(`visual-check staged evidence is not a uniquely owned regular file: "${stagedPath}".`);
346
+ }
347
+ if (stat.nlink !== 1n) {
348
+ ownership.stagedEntries.set(finalPath, {
349
+ path: stagedPath,
350
+ identity: fileIdentity(stat),
351
+ });
352
+ throw new Error(`visual-check staged evidence has an external hard link: "${stagedPath}".`);
353
+ }
354
+ const targetMode = ownership.targets.get(finalPath)?.mode;
355
+ if (targetMode !== null && targetMode !== undefined
356
+ && Number(stat.mode & 0o777n) !== targetMode) {
357
+ fs.chmodSync(stagedPath, targetMode);
358
+ const adjusted = fs.lstatSync(stagedPath, { bigint: true });
359
+ if (adjusted.dev !== stat.dev || adjusted.ino !== stat.ino || !adjusted.isFile()) {
360
+ throw new Error(`visual-check staged evidence changed while preserving its mode: "${stagedPath}".`);
361
+ }
362
+ stat = adjusted;
363
+ }
364
+ const entry = {
365
+ path: stagedPath,
366
+ identity: fileIdentity(stat),
367
+ };
368
+ ownership.stagedEntries.set(finalPath, entry);
369
+ const evidence = regularFileEvidence(stagedPath);
370
+ if (!evidence.ok || !evidenceIdentityMatches(evidence.identity, entry.identity)) {
371
+ throw new Error(`visual-check could not bind staged evidence "${stagedPath}" to its contents.`);
372
+ }
373
+ entry.evidence = {
374
+ sha256: evidence.evidence.sha256,
375
+ bytes: evidence.evidence.bytes,
376
+ };
377
+ }
378
+
379
+ function writeStagedEvidence(ownership, finalPath, contents) {
380
+ const stagedPath = stagedPathFor(ownership, finalPath);
381
+ const target = ownership.targets.get(finalPath);
382
+ const mode = target?.mode ?? 0o666;
383
+ let descriptor;
384
+ try {
385
+ descriptor = fs.openSync(stagedPath, 'wx', mode);
386
+ let stat = fs.fstatSync(descriptor, { bigint: true });
387
+ if (!stat.isFile() || stat.ino === 0n) {
388
+ throw new Error('the newly created staging entry has no unique regular-file identity');
389
+ }
390
+ if (target?.mode !== null && target?.mode !== undefined
391
+ && Number(stat.mode & 0o777n) !== target.mode) {
392
+ fs.fchmodSync(descriptor, target.mode);
393
+ const adjusted = fs.fstatSync(descriptor, { bigint: true });
394
+ if (adjusted.dev !== stat.dev || adjusted.ino !== stat.ino || !adjusted.isFile()
395
+ || Number(adjusted.mode & 0o777n) !== target.mode) {
396
+ throw new Error('the staged evidence mode could not be preserved');
397
+ }
398
+ stat = adjusted;
399
+ }
400
+ const entry = {
401
+ path: stagedPath,
402
+ identity: fileIdentity(stat),
403
+ };
404
+ ownership.stagedEntries.set(finalPath, entry);
405
+ if (stat.nlink !== 1n) {
406
+ throw new Error('the newly created staging entry has an external hard link');
407
+ }
408
+ fs.writeFileSync(descriptor, contents);
409
+ const bytes = Buffer.isBuffer(contents) ? contents : Buffer.from(contents);
410
+ entry.evidence = { sha256: sha256(bytes), bytes: bytes.byteLength };
411
+ } finally {
412
+ if (descriptor !== undefined) fs.closeSync(descriptor);
413
+ }
414
+ }
415
+
416
+ function unlinkOwnedEntry(file, identity, {
417
+ evidence,
418
+ expectedLinks,
419
+ } = {}) {
420
+ const verifiedLinks = Number(expectedLinks ?? identity.links ?? 1);
421
+ let captured = captureRegularFileBinding(file, {
422
+ subject: 'visual-cleanup',
423
+ expectedIdentity: identity,
424
+ expectedMode: identity.mode,
425
+ expectedLinks: verifiedLinks,
426
+ ...(evidence ? {
427
+ expectedSha256: evidence.sha256,
428
+ expectedBytes: evidence.bytes,
429
+ } : {}),
430
+ });
431
+ const reportedLinks = Number(captured.reason?.links);
432
+ if (captured.status === 'unsupported'
433
+ && captured.reason?.code === 'visual-cleanup-hardlinked'
434
+ && Number.isSafeInteger(reportedLinks)
435
+ && reportedLinks > verifiedLinks) {
436
+ captured = captureRegularFileBinding(file, {
437
+ subject: 'visual-cleanup',
438
+ expectedIdentity: identity,
439
+ expectedMode: identity.mode,
440
+ expectedLinks: reportedLinks,
441
+ ...(evidence ? {
442
+ expectedSha256: evidence.sha256,
443
+ expectedBytes: evidence.bytes,
444
+ } : {}),
445
+ });
446
+ }
447
+ if (captured.status !== 'captured') {
448
+ if (captured.reason?.systemCode === 'ENOENT') return { status: 'absent' };
449
+ return {
450
+ status: captured.status === 'different' || captured.status === 'unsupported'
451
+ ? 'different'
452
+ : 'unknown',
453
+ reason: captured.reason?.code?.includes('content-changed') ? 'content' : 'identity',
454
+ error: new Error(captured.reason?.code || 'visual cleanup binding failed'),
455
+ bindingState: captured.reason,
456
+ };
457
+ }
458
+ let removal;
459
+ let released;
460
+ try {
461
+ removal = quarantineRemoveRegularFileBinding(captured.binding, file, {
462
+ subject: 'visual-cleanup',
463
+ expectedLinks: captured.identity?.links ? Number(captured.identity.links) : verifiedLinks,
464
+ });
465
+ } finally {
466
+ released = releaseRegularFileBinding(captured.binding);
467
+ }
468
+ if (released.status !== 'released') {
469
+ return {
470
+ status: 'unknown',
471
+ reason: 'identity',
472
+ error: new Error(released.reason?.code || 'visual cleanup binding release failed'),
473
+ bindingState: released.reason,
474
+ };
475
+ }
476
+ if (removal.status === 'removed' || removal.status === 'absent') return removal;
477
+ return {
478
+ status: removal.status === 'preserved' || removal.status === 'different'
479
+ || removal.status === 'unsupported' ? 'different' : 'unknown',
480
+ reason: 'identity',
481
+ error: new Error(removal.reason?.code || 'visual cleanup quarantine failed'),
482
+ bindingState: removal.reason,
483
+ ...(removal.recoveryDirectory ? {
484
+ recoveryDirectory: removal.recoveryDirectory,
485
+ recoveryFile: removal.recoveryFile,
486
+ } : {}),
487
+ };
488
+ }
489
+
490
+ function backupOwnedPublishedEntry(file, backupPath, identity, evidence) {
491
+ const captured = captureRegularFileBinding(file, {
492
+ subject: 'previous-evidence',
493
+ expectedIdentity: identity,
494
+ expectedMode: identity.mode,
495
+ expectedSha256: evidence.sha256,
496
+ expectedBytes: evidence.bytes,
497
+ expectedLinks: 1,
498
+ });
499
+ if (captured.status !== 'captured') {
500
+ return { ...captured, backupCreated: false, backupVerified: false };
501
+ }
502
+ let backup;
503
+ let released;
504
+ try {
505
+ backup = backupPublicRegularFileBinding(captured.binding, file, backupPath, {
506
+ subject: 'previous-evidence',
507
+ });
508
+ } finally {
509
+ released = releaseRegularFileBinding(captured.binding);
510
+ }
511
+ if (released.status !== 'released') {
512
+ return {
513
+ status: 'recovery-required',
514
+ reason: {
515
+ code: 'previous-evidence-binding-release-failed',
516
+ bindingState: released.reason,
517
+ },
518
+ recoveryDirectory: backup?.recoveryDirectory || path.dirname(backupPath),
519
+ recoveryFile: backup?.recoveryFile || (backup?.backupCreated ? backupPath : undefined),
520
+ target: backup?.target || file,
521
+ backupCreated: backup?.backupCreated === true,
522
+ backupVerified: backup?.backupVerified === true,
523
+ };
524
+ }
525
+ return backup;
526
+ }
527
+
528
+ function publishedRemovalError(file, result) {
529
+ const code = result.reason?.code;
530
+ let reason;
531
+ if (result.status === 'preserved') {
532
+ reason = 'published entry changed during retirement; its successor was restored and preserved';
533
+ } else if (result.status === 'recovery-required') {
534
+ reason = 'published entry changed during retirement; recovery material was preserved';
535
+ } else if (code?.includes('content-changed')) {
536
+ reason = 'published entry content changed; it was preserved';
537
+ } else if (code?.includes('mode-changed')) {
538
+ reason = 'published entry mode changed; it was preserved';
539
+ } else if (result.status === 'different' || result.status === 'unsupported') {
540
+ reason = 'published entry identity changed; it was preserved';
541
+ } else {
542
+ reason = code || 'published entry could not be safely retired; it was preserved';
543
+ }
544
+ return {
545
+ file,
546
+ reason,
547
+ ...(code ? { code } : {}),
548
+ ...(result.recoveryDirectory ? { recoveryDirectory: result.recoveryDirectory } : {}),
549
+ ...(result.recoveryFile ? { recoveryFile: result.recoveryFile } : {}),
550
+ ...(result.target ? { target: result.target } : {}),
551
+ };
552
+ }
553
+
554
+ function cleanupStagedEvidence(ownership, { removeDirectory = false } = {}) {
555
+ const errors = [];
556
+ for (const [finalPath, entry] of [...ownership.stagedEntries]) {
557
+ const result = unlinkOwnedEntry(entry.path, entry.identity, { evidence: entry.evidence });
558
+ if (result.status === 'removed' || result.status === 'absent') {
559
+ ownership.stagedEntries.delete(finalPath);
560
+ } else {
561
+ errors.push({
562
+ file: entry.path,
563
+ reason: result.status === 'different' && result.reason === 'content'
564
+ ? 'staging entry content changed; it was preserved'
565
+ : result.status === 'different'
566
+ ? 'staging entry identity changed; it was preserved'
567
+ : result.error?.message,
568
+ });
569
+ }
570
+ }
571
+ const directories = [
572
+ ownership.inspection,
573
+ ...(removeDirectory ? [{
574
+ directory: ownership.stagingDirectory,
575
+ identity: ownership.stagingIdentity,
576
+ }] : []),
577
+ ].filter(Boolean);
578
+ for (const { directory, identity } of directories) {
579
+ try {
580
+ const stat = fs.lstatSync(directory, { bigint: true });
581
+ if (!identity || !identityMatches(stat, identity, { directory: true })) {
582
+ errors.push({
583
+ file: directory,
584
+ recoveryDirectory: directory,
585
+ reason: 'staging directory identity changed; it was preserved',
586
+ });
587
+ } else {
588
+ removeEmptyDirectoryWithRetry(directory);
589
+ }
590
+ } catch (error) {
591
+ if (error?.code !== 'ENOENT') {
592
+ errors.push({ file: directory, recoveryDirectory: directory, reason: error.message });
593
+ }
594
+ }
595
+ }
596
+ return errors;
597
+ }
598
+
599
+ function verifyVisualEvidenceTargets(artifactPath, outputs, ownership) {
600
+ for (const target of visualEvidenceTargets(outputs)) {
601
+ const captured = ownership.targets.get(target.path);
602
+ const verification = captured ? verifyAtomicOutput(captured.snapshot) : {
603
+ status: 'unknown',
604
+ reason: { code: 'evidence-snapshot-missing' },
605
+ };
606
+ if (verification.status !== 'match') {
607
+ return evidencePathConflict(artifactPath, outputs, target.path, verification.reason);
608
+ }
609
+ }
610
+ return { ok: true };
611
+ }
612
+
613
+ function beginVisualEvidenceWrite(artifactPath, artifactBytes, outputs) {
614
+ const targets = visualEvidenceTargets(outputs);
615
+ const candidates = targets.map((target) => target.path);
616
+ const previousEvidence = new Map();
617
+ try {
618
+ fs.mkdirSync(path.dirname(outputs.receipt), { recursive: true });
619
+ } catch (error) {
620
+ return evidenceWriteFailure(
621
+ artifactPath,
622
+ 'visual-check could not create its evidence directory.',
623
+ [{ file: path.dirname(outputs.receipt), reason: error.message }],
624
+ );
625
+ }
626
+
627
+ const capturedTargets = new Map();
628
+ for (const target of targets) {
629
+ const captured = captureAtomicOutput(target.path, {
630
+ requestedEntryPolicy: 'regular-or-absent',
631
+ });
632
+ if (captured.status !== 'captured') {
633
+ return evidencePathConflict(artifactPath, outputs, target.path, captured.reason);
634
+ }
635
+ capturedTargets.set(target.path, captured);
636
+ }
637
+
638
+ const parent = capturedTargets.get(outputs.receipt).snapshot.slot;
639
+ for (const target of targets.slice(1)) {
640
+ const slot = capturedTargets.get(target.path).snapshot.slot;
641
+ if (slot.parentDevice !== parent.parentDevice || slot.parentInode !== parent.parentInode) {
642
+ return evidencePathConflict(artifactPath, outputs, target.path, {
643
+ code: 'evidence-parent-mismatch',
644
+ });
645
+ }
646
+ }
647
+
648
+ const existing = candidates.filter((file) => (
649
+ capturedTargets.get(file).snapshot.requestedEntry.kind === 'existing'
650
+ ));
651
+ if (existing.length) {
652
+ const receiptEntry = capturedTargets.get(outputs.receipt).snapshot.requestedEntry;
653
+ if (receiptEntry.kind !== 'existing') {
654
+ return evidencePathConflict(artifactPath, outputs, existing[0], {
655
+ code: 'ownership-receipt-missing',
656
+ });
657
+ }
658
+
659
+ const previousReceipt = readRegularFileContents(outputs.receipt, {
660
+ subject: 'ownership-receipt',
661
+ });
662
+ const capturedReceipt = capturedTargets.get(outputs.receipt).snapshot.target;
663
+ if (!previousReceipt.ok || !evidenceIdentityMatches(previousReceipt.identity, {
664
+ device: capturedReceipt.device,
665
+ inode: capturedReceipt.inode,
666
+ mode: capturedReceipt.mode,
667
+ links: 1,
668
+ })) {
669
+ return evidencePathConflict(artifactPath, outputs, outputs.receipt, {
670
+ code: 'ownership-receipt-invalid',
671
+ ...(previousReceipt.reason?.code ? { bindingCode: previousReceipt.reason.code } : {}),
672
+ ...(previousReceipt.reason?.systemCode
673
+ ? { systemCode: previousReceipt.reason.systemCode } : {}),
674
+ });
675
+ }
676
+ const previousBytes = previousReceipt.bytes;
677
+ let previous;
678
+ try {
679
+ previous = JSON.parse(previousBytes.toString('utf8'));
680
+ } catch (error) {
681
+ return evidencePathConflict(artifactPath, outputs, outputs.receipt, {
682
+ code: 'ownership-receipt-invalid',
683
+ ...(error?.code ? { systemCode: error.code } : {}),
684
+ });
685
+ }
686
+ previousEvidence.set(outputs.receipt, {
687
+ ...previousReceipt.evidence,
688
+ });
689
+
690
+ if (previous?.schemaVersion !== 1 || previous?.command !== outputs.command) {
691
+ return evidencePathConflict(artifactPath, outputs, outputs.receipt, {
692
+ code: 'ownership-receipt-schema-mismatch',
693
+ });
694
+ }
695
+ const recordedReceiptName = previous?.sidecars?.receipt;
696
+ const recordedContactName = previous?.sidecars?.contactSheet;
697
+ const recordedDirectory = previous?.sidecars?.directory || path.dirname(previous?.artifact?.path || '');
698
+ const receiptNameSafe = typeof recordedReceiptName === 'string'
699
+ // path-contract-allow: portable-logical-path -- receipt filenames are serialized logical basenames.
700
+ && path.basename(recordedReceiptName) === recordedReceiptName;
701
+ const contactNameSafe = outputs.capture === false || typeof recordedContactName === 'string'
702
+ // path-contract-allow: portable-logical-path -- contact-sheet filenames are serialized logical basenames.
703
+ && path.basename(recordedContactName) === recordedContactName;
704
+ if (!path.isAbsolute(recordedDirectory) || !receiptNameSafe || !contactNameSafe
705
+ || sameLocation(path.join(recordedDirectory, recordedReceiptName), outputs.receipt).status !== 'match'
706
+ || (outputs.capture !== false && sameLocation(path.join(recordedDirectory, recordedContactName), outputs.contactSheet).status !== 'match')) {
707
+ return evidencePathConflict(artifactPath, outputs, outputs.receipt, {
708
+ code: 'ownership-sidecar-path-mismatch',
709
+ });
710
+ }
711
+ if (typeof previous?.artifact?.path !== 'string'
712
+ || !path.isAbsolute(previous.artifact.path)
713
+ || sameEntry(previous.artifact.path, artifactPath).status !== 'match'
714
+ || previous.artifact.sha256 !== sha256(artifactBytes)
715
+ || previous.artifact.bytes !== artifactBytes.byteLength) {
716
+ return evidencePathConflict(artifactPath, outputs, outputs.receipt, {
717
+ code: 'ownership-artifact-mismatch',
718
+ });
719
+ }
720
+
721
+ const existingEvidence = visualEvidencePaths(outputs).filter((file) => (
722
+ capturedTargets.get(file).snapshot.requestedEntry.kind === 'existing'
723
+ ));
724
+ const recordedEvidence = previous?.sidecars?.files;
725
+ if (existingEvidence.length && !Array.isArray(recordedEvidence)) {
726
+ return evidencePathConflict(artifactPath, outputs, existingEvidence[0], {
727
+ code: 'ownership-evidence-digests-missing',
728
+ });
729
+ }
730
+ if (Array.isArray(recordedEvidence)) {
731
+ const allowed = new Map(visualEvidencePaths(outputs).map((file) => [path.basename(file), file]));
732
+ const recorded = new Map();
733
+ for (const item of recordedEvidence) {
734
+ if (!item || typeof item.file !== 'string' || recorded.has(item.file) || !allowed.has(item.file)) {
735
+ return evidencePathConflict(artifactPath, outputs, outputs.receipt, {
736
+ code: 'ownership-evidence-list-invalid',
737
+ });
738
+ }
739
+ recorded.set(item.file, item);
740
+ }
741
+ if (recorded.size !== existingEvidence.length
742
+ || existingEvidence.some((file) => !recorded.has(path.basename(file)))) {
743
+ return evidencePathConflict(artifactPath, outputs, outputs.receipt, {
744
+ code: 'ownership-evidence-list-mismatch',
745
+ });
746
+ }
747
+ for (const file of existingEvidence) {
748
+ const actual = regularFileEvidence(file);
749
+ const expected = recorded.get(path.basename(file));
750
+ if (!actual.ok
751
+ || actual.evidence.sha256 !== expected.sha256
752
+ || actual.evidence.bytes !== expected.bytes) {
753
+ return evidencePathConflict(artifactPath, outputs, file, {
754
+ code: actual.ok ? 'ownership-evidence-digest-mismatch' : actual.reason.code,
755
+ ...(!actual.ok && actual.reason.systemCode
756
+ ? { systemCode: actual.reason.systemCode } : {}),
757
+ });
758
+ }
759
+ previousEvidence.set(file, {
760
+ sha256: actual.evidence.sha256,
761
+ bytes: actual.evidence.bytes,
762
+ });
763
+ }
764
+ }
765
+
766
+ }
767
+
768
+ for (const target of targets) {
769
+ const verification = verifyAtomicOutput(capturedTargets.get(target.path).snapshot);
770
+ if (verification.status !== 'match') {
771
+ return evidencePathConflict(artifactPath, outputs, target.path, verification.reason);
772
+ }
773
+ }
774
+
775
+ let stagingDirectory;
776
+ let stagingStat;
777
+ try {
778
+ stagingDirectory = fs.mkdtempSync(path.toNamespacedPath(
779
+ path.join(parent.parentPath, '.archify-visual-check-'),
780
+ ));
781
+ stagingStat = fs.lstatSync(stagingDirectory, { bigint: true });
782
+ if (!stagingStat.isDirectory() || stagingStat.isSymbolicLink() || stagingStat.ino === 0n) {
783
+ throw new Error('the newly created staging directory has no stable directory identity');
784
+ }
785
+ } catch (error) {
786
+ return evidenceWriteFailure(
787
+ artifactPath,
788
+ 'visual-check could not create a private evidence staging directory.',
789
+ [{ file: parent.parentPath, reason: error.message }],
790
+ );
791
+ }
792
+
793
+ const staged = stagedOutputs(outputs, stagingDirectory);
794
+ const ownership = {
795
+ active: true,
796
+ artifact: path.resolve(artifactPath),
797
+ receipt: outputs.receipt,
798
+ targets: capturedTargets,
799
+ stagingDirectory,
800
+ stagingIdentity: fileIdentity(stagingStat),
801
+ stagedOutputs: staged,
802
+ stagingPaths: new Map([
803
+ [outputs.receipt, staged.receipt],
804
+ [outputs.contactSheet, staged.contactSheet],
805
+ ...outputs.screenshots.map((entry, index) => [entry.path, staged.screenshots[index].path]),
806
+ ]),
807
+ stagedEntries: new Map(),
808
+ previousEvidence,
809
+ };
810
+ visualEvidenceOwnerships.add(ownership);
811
+ return { ok: true, ownership };
812
+ }
813
+
814
+ function recordVisualEvidenceFiles(receipt, outputs, ownership) {
815
+ const files = [];
816
+ for (const file of visualEvidencePaths(outputs)) {
817
+ const staged = ownership.stagedEntries.get(file);
818
+ if (!staged || !currentEvidenceMatches(staged.path, staged.identity, staged.evidence)) {
819
+ const error = new Error(`visual-check could not bind evidence file "${file}" to its receipt.`);
820
+ error.evidenceReason = { code: 'staged-evidence-content-mismatch' };
821
+ throw error;
822
+ }
823
+ files.push({ ...staged.evidence, file: path.basename(file) });
824
+ }
825
+ receipt.sidecars.files = files;
826
+ }
827
+
828
+ function currentEvidenceMatches(file, identity, evidence, {
829
+ expectedLinks = identity.links ?? 1,
830
+ } = {}) {
831
+ if (!evidence) return false;
832
+ const current = regularFileEvidence(file, { expectedLinks: Number(expectedLinks) });
833
+ return current.ok
834
+ && evidenceIdentityMatches(current.identity, identity, expectedLinks)
835
+ && current.evidence.sha256 === evidence.sha256
836
+ && current.evidence.bytes === evidence.bytes;
837
+ }
838
+
839
+ function restoreOwnedBackup(backup, errors) {
840
+ const expectedLinks = backup.identity.links ?? 1n;
841
+ const expectedLinkCount = Number(expectedLinks);
842
+ let backupStat;
843
+ try {
844
+ backupStat = fs.lstatSync(backup.path, { bigint: true });
845
+ } catch {
846
+ errors.push({ file: backup.path, reason: 'backup identity changed; it was preserved' });
847
+ return;
848
+ }
849
+ if (!identityMatches(backupStat, backup.identity) || backupStat.nlink !== expectedLinks) {
850
+ errors.push({ file: backup.path, reason: 'backup identity changed; it was preserved' });
851
+ return;
852
+ }
853
+ let captured = backup.evidence && Number.isSafeInteger(expectedLinkCount)
854
+ ? captureRegularFileBinding(backup.path, {
855
+ subject: 'restore-backup',
856
+ expectedIdentity: backup.identity,
857
+ expectedMode: backup.identity.mode,
858
+ expectedSha256: backup.evidence.sha256,
859
+ expectedBytes: backup.evidence.bytes,
860
+ expectedLinks: expectedLinkCount,
861
+ })
862
+ : { status: 'unknown', reason: { code: 'restore-backup-evidence-unavailable' } };
863
+ let contentChanged = false;
864
+ if (captured.status !== 'captured'
865
+ && captured.reason?.code === 'restore-backup-content-changed') {
866
+ captured = captureRegularFileBinding(backup.path, {
867
+ subject: 'restore-backup-claimant',
868
+ expectedIdentity: backup.identity,
869
+ expectedMode: backup.identity.mode,
870
+ expectedLinks: expectedLinkCount,
871
+ });
872
+ contentChanged = captured.status === 'captured';
873
+ }
874
+ if (captured.status !== 'captured') {
875
+ errors.push({
876
+ file: backup.path,
877
+ reason: 'backup bytes, mode, or identity changed; it was preserved',
878
+ ...(captured.reason?.code ? { code: captured.reason.code } : {}),
879
+ });
880
+ return;
881
+ }
882
+ let released;
883
+ try {
884
+ const finalEntry = pathEntry(backup.finalPath);
885
+ if (finalEntry.exists === true) {
886
+ errors.push({
887
+ file: backup.path,
888
+ reason: 'final path is occupied; the owned backup was preserved',
889
+ });
890
+ return;
891
+ }
892
+ if (finalEntry.exists === null) {
893
+ errors.push({ file: backup.finalPath, reason: finalEntry.error?.message });
894
+ return;
895
+ }
896
+ try {
897
+ fs.linkSync(backup.path, backup.finalPath);
898
+ const linkedCount = expectedLinkCount + 1;
899
+ const staged = verifyRegularFileBinding(captured.binding, {
900
+ filePath: backup.path,
901
+ expectedLinks: linkedCount,
902
+ });
903
+ const published = verifyRegularFileBinding(captured.binding, {
904
+ filePath: backup.finalPath,
905
+ expectedLinks: linkedCount,
906
+ });
907
+ if (staged.status !== 'match' || published.status !== 'match') {
908
+ const removed = quarantineRemoveRegularFileBinding(
909
+ captured.binding,
910
+ backup.finalPath,
911
+ { subject: 'restored-evidence', expectedLinks: linkedCount },
912
+ );
913
+ errors.push({
914
+ file: backup.path,
915
+ reason: removed.status === 'removed'
916
+ ? 'restored entry identity could not be verified; the owned backup was preserved'
917
+ : removed.status === 'preserved'
918
+ ? 'restored entry changed during cleanup; its successor and the owned backup were preserved'
919
+ : 'restored entry changed before rollback; both entries were preserved',
920
+ ...(removed.reason?.code ? { code: removed.reason.code } : {}),
921
+ ...(removed.recoveryDirectory ? { recoveryDirectory: removed.recoveryDirectory } : {}),
922
+ ...(removed.recoveryFile ? { recoveryFile: removed.recoveryFile } : {}),
923
+ });
924
+ return;
925
+ }
926
+ const removed = unlinkOwnedEntry(backup.path, backup.identity, {
927
+ evidence: captured.content,
928
+ expectedLinks: linkedCount,
929
+ });
930
+ const finalMatches = verifyRegularFileBinding(captured.binding, {
931
+ filePath: backup.finalPath,
932
+ expectedLinks: expectedLinkCount,
933
+ }).status === 'match';
934
+ if (removed.status !== 'removed' || !finalMatches) {
935
+ errors.push({ file: backup.path, reason: 'restored entry link count could not be finalized' });
936
+ } else if (contentChanged) {
937
+ errors.push({
938
+ file: backup.finalPath,
939
+ reason: 'the backup content changed externally; its current bytes were restored and preserved',
940
+ });
941
+ }
942
+ } catch (error) {
943
+ errors.push({
944
+ file: backup.path,
945
+ reason: error?.code === 'EEXIST'
946
+ ? 'final path was claimed during restore; the owned backup was preserved'
947
+ : error.message,
948
+ });
949
+ }
950
+ } finally {
951
+ released = releaseRegularFileBinding(captured.binding);
952
+ if (released.status !== 'released') {
953
+ errors.push({
954
+ file: backup.path,
955
+ reason: 'restored backup binding could not be released cleanly',
956
+ ...(released.reason?.code ? { code: released.reason.code } : {}),
957
+ });
958
+ }
959
+ }
960
+ }
961
+
962
+ function commitVisualEvidence(artifactPath, outputs, ownership, desiredPaths) {
963
+ const verification = verifyVisualEvidenceTargets(artifactPath, outputs, ownership);
964
+ if (!verification.ok) {
965
+ const cleanupErrors = cleanupStagedEvidence(ownership, { removeDirectory: true });
966
+ if (cleanupErrors.length) verification.diagnostic.evidence.rollbackErrors = cleanupErrors;
967
+ ownership.active = false;
968
+ return verification;
969
+ }
970
+
971
+ const desired = new Set(desiredPaths);
972
+ const stagedBindings = new Map();
973
+ const releaseStagedBindings = () => {
974
+ const failures = [];
975
+ for (const [finalPath, binding] of stagedBindings) {
976
+ const released = releaseRegularFileBinding(binding);
977
+ if (released.status !== 'released') {
978
+ failures.push({
979
+ file: finalPath,
980
+ reason: released.reason?.code,
981
+ bindingState: released.reason,
982
+ ...(released.reason?.recoveryDirectory
983
+ ? { recoveryDirectory: released.reason.recoveryDirectory } : {}),
984
+ });
985
+ }
986
+ }
987
+ stagedBindings.clear();
988
+ return failures;
989
+ };
990
+ for (const finalPath of desired) {
991
+ const staged = ownership.stagedEntries.get(finalPath);
992
+ const captured = staged ? captureRegularFileBinding(staged.path, {
993
+ subject: 'staged-evidence',
994
+ expectedIdentity: staged.identity,
995
+ expectedMode: staged.identity.mode,
996
+ expectedSha256: staged.evidence?.sha256,
997
+ expectedBytes: staged.evidence?.bytes,
998
+ expectedLinks: 1,
999
+ }) : null;
1000
+ if (!staged || captured?.status !== 'captured') {
1001
+ const failure = evidenceWriteFailure(
1002
+ artifactPath,
1003
+ 'visual-check could not verify its staged evidence before publication.',
1004
+ [{
1005
+ file: staged?.path || stagedPathFor(ownership, finalPath),
1006
+ reason: captured?.reason?.code || 'staged entry missing or changed',
1007
+ }],
1008
+ );
1009
+ failure.diagnostic.evidence.errors.push(
1010
+ ...releaseStagedBindings(),
1011
+ ...cleanupStagedEvidence(ownership, { removeDirectory: true }),
1012
+ );
1013
+ ownership.active = false;
1014
+ return failure;
1015
+ }
1016
+ stagedBindings.set(finalPath, captured.binding);
1017
+ }
1018
+
1019
+ const backups = [];
1020
+ const published = [];
1021
+ let conflict = null;
1022
+ try {
1023
+ for (const [index, target] of visualEvidenceTargets(outputs).entries()) {
1024
+ const captured = ownership.targets.get(target.path);
1025
+ if (captured.snapshot.target.kind !== 'file') continue;
1026
+ const backupPath = path.join(ownership.stagingDirectory, `previous-${index}`);
1027
+ const identity = {
1028
+ device: captured.snapshot.target.device,
1029
+ inode: captured.snapshot.target.inode,
1030
+ mode: captured.snapshot.target.mode,
1031
+ links: 1n,
1032
+ };
1033
+ const evidence = ownership.previousEvidence.get(target.path);
1034
+ if (!evidence) {
1035
+ conflict = evidencePathConflict(artifactPath, outputs, target.path, {
1036
+ code: 'target-evidence-missing-during-commit',
1037
+ });
1038
+ throw new Error(conflict.error);
1039
+ }
1040
+ const backup = {
1041
+ targetPath: target.path,
1042
+ finalPath: captured.commitPath,
1043
+ path: backupPath,
1044
+ identity,
1045
+ evidence,
1046
+ };
1047
+ const backupResult = backupOwnedPublishedEntry(
1048
+ captured.commitPath,
1049
+ backupPath,
1050
+ identity,
1051
+ evidence,
1052
+ );
1053
+ if (backupResult.backupCreated) backups.push(backup);
1054
+ if (backupResult.status !== 'backed-up'
1055
+ || !backupResult.backupCreated
1056
+ || !backupResult.backupVerified) {
1057
+ conflict = evidencePathConflict(artifactPath, outputs, target.path, {
1058
+ code: backupResult.reason?.code || 'target-backup-failed-during-commit',
1059
+ backupCreated: backupResult.backupCreated === true,
1060
+ backupVerified: backupResult.backupVerified === true,
1061
+ ...(backupResult.recoveryDirectory
1062
+ ? { recoveryDirectory: backupResult.recoveryDirectory } : {}),
1063
+ ...(backupResult.recoveryFile ? { recoveryFile: backupResult.recoveryFile } : {}),
1064
+ ...(backupResult.target ? { target: backupResult.target } : {}),
1065
+ ...(backupResult.reason ? { bindingState: backupResult.reason } : {}),
1066
+ });
1067
+ throw new Error(conflict.error);
1068
+ }
1069
+ }
1070
+
1071
+ const publicationOrder = visualEvidenceTargets(outputs)
1072
+ .filter((target) => desired.has(target.path))
1073
+ .sort((left, right) => Number(left.kind === 'receipt') - Number(right.kind === 'receipt'));
1074
+ for (const target of publicationOrder) {
1075
+ const captured = ownership.targets.get(target.path);
1076
+ const staged = ownership.stagedEntries.get(target.path);
1077
+ const stagedBinding = stagedBindings.get(target.path);
1078
+ const beforeLink = verifyRegularFileBinding(stagedBinding, {
1079
+ filePath: staged.path,
1080
+ expectedLinks: 1,
1081
+ });
1082
+ if (beforeLink.status !== 'match') {
1083
+ conflict = evidencePathConflict(artifactPath, outputs, target.path, {
1084
+ code: beforeLink.reason?.code?.includes('content-changed')
1085
+ ? 'staged-evidence-content-mismatch'
1086
+ : beforeLink.reason?.code || 'staged-evidence-content-mismatch',
1087
+ });
1088
+ throw new Error(conflict.error);
1089
+ }
1090
+ try {
1091
+ fs.linkSync(staged.path, captured.commitPath);
1092
+ } catch (error) {
1093
+ if (error?.code === 'EEXIST') {
1094
+ conflict = evidencePathConflict(artifactPath, outputs, target.path, {
1095
+ code: 'target-created-during-commit',
1096
+ });
1097
+ }
1098
+ throw error;
1099
+ }
1100
+ published.push({
1101
+ finalPath: captured.commitPath,
1102
+ stagedPath: staged.path,
1103
+ identity: staged.identity,
1104
+ evidence: staged.evidence,
1105
+ binding: stagedBinding,
1106
+ });
1107
+ const stagedLinked = verifyRegularFileBinding(stagedBinding, {
1108
+ filePath: staged.path,
1109
+ expectedLinks: 2,
1110
+ });
1111
+ const publishedLinked = verifyRegularFileBinding(stagedBinding, {
1112
+ filePath: captured.commitPath,
1113
+ expectedLinks: 2,
1114
+ });
1115
+ if (stagedLinked.status !== 'match' || publishedLinked.status !== 'match') {
1116
+ conflict = evidencePathConflict(artifactPath, outputs, target.path, {
1117
+ code: 'published-entry-identity-mismatch',
1118
+ stagedState: stagedLinked.reason,
1119
+ publishedState: publishedLinked.reason,
1120
+ });
1121
+ throw new Error(conflict.error);
1122
+ }
1123
+ const removed = quarantineRemoveRegularFileBinding(stagedBinding, staged.path, {
1124
+ subject: 'staged-evidence',
1125
+ expectedLinks: 2,
1126
+ });
1127
+ if (removed.status !== 'removed' && removed.status !== 'preserved') {
1128
+ conflict = evidencePathConflict(artifactPath, outputs, target.path, {
1129
+ code: removed.reason?.code || 'published-entry-identity-mismatch',
1130
+ });
1131
+ throw new Error(`visual-check could not retire staged evidence "${staged.path}".`);
1132
+ }
1133
+ if (removed.status === 'removed') ownership.stagedEntries.delete(target.path);
1134
+ const finalized = verifyRegularFileBinding(stagedBinding, {
1135
+ filePath: captured.commitPath,
1136
+ expectedLinks: 1,
1137
+ });
1138
+ if (finalized.status !== 'match') {
1139
+ conflict = evidencePathConflict(artifactPath, outputs, target.path, {
1140
+ code: 'published-entry-link-count-mismatch',
1141
+ bindingState: finalized.reason,
1142
+ });
1143
+ throw new Error(conflict.error);
1144
+ }
1145
+ }
1146
+
1147
+ // Receipt publication is the linearization point for the evidence set.
1148
+ // Recheck every earlier member afterwards so a writer that replaces a PNG
1149
+ // or the contact sheet while later members publish cannot yield success.
1150
+ for (const entry of published) {
1151
+ const finalState = verifyRegularFileBinding(entry.binding, {
1152
+ filePath: entry.finalPath,
1153
+ expectedLinks: 1,
1154
+ });
1155
+ if (finalState.status !== 'match') {
1156
+ conflict = evidencePathConflict(artifactPath, outputs, entry.finalPath, {
1157
+ code: 'published-set-identity-mismatch',
1158
+ bindingState: finalState.reason,
1159
+ });
1160
+ throw new Error(conflict.error);
1161
+ }
1162
+ }
1163
+
1164
+ for (const backup of backups) {
1165
+ if (!currentEvidenceMatches(
1166
+ backup.path,
1167
+ backup.identity,
1168
+ ownership.previousEvidence.get(backup.targetPath),
1169
+ )) {
1170
+ conflict = evidencePathConflict(artifactPath, outputs, backup.targetPath, {
1171
+ code: 'backup-content-changed-before-cleanup',
1172
+ });
1173
+ throw new Error(conflict.error);
1174
+ }
1175
+ }
1176
+
1177
+ // SMB keeps removed staging names pending until every bound handle closes.
1178
+ // Publication and backup verification are complete before directory cleanup.
1179
+ const cleanupErrors = releaseStagedBindings();
1180
+ for (const backup of backups) {
1181
+ const removed = unlinkOwnedEntry(backup.path, backup.identity, {
1182
+ evidence: backup.evidence,
1183
+ });
1184
+ if (removed.status !== 'removed' && removed.status !== 'absent') {
1185
+ cleanupErrors.push({
1186
+ file: backup.path,
1187
+ reason: removed.status === 'different' && removed.reason === 'content'
1188
+ ? 'backup content changed; it was preserved'
1189
+ : removed.status === 'different'
1190
+ ? 'backup identity changed; it was preserved'
1191
+ : removed.error?.message,
1192
+ });
1193
+ }
1194
+ }
1195
+ cleanupErrors.push(...cleanupStagedEvidence(ownership, { removeDirectory: true }));
1196
+ ownership.active = false;
1197
+ let recoveryDirectory;
1198
+ if (cleanupErrors.length) {
1199
+ try {
1200
+ const retained = fs.lstatSync(ownership.stagingDirectory, { bigint: true });
1201
+ if (identityMatches(retained, ownership.stagingIdentity, { directory: true })) {
1202
+ recoveryDirectory = ownership.stagingDirectory;
1203
+ }
1204
+ } catch {}
1205
+ recoveryDirectory ||= cleanupErrors.find((entry) => entry.recoveryDirectory)?.recoveryDirectory;
1206
+ }
1207
+ return {
1208
+ ok: true,
1209
+ status: cleanupErrors.length ? 'committed-with-warning' : 'committed',
1210
+ cleanupErrors,
1211
+ ...(recoveryDirectory ? { recoveryDirectory } : {}),
1212
+ committedReceipt: outputs.receipt,
1213
+ };
1214
+ } catch (error) {
1215
+ const rollbackErrors = [];
1216
+ for (const entry of [...published].reverse()) {
1217
+ let removed;
1218
+ let ownedMismatch;
1219
+ for (const expectedLinks of [2, 1]) {
1220
+ const matches = verifyRegularFileBinding(entry.binding, {
1221
+ filePath: entry.finalPath,
1222
+ expectedLinks,
1223
+ });
1224
+ if (matches.status === 'match') {
1225
+ removed = quarantineRemoveRegularFileBinding(
1226
+ entry.binding,
1227
+ entry.finalPath,
1228
+ { subject: 'published-evidence', expectedLinks },
1229
+ );
1230
+ break;
1231
+ }
1232
+ if (matches.reason?.code?.includes('content-changed')
1233
+ || matches.reason?.code?.includes('mode-changed')) {
1234
+ ownedMismatch = matches;
1235
+ } else {
1236
+ ownedMismatch ||= matches;
1237
+ }
1238
+ const reportedLinks = Number(matches.reason?.links);
1239
+ if (matches.status === 'unsupported'
1240
+ && matches.reason?.code === 'staged-evidence-hardlinked'
1241
+ && Number.isSafeInteger(reportedLinks)
1242
+ && reportedLinks > expectedLinks) {
1243
+ const current = verifyRegularFileBinding(entry.binding, {
1244
+ filePath: entry.finalPath,
1245
+ expectedLinks: reportedLinks,
1246
+ });
1247
+ if (current.status === 'match') {
1248
+ removed = quarantineRemoveRegularFileBinding(
1249
+ entry.binding,
1250
+ entry.finalPath,
1251
+ { subject: 'published-evidence', expectedLinks: reportedLinks },
1252
+ );
1253
+ break;
1254
+ }
1255
+ }
1256
+ }
1257
+ if (!removed) {
1258
+ const claimantRemoval = quarantineRemoveLinkedRegularFileAlias(
1259
+ entry.stagedPath,
1260
+ entry.finalPath,
1261
+ { subject: 'published-evidence-claimant' },
1262
+ );
1263
+ removed = claimantRemoval.status === 'removed' ? claimantRemoval : ownedMismatch;
1264
+ }
1265
+ if (removed.status !== 'removed' && removed.status !== 'absent') {
1266
+ rollbackErrors.push(publishedRemovalError(entry.finalPath, removed));
1267
+ }
1268
+ }
1269
+ for (const backup of [...backups].reverse()) restoreOwnedBackup(backup, rollbackErrors);
1270
+ rollbackErrors.push(...releaseStagedBindings());
1271
+ rollbackErrors.push(...cleanupStagedEvidence(ownership, { removeDirectory: true }));
1272
+ ownership.active = false;
1273
+ if (conflict) {
1274
+ if (rollbackErrors.length) conflict.diagnostic.evidence.rollbackErrors = rollbackErrors;
1275
+ return conflict;
1276
+ }
1277
+ return evidenceWriteFailure(
1278
+ artifactPath,
1279
+ 'visual-check could not atomically publish its evidence set.',
1280
+ [{ reason: error.message }, ...rollbackErrors],
1281
+ );
1282
+ } finally {
1283
+ releaseStagedBindings();
1284
+ }
1285
+ }
1286
+
1287
+ function executable(file, platform = process.platform) {
1288
+ if (!file) return null;
1289
+ try {
1290
+ fs.accessSync(file, platform === 'win32' ? fs.constants.F_OK : fs.constants.X_OK);
1291
+ return path.resolve(file);
1292
+ } catch {
1293
+ return null;
1294
+ }
1295
+ }
1296
+
1297
+ function findOnPath(command, env, platform, resolveExecutable) {
1298
+ // Use the target platform's path grammar, not the host's: these candidates
1299
+ // are checked through an injected platform (see the findChrome tests), and
1300
+ // the host `path` object on Windows would join POSIX directories with
1301
+ // backslashes and split PATH on ';'.
1302
+ const pathApi = platform === 'win32' ? path.win32 : path.posix;
1303
+ const directories = String(env.PATH || '').split(pathApi.delimiter).filter(Boolean);
1304
+ const extensions = platform === 'win32'
1305
+ ? String(env.PATHEXT || '.EXE;.CMD;.BAT;.COM').split(';').filter(Boolean)
1306
+ : [''];
1307
+ for (const directory of directories) {
1308
+ for (const extension of extensions) {
1309
+ const candidate = pathApi.join(directory, `${command}${extension}`);
1310
+ const resolved = resolveExecutable(candidate, platform);
1311
+ if (resolved) return resolved;
1312
+ }
1313
+ }
1314
+ return null;
1315
+ }
1316
+
1317
+ export function findChrome({
1318
+ env = process.env,
1319
+ platform = process.platform,
1320
+ resolveExecutable = executable,
1321
+ } = {}) {
1322
+ // Windows environment names are case-insensitive, including when callers
1323
+ // provide a plain object instead of the special process.env object.
1324
+ if (platform === 'win32') {
1325
+ env = Object.fromEntries(Object.entries(env).map(([name, value]) => [name.toUpperCase(), value]));
1326
+ }
1327
+ if (Object.prototype.hasOwnProperty.call(env, 'ARCHIFY_CHROME')) {
1328
+ return resolveExecutable(env.ARCHIFY_CHROME, platform);
1329
+ }
1330
+
1331
+ const fixed = [];
1332
+ const commands = [];
1333
+ if (platform === 'darwin') {
1334
+ fixed.push(
1335
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
1336
+ '/Applications/Chromium.app/Contents/MacOS/Chromium',
1337
+ );
1338
+ } else if (platform === 'win32') {
1339
+ const pathApi = path.win32;
1340
+ for (const root of [env.PROGRAMFILES, env['PROGRAMFILES(X86)'], env.LOCALAPPDATA].filter(Boolean)) {
1341
+ fixed.push(
1342
+ pathApi.join(root, 'Google', 'Chrome', 'Application', 'chrome.exe'),
1343
+ pathApi.join(root, 'Chromium', 'Application', 'chrome.exe'),
1344
+ );
1345
+ }
1346
+ commands.push('chrome', 'google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser');
1347
+ } else {
1348
+ commands.push('google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser');
1349
+ }
1350
+
1351
+ for (const candidate of fixed) {
1352
+ const resolved = resolveExecutable(candidate, platform);
1353
+ if (resolved) return resolved;
1354
+ }
1355
+ for (const command of commands) {
1356
+ const resolved = findOnPath(command, env, platform, resolveExecutable);
1357
+ if (resolved) return resolved;
1358
+ }
1359
+ // Preserve every Chrome/Chromium candidate's priority, including portable
1360
+ // PATH installations, before falling back to Windows' bundled browser.
1361
+ if (platform === 'win32') {
1362
+ for (const root of [env['PROGRAMFILES(X86)'], env.PROGRAMFILES, env.LOCALAPPDATA].filter(Boolean)) {
1363
+ const candidate = path.win32.join(root, 'Microsoft', 'Edge', 'Application', 'msedge.exe');
1364
+ const resolved = resolveExecutable(candidate, platform);
1365
+ if (resolved) return resolved;
1366
+ }
1367
+ return findOnPath('msedge', env, platform, resolveExecutable);
1368
+ }
1369
+ // macOS and Linux: probe Edge behind every Chrome/Chromium candidate, the
1370
+ // same way Windows does. #920 asked for `microsoft-edge`,
1371
+ // `microsoft-edge-stable`, and the macOS application bundle.
1372
+ if (platform === 'darwin') {
1373
+ const edgeApp = '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge';
1374
+ const resolved = resolveExecutable(edgeApp, platform);
1375
+ if (resolved) return resolved;
1376
+ }
1377
+ for (const command of ['microsoft-edge', 'microsoft-edge-stable']) {
1378
+ const resolved = findOnPath(command, env, platform, resolveExecutable);
1379
+ if (resolved) return resolved;
1380
+ }
1381
+ return null;
1382
+ }
1383
+
1384
+ class PipeCdp {
1385
+ constructor(child, { failureDetails = () => '' } = {}) {
1386
+ this.child = child;
1387
+ this.failureDetails = failureDetails;
1388
+ this.nextId = 1;
1389
+ this.buffer = '';
1390
+ this.receivedBytes = 0;
1391
+ this.receivedMessages = 0;
1392
+ this.completedWrites = 0;
1393
+ this.writtenBytes = 0;
1394
+ this.pending = new Map();
1395
+ this.waiters = [];
1396
+ this.subscribers = new Set();
1397
+ this.writePipe = child.stdio[3];
1398
+ this.readPipe = child.stdio[4];
1399
+ this.readPipe.setEncoding('utf8');
1400
+ this.readPipe.on('data', (chunk) => this.consume(chunk));
1401
+ this.writePipe.on('error', (error) => this.failAll(this.failure('write pipe', error)));
1402
+ this.readPipe.on('error', (error) => this.failAll(this.failure('read pipe', error)));
1403
+ this.readPipe.once('end', () => this.failAll(this.failure('read pipe', new Error('stream ended'))));
1404
+ this.readPipe.once('close', () => this.failAll(this.failure('read pipe', new Error('stream closed'))));
1405
+ this.writePipe.once('close', () => this.failAll(this.failure('write pipe', new Error('stream closed'))));
1406
+ child.once('error', (error) => this.failAll(this.failure('process launch', error)));
1407
+ child.once('close', (code, signal) => {
1408
+ const ending = signal ? `signal ${signal}` : `exit code ${code}`;
1409
+ this.failAll(this.failure('process exit', new Error(`Chrome closed with ${ending}`)));
1410
+ });
1411
+ }
1412
+
1413
+ failure(stage, error) {
1414
+ const code = error?.code ? ` [${error.code}]` : '';
1415
+ const details = this.failureDetails();
1416
+ const failure = new Error([
1417
+ `Chrome DevTools ${stage} failed: ${error?.message || String(error)}${code}`,
1418
+ details,
1419
+ `Chrome transport: Node ${process.version}, libuv ${process.versions.uv}, ${process.platform}; pid=${this.child.pid ?? 'unavailable'}, exitCode=${this.child.exitCode}, signalCode=${this.child.signalCode}.`,
1420
+ `Chrome read pipe: readable=${this.readPipe.readable}, ended=${this.readPipe.readableEnded}, destroyed=${this.readPipe.destroyed}, receivedBytes=${this.receivedBytes}, messages=${this.receivedMessages}, bufferedBytes=${Buffer.byteLength(this.buffer)}.`,
1421
+ `Chrome write pipe: writable=${this.writePipe.writable}, ended=${this.writePipe.writableEnded}, destroyed=${this.writePipe.destroyed}, completedWrites=${this.completedWrites}, writtenBytes=${this.writtenBytes}, bufferedBytes=${this.writePipe.writableLength}.`,
1422
+ ].filter(Boolean).join('\n'));
1423
+ if (error?.code) failure.code = error.code;
1424
+ if (error?.method) failure.method = error.method;
1425
+ return failure;
1426
+ }
1427
+
1428
+ consume(chunk) {
1429
+ this.receivedBytes += Buffer.byteLength(chunk);
1430
+ this.buffer += chunk;
1431
+ let boundary;
1432
+ while ((boundary = this.buffer.indexOf('\0')) >= 0) {
1433
+ const raw = this.buffer.slice(0, boundary);
1434
+ this.buffer = this.buffer.slice(boundary + 1);
1435
+ if (!raw) continue;
1436
+ let message;
1437
+ try {
1438
+ message = JSON.parse(raw);
1439
+ } catch (error) {
1440
+ this.failAll(new Error(`Chrome DevTools returned invalid JSON: ${error.message}`));
1441
+ continue;
1442
+ }
1443
+ this.receivedMessages += 1;
1444
+ if (message.id) {
1445
+ const pending = this.pending.get(message.id);
1446
+ if (!pending) continue;
1447
+ clearTimeout(pending.timer);
1448
+ this.pending.delete(message.id);
1449
+ if (message.error) pending.reject(new Error(`${pending.method}: ${message.error.message}`));
1450
+ else pending.resolve(message.result || {});
1451
+ continue;
1452
+ }
1453
+ for (const subscriber of this.subscribers) subscriber(message);
1454
+ for (const waiter of [...this.waiters]) {
1455
+ if (waiter.method !== message.method) continue;
1456
+ if (waiter.sessionId && waiter.sessionId !== message.sessionId) continue;
1457
+ clearTimeout(waiter.timer);
1458
+ this.waiters.splice(this.waiters.indexOf(waiter), 1);
1459
+ waiter.resolve(message.params || {});
1460
+ }
1461
+ }
1462
+ }
1463
+
1464
+ subscribe(callback) {
1465
+ this.subscribers.add(callback);
1466
+ return () => this.subscribers.delete(callback);
1467
+ }
1468
+
1469
+ send(method, params = {}, sessionId = undefined, timeoutMs = 15000) {
1470
+ const id = this.nextId++;
1471
+ const message = { id, method, params };
1472
+ if (sessionId) message.sessionId = sessionId;
1473
+ return new Promise((resolve, reject) => {
1474
+ const timer = setTimeout(() => {
1475
+ this.pending.delete(id);
1476
+ const error = new Error(`${method}: timed out after ${timeoutMs}ms`);
1477
+ error.code = 'ERR_CHROME_CDP_TIMEOUT';
1478
+ error.method = method;
1479
+ reject(this.failure('protocol timeout', error));
1480
+ }, timeoutMs);
1481
+ this.pending.set(id, { method, resolve, reject, timer });
1482
+ try {
1483
+ const serialized = `${JSON.stringify(message)}\0`;
1484
+ this.writePipe.write(serialized, (error) => {
1485
+ if (error) {
1486
+ this.failAll(this.failure('write pipe', error));
1487
+ } else {
1488
+ this.completedWrites += 1;
1489
+ this.writtenBytes += Buffer.byteLength(serialized);
1490
+ }
1491
+ });
1492
+ } catch (error) {
1493
+ this.failAll(this.failure('write pipe', error));
1494
+ }
1495
+ });
1496
+ }
1497
+
1498
+ waitFor(method, sessionId, timeoutMs = 15000) {
1499
+ return new Promise((resolve, reject) => {
1500
+ const waiter = { method, sessionId, resolve, reject, timer: null };
1501
+ waiter.timer = setTimeout(() => {
1502
+ this.waiters.splice(this.waiters.indexOf(waiter), 1);
1503
+ reject(this.failure('event timeout', new Error(`${method}: event timed out after ${timeoutMs}ms`)));
1504
+ }, timeoutMs);
1505
+ this.waiters.push(waiter);
1506
+ });
1507
+ }
1508
+
1509
+ failAll(error) {
1510
+ for (const pending of this.pending.values()) {
1511
+ clearTimeout(pending.timer);
1512
+ pending.reject(error);
1513
+ }
1514
+ for (const waiter of this.waiters) {
1515
+ clearTimeout(waiter.timer);
1516
+ waiter.reject(error);
1517
+ }
1518
+ this.pending.clear();
1519
+ this.waiters = [];
1520
+ }
1521
+ }
1522
+
1523
+ export function chromeVisualBrowserArgs(profileRoot, {
1524
+ env = process.env,
1525
+ getuid = typeof process.getuid === 'function' ? () => process.getuid() : null,
1526
+ } = {}) {
1527
+ const args = [
1528
+ '--headless=new',
1529
+ '--remote-debugging-pipe',
1530
+ '--disable-gpu',
1531
+ '--hide-scrollbars',
1532
+ '--disable-background-networking',
1533
+ '--disable-component-update',
1534
+ '--disable-default-apps',
1535
+ '--disable-sync',
1536
+ '--metrics-recording-only',
1537
+ '--no-first-run',
1538
+ '--no-default-browser-check',
1539
+ '--disable-background-timer-throttling',
1540
+ '--disable-backgrounding-occluded-windows',
1541
+ '--disable-renderer-backgrounding',
1542
+ '--force-device-scale-factor=1',
1543
+ `--user-data-dir=${profileRoot}`,
1544
+ 'about:blank',
1545
+ ];
1546
+ const rootUser = typeof getuid === 'function' && getuid() === 0;
1547
+ const sandboxOptOut = env?.[CHROME_NO_SANDBOX_ENV] === '1';
1548
+ if (rootUser || sandboxOptOut) args.unshift('--no-sandbox');
1549
+ return args;
1550
+ }
1551
+
1552
+ async function evaluate(cdp, sessionId, expression, awaitPromise = false) {
1553
+ const response = await cdp.send('Runtime.evaluate', {
1554
+ expression,
1555
+ awaitPromise,
1556
+ returnByValue: true,
1557
+ }, sessionId);
1558
+ if (response.exceptionDetails) {
1559
+ throw new Error(response.exceptionDetails.exception?.description
1560
+ || response.exceptionDetails.text
1561
+ || 'Runtime.evaluate failed');
1562
+ }
1563
+ return response.result?.value;
1564
+ }
1565
+
1566
+ function browserEnvironment(env, platform) {
1567
+ if (platform !== 'win32') return env;
1568
+ // Agent-launched Git Bash can inherit this app-health shim. Edge then
1569
+ // relaunches and loses the DevTools pipes (#790). Change the browser's copy
1570
+ // only, and leave unknown/combined layers (including privilege settings) alone.
1571
+ return Object.fromEntries(Object.entries(env).filter(([name, value]) =>
1572
+ !(name.toUpperCase() === '__COMPAT_LAYER'
1573
+ && /^\s*DetectorsAppHealth\s*$/i.test(String(value)))));
1574
+ }
1575
+
1576
+ export class ChromeVisualBrowser {
1577
+ #profile;
1578
+ constructor(chromePath, {
1579
+ platform = process.platform,
1580
+ env = process.env,
1581
+ getuid = typeof process.getuid === 'function' ? () => process.getuid() : null,
1582
+ spawnImpl = spawn,
1583
+ startupTimeoutMs = CHROME_STARTUP_TIMEOUT_MS,
1584
+ shutdownTimeoutMs = 1500,
1585
+ } = {}) {
1586
+ this.#profile = createOwnedTempDirectory('archify-visual-check-profile-');
1587
+ this.profileRoot = this.#profile.path;
1588
+ this.shutdownTimeoutMs = shutdownTimeoutMs;
1589
+ this.stderr = '';
1590
+ const args = chromeVisualBrowserArgs(this.profileRoot, { env, getuid });
1591
+ this.child = spawnImpl(chromePath, args, {
1592
+ stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'],
1593
+ env: browserEnvironment(env, platform),
1594
+ });
1595
+ this.child.stderr.setEncoding('utf8');
1596
+ this.child.stderr.on('data', (chunk) => {
1597
+ this.stderr = `${this.stderr}${chunk}`.slice(-8000);
1598
+ });
1599
+ this.child.stderr.on('error', (error) => {
1600
+ this.stderr = `${this.stderr}\nChrome stderr stream failed: ${error.message}`.trim().slice(-8000);
1601
+ });
1602
+ this.cdp = new PipeCdp(this.child, {
1603
+ failureDetails: () => {
1604
+ const exit = this.child.signalCode
1605
+ ? `signal ${this.child.signalCode}`
1606
+ : this.child.exitCode == null ? 'still running' : `exit code ${this.child.exitCode}`;
1607
+ const stderr = this.stderr.trim();
1608
+ return [
1609
+ `Chrome process: ${exit}.`,
1610
+ stderr ? `Chrome stderr:\n${stderr}` : '',
1611
+ platform === 'win32' && this.cdp?.receivedBytes === 0
1612
+ ? 'Windows browser startup may have relaunched before connecting to the DevTools pipe. '
1613
+ + 'Retry from a non-elevated PowerShell opened normally, outside an elevated or compatibility-mode parent. '
1614
+ + 'Archify does not disable browser de-elevation or the sandbox to preserve pipe handles.'
1615
+ : '',
1616
+ ].filter(Boolean).join('\n');
1617
+ },
1618
+ });
1619
+ this.startupTimeoutMs = startupTimeoutMs;
1620
+ this.sessionPromise = this.attach();
1621
+ }
1622
+
1623
+ async attach() {
1624
+ // Process launch can be delayed substantially on a busy desktop. Keep the
1625
+ // longer allowance inside one gate invocation so an authoring agent does
1626
+ // not turn startup jitter into repeated tool calls or candidate edits.
1627
+ const targets = await this.cdp.send(
1628
+ 'Target.getTargets', {}, undefined, this.startupTimeoutMs,
1629
+ );
1630
+ let target = targets.targetInfos?.find((item) => item.type === 'page');
1631
+ if (!target) {
1632
+ const created = await this.cdp.send('Target.createTarget', { url: 'about:blank' });
1633
+ target = { targetId: created.targetId };
1634
+ }
1635
+ this.targetId = target.targetId;
1636
+ const attached = await this.cdp.send('Target.attachToTarget', {
1637
+ targetId: target.targetId,
1638
+ flatten: true,
1639
+ });
1640
+ await this.cdp.send('Page.enable', {}, attached.sessionId);
1641
+ await this.cdp.send('Runtime.enable', {}, attached.sessionId);
1642
+ return attached.sessionId;
1643
+ }
1644
+
1645
+ async resetPage() {
1646
+ await this.sessionPromise;
1647
+ const previousTarget = this.targetId;
1648
+ const created = await this.cdp.send('Target.createTarget', { url: 'about:blank' });
1649
+ const attached = await this.cdp.send('Target.attachToTarget', { targetId: created.targetId, flatten: true });
1650
+ await this.cdp.send('Page.enable', {}, attached.sessionId);
1651
+ await this.cdp.send('Runtime.enable', {}, attached.sessionId);
1652
+ this.targetId = created.targetId;
1653
+ this.sessionPromise = Promise.resolve(attached.sessionId);
1654
+ if (previousTarget) await this.cdp.send('Target.closeTarget', { targetId: previousTarget });
1655
+ await this.cdp.send('Target.activateTarget', { targetId: this.targetId });
1656
+ await this.cdp.send('Page.bringToFront', {}, attached.sessionId);
1657
+ }
1658
+
1659
+ async inspect({ artifactPath, width, height, theme, screenshotPath, writeScreenshot }) {
1660
+ const sessionId = await this.sessionPromise;
1661
+ await this.cdp.send('Emulation.setDeviceMetricsOverride', {
1662
+ width,
1663
+ height,
1664
+ deviceScaleFactor: 1,
1665
+ mobile: false,
1666
+ }, sessionId);
1667
+
1668
+ const url = pathToFileURL(artifactPath);
1669
+ url.searchParams.set('theme', theme);
1670
+ const loaded = this.cdp.waitFor('Page.loadEventFired', sessionId);
1671
+ // Navigation can fail before this waiter is awaited. Attach a rejection
1672
+ // handler immediately so a later load failure never escapes as an
1673
+ // unhandled rejection; awaiting `loaded` below still reports it normally.
1674
+ loaded.catch(() => {});
1675
+ const navigation = await this.cdp.send('Page.navigate', { url: url.href }, sessionId);
1676
+ if (navigation.errorText) throw new Error(`Chrome navigation failed: ${navigation.errorText}`);
1677
+ await loaded;
1678
+ await evaluate(this.cdp, sessionId, `(function () {
1679
+ document.documentElement.setAttribute('data-motion', 'still');
1680
+ var panel = document.querySelector('.diagram-container');
1681
+ if (panel) panel.setAttribute('data-detail-level', 'read');
1682
+ var fontsReady = document.fonts && document.fonts.ready
1683
+ ? document.fonts.ready.catch(function () {})
1684
+ : Promise.resolve();
1685
+ if (window.Archify && Archify.layoutStability && typeof Archify.layoutStability.whenStable === 'function') {
1686
+ return fontsReady.then(function () { return Archify.layoutStability.whenStable(); });
1687
+ }
1688
+ return fontsReady.then(function () {
1689
+ if (window.Archify && Archify.readerLayout && typeof Archify.readerLayout.whenStable === 'function') {
1690
+ return Archify.readerLayout.whenStable();
1691
+ }
1692
+ }).then(function () {
1693
+ if (window.Archify && Archify.viewerChromeLayout && typeof Archify.viewerChromeLayout.whenStable === 'function') {
1694
+ return Archify.viewerChromeLayout.whenStable();
1695
+ }
1696
+ }).then(function () {
1697
+ if (window.Archify && Archify.readerLayout && typeof Archify.readerLayout.whenStable === 'function') {
1698
+ return Archify.readerLayout.whenStable();
1699
+ }
1700
+ }).then(function () {
1701
+ if (window.Archify && Archify.viewerChromeLayout && typeof Archify.viewerChromeLayout.whenStable === 'function') {
1702
+ return Archify.viewerChromeLayout.whenStable();
1703
+ }
1704
+ return new Promise(function (resolve) {
1705
+ requestAnimationFrame(function () { requestAnimationFrame(resolve); });
1706
+ });
1707
+ });
1708
+ })()`, true);
1709
+
1710
+ const metrics = await evaluate(this.cdp, sessionId, `(function () {
1711
+ var reader = document.querySelector('.container');
1712
+ var diagram = document.querySelector('.diagram-container');
1713
+ var svg = diagram && (
1714
+ diagram.querySelector(':scope > svg') ||
1715
+ diagram.querySelector(':scope > .diagram-stage > svg')
1716
+ );
1717
+ var stage = diagram && (diagram.querySelector(':scope > .diagram-stage') || svg);
1718
+ var legend = svg && svg.querySelector('[data-legend]');
1719
+ var navigationDock = diagram && diagram.querySelector('.diagram-nav');
1720
+ var viewBox = svg && svg.viewBox && svg.viewBox.baseVal;
1721
+ var diagramWidth = svg ? svg.getBoundingClientRect().width : 0;
1722
+ var viewBoxWidth = viewBox ? viewBox.width : 0;
1723
+ var scale = viewBoxWidth > 0 ? Math.min(1, diagramWidth / viewBoxWidth) : 0;
1724
+ var minimum = null;
1725
+ var minimumNonEdge = null;
1726
+ var minimumEdge = null;
1727
+ if (svg && scale > 0) {
1728
+ Array.from(svg.querySelectorAll('text[data-node-label], text[data-boundary-label], text[data-detail="context"], g[data-detail="context"] text')).forEach(function (text) {
1729
+ if (text.getAttribute('data-detail') === 'fine' || text.closest('[data-detail="fine"]')) return;
1730
+ var edge = text.closest('[data-edge-from][data-edge-to]');
1731
+ var node = text.closest('[data-node-id]');
1732
+ var context = text.getAttribute('data-detail') === 'context' || Boolean(text.closest('g[data-detail="context"]'));
1733
+ var detail = text.hasAttribute('data-node-label')
1734
+ ? 'primary'
1735
+ : text.hasAttribute('data-boundary-label') ? 'boundary'
1736
+ : context && edge ? 'edge' : 'context';
1737
+ if (detail === 'context' && !node) return;
1738
+ var sourceFontPx = parseFloat(text.getAttribute('font-size') || '');
1739
+ if (!Number.isFinite(sourceFontPx)) return;
1740
+ var projectedFontPx = sourceFontPx * scale;
1741
+ var entry = {
1742
+ text: (text.textContent || '').trim(),
1743
+ detail: detail,
1744
+ owner: edge ? {
1745
+ kind: 'edge',
1746
+ id: edge.getAttribute('data-edge-id'),
1747
+ from: edge.getAttribute('data-edge-from'),
1748
+ to: edge.getAttribute('data-edge-to')
1749
+ } : node ? { kind: 'node', id: node.getAttribute('data-node-id') }
1750
+ : detail === 'boundary' ? { kind: 'boundary', id: null } : null,
1751
+ sourceFontPx: sourceFontPx,
1752
+ projectedFontPx: projectedFontPx
1753
+ };
1754
+ if (!minimum || projectedFontPx < minimum.projectedFontPx) minimum = entry;
1755
+ if (detail === 'edge') {
1756
+ if (!minimumEdge || projectedFontPx < minimumEdge.projectedFontPx) minimumEdge = entry;
1757
+ } else if (!minimumNonEdge || projectedFontPx < minimumNonEdge.projectedFontPx) {
1758
+ minimumNonEdge = entry;
1759
+ }
1760
+ });
1761
+ }
1762
+ function intersectionArea(a, b) {
1763
+ if (!a || !b || !a.width || !a.height || !b.width || !b.height) return 0;
1764
+ var width = Math.max(0, Math.min(a.right, b.right) - Math.max(a.left, b.left));
1765
+ var height = Math.max(0, Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top));
1766
+ return width * height;
1767
+ }
1768
+ var legendRect = legend ? legend.getBoundingClientRect() : null;
1769
+ var stageRect = window.Archify && Archify.viewerChromeLayout
1770
+ && typeof Archify.viewerChromeLayout.stageRect === 'function'
1771
+ ? Archify.viewerChromeLayout.stageRect()
1772
+ : (stage ? stage.getBoundingClientRect() : null);
1773
+ // The dock may lift to the viewport floor while the page scrolls; the
1774
+ // stage contract is about its resting position.
1775
+ var navigationDockRect = !navigationDock ? null
1776
+ : window.Archify && Archify.viewerChromeLayout && typeof Archify.viewerChromeLayout.dockRect === 'function'
1777
+ ? Archify.viewerChromeLayout.dockRect()
1778
+ : navigationDock.getBoundingClientRect();
1779
+ var stageDockIntersectionArea = intersectionArea(stageRect, navigationDockRect);
1780
+ var viewerChromeReceipt = window.Archify && Archify.viewerChromeLayout
1781
+ && typeof Archify.viewerChromeLayout.receipt === 'function'
1782
+ ? Archify.viewerChromeLayout.receipt()
1783
+ : null;
1784
+ // Read rendered boxes only; source ownership, offsets and hard pins are unknown.
1785
+ var workflowLanes = svg ? Array.from(svg.querySelectorAll('rect[data-composition-frame-kind="lane"]')).map(function (lane) {
1786
+ var rect = lane.getBoundingClientRect();
1787
+ var members = Array.from(svg.querySelectorAll('g[data-node-id]')).map(function (node) {
1788
+ var box = node.querySelector('rect');
1789
+ if (!box) return null;
1790
+ var bounds = box.getBoundingClientRect();
1791
+ if (bounds.top < rect.top - 1 || bounds.bottom > rect.bottom + 1
1792
+ || bounds.left < rect.left - 1 || bounds.right > rect.right + 1) return null;
1793
+ return { id: node.getAttribute('data-node-id'), top: bounds.top, bottom: bounds.bottom };
1794
+ }).filter(Boolean);
1795
+ var top = members.length ? members.reduce(function (minimum, node) { return Math.min(minimum, node.top); }, Infinity) : null;
1796
+ var bottom = members.length ? members.reduce(function (maximum, node) { return Math.max(maximum, node.bottom); }, -Infinity) : null;
1797
+ return {
1798
+ frameId: lane.getAttribute('data-composition-frame-id'),
1799
+ heightPx: Math.round(rect.height),
1800
+ nodeCount: members.length,
1801
+ nodeIds: members.slice(0, 12).map(function (node) { return node.id; }),
1802
+ nodeSpanPx: top === null ? null : Math.round(bottom - top),
1803
+ spaceAboveNodesPx: top === null ? null : Math.round(top - rect.top),
1804
+ spaceBelowNodesPx: bottom === null ? null : Math.round(rect.bottom - bottom)
1805
+ };
1806
+ }).sort(function (a, b) { return b.heightPx - a.heightPx; }).slice(0, 6) : [];
1807
+ // Vertical page budget: every block that stacks above or below the SVG,
1808
+ // so an overflow receipt can say which part must give up how many pixels.
1809
+ function outerHeight(element) {
1810
+ if (!element) return 0;
1811
+ var style = window.getComputedStyle(element);
1812
+ if (element.hidden || style.display === 'none') return 0;
1813
+ return element.getBoundingClientRect().height
1814
+ + (parseFloat(style.marginTop) || 0) + (parseFloat(style.marginBottom) || 0);
1815
+ }
1816
+ var bodyStyle = window.getComputedStyle(document.body);
1817
+ var diagramStyle = diagram ? window.getComputedStyle(diagram) : null;
1818
+ var svgHeight = svg ? svg.getBoundingClientRect().height : 0;
1819
+ var notesBelowFold = Boolean(reader) && document.documentElement.getAttribute('data-reader-rail') === 'bottom';
1820
+ var pageComposition = {
1821
+ bodyPaddingPx: Math.round((parseFloat(bodyStyle.paddingTop) || 0) + (parseFloat(bodyStyle.paddingBottom) || 0)),
1822
+ headerPx: Math.round(outerHeight(reader && reader.querySelector('.header'))),
1823
+ diagramChromePx: Math.round(outerHeight(diagram) - svgHeight),
1824
+ svgPx: Math.round(svgHeight),
1825
+ cardsPx: notesBelowFold ? 0 : Math.round(outerHeight(reader && reader.querySelector('.cards'))),
1826
+ viewBoxHeight: viewBox ? viewBox.height : 0
1827
+ };
1828
+ var svgRect = svg && svg.getBoundingClientRect();
1829
+ var diagramRect = diagram && diagram.getBoundingClientRect();
1830
+ var documentScrollUnclipped = Boolean(svgRect && diagramRect
1831
+ && svgRect.top >= diagramRect.top - 1 && svgRect.left >= diagramRect.left - 1
1832
+ && svgRect.bottom <= diagramRect.bottom + 1 && svgRect.right <= diagramRect.right + 1
1833
+ && diagram.scrollHeight <= diagram.clientHeight + 1
1834
+ && diagram.scrollWidth <= diagram.clientWidth + 1
1835
+ && [document.documentElement, document.body].every(function (element) {
1836
+ return !['hidden', 'clip'].includes(window.getComputedStyle(element).overflowY);
1837
+ }));
1838
+ return {
1839
+ pageComposition: pageComposition,
1840
+ innerWidth: window.innerWidth,
1841
+ innerHeight: window.innerHeight,
1842
+ scrollWidth: Math.ceil(document.documentElement.scrollWidth),
1843
+ // Bottom notes and index are reading material below the fold; the
1844
+ // Reader excludes them from the one-screen fit, and so does this check.
1845
+ scrollHeight: Math.max(window.innerHeight, Math.ceil(document.documentElement.scrollHeight - (
1846
+ notesBelowFold ? outerHeight(reader.querySelector('.reader-rail')) : 0))),
1847
+ resolvedTheme: document.documentElement.getAttribute('data-theme') || '',
1848
+ readerLayout: document.documentElement.getAttribute('data-reader-layout') || null,
1849
+ readerOverflow: document.documentElement.getAttribute('data-reader-overflow') || null,
1850
+ readerFit: svg ? svg.getAttribute('data-reader-fit') : null,
1851
+ diagramType: svg ? svg.getAttribute('data-diagram-type') : null,
1852
+ documentScrollUnclipped: documentScrollUnclipped,
1853
+ readerWidth: reader ? reader.getBoundingClientRect().width : 0,
1854
+ diagramWidth: diagramWidth,
1855
+ viewBoxWidth: viewBoxWidth,
1856
+ workflowLanes: workflowLanes,
1857
+ minimumProjectedNodeTextPx: minimum ? minimum.projectedFontPx : null,
1858
+ minimumProjectedNonEdgeTextPx: minimumNonEdge ? minimumNonEdge.projectedFontPx : null,
1859
+ minimumProjectedEdgeTextPx: minimumEdge ? minimumEdge.projectedFontPx : null,
1860
+ minimumProjectedNodeText: minimum ? minimum.text : null,
1861
+ minimumProjectedNodeTextDetail: minimum ? minimum.detail : null,
1862
+ minimumProjectedNodeTextOwner: minimum ? minimum.owner : null,
1863
+ hasLegend: Boolean(legendRect && legendRect.width && legendRect.height),
1864
+ hasNavigationDock: Boolean(navigationDockRect && navigationDockRect.width && navigationDockRect.height),
1865
+ legendDockIntersectionArea: stageDockIntersectionArea > 0
1866
+ ? intersectionArea(legendRect, navigationDockRect)
1867
+ : 0,
1868
+ dockStageIntersectionArea: stageDockIntersectionArea,
1869
+ dockStageGap: stageRect && navigationDockRect ? navigationDockRect.top - stageRect.bottom : null,
1870
+ viewerChromeRequiredGap: viewerChromeReceipt ? viewerChromeReceipt.gap : null,
1871
+ viewerChromeReserve: viewerChromeReceipt ? viewerChromeReceipt.reserve : 0,
1872
+ viewerChromeActive: viewerChromeReceipt ? viewerChromeReceipt.active : false
1873
+ };
1874
+ })()`);
1875
+ if (!metrics || !Number.isFinite(metrics.scrollWidth) || !Number.isFinite(metrics.scrollHeight)) {
1876
+ throw new Error('Chrome returned incomplete containment metrics.');
1877
+ }
1878
+
1879
+ if (screenshotPath) {
1880
+ const capture = await this.cdp.send('Page.captureScreenshot', {
1881
+ format: 'png',
1882
+ fromSurface: true,
1883
+ captureBeyondViewport: false,
1884
+ }, sessionId, 20000);
1885
+ if (!capture.data) throw new Error('Chrome returned an empty screenshot.');
1886
+ const screenshot = Buffer.from(capture.data, 'base64');
1887
+ if (writeScreenshot) writeScreenshot(screenshot);
1888
+ else fs.writeFileSync(screenshotPath, screenshot, { flag: 'wx' });
1889
+ }
1890
+ return metrics;
1891
+ }
1892
+
1893
+ close() {
1894
+ if (!this.closePromise) this.closePromise = this.finishClose();
1895
+ return this.closePromise;
1896
+ }
1897
+
1898
+ async finishClose() {
1899
+ this.cdp.failAll(new Error('visual-check finished'));
1900
+ try {
1901
+ if (this.child.exitCode === null && this.child.signalCode === null) {
1902
+ const exited = () => this.child.exitCode !== null || this.child.signalCode !== null;
1903
+ const signalAndWait = (signal) => new Promise((resolve, reject) => {
1904
+ let timer;
1905
+ const finish = () => {
1906
+ clearTimeout(timer);
1907
+ this.child.removeListener('exit', finish);
1908
+ resolve(true);
1909
+ };
1910
+ this.child.once('exit', finish);
1911
+ timer = setTimeout(() => {
1912
+ this.child.removeListener('exit', finish);
1913
+ resolve(exited());
1914
+ }, this.shutdownTimeoutMs);
1915
+ try {
1916
+ this.child.kill(signal);
1917
+ } catch (error) {
1918
+ clearTimeout(timer);
1919
+ this.child.removeListener('exit', finish);
1920
+ reject(error);
1921
+ }
1922
+ });
1923
+ if (!await signalAndWait('SIGTERM') && !await signalAndWait('SIGKILL')) {
1924
+ const error = new Error(`Chrome did not exit; retained temporary profile "${this.#profile.path}".`);
1925
+ error.code = 'ARCHIFY_TEMP_CLEANUP';
1926
+ error.directory = this.#profile.path;
1927
+ throw error;
1928
+ }
1929
+ }
1930
+ } finally {
1931
+ // `exit` only reports that Chrome's main process is gone. A helper may
1932
+ // still hold an inherited pipe open, so explicitly release every stream
1933
+ // this browser instance owns before its test cleanup hook resolves.
1934
+ for (const stream of [this.child.stderr, this.child.stdio[3], this.child.stdio[4]]) {
1935
+ if (stream && !stream.destroyed) stream.destroy();
1936
+ }
1937
+ }
1938
+ await this.#profile.cleanup();
1939
+ }
1940
+ }
1941
+
1942
+ function observation({ width, height, theme, metrics }) {
1943
+ const innerWidth = Number(metrics.innerWidth);
1944
+ const innerHeight = Number(metrics.innerHeight);
1945
+ const scrollWidth = Number(metrics.scrollWidth);
1946
+ const scrollHeight = Number(metrics.scrollHeight);
1947
+ const overflowX = scrollWidth > innerWidth;
1948
+ const overflowY = scrollHeight > innerHeight;
1949
+ const minimumProjectedNodeTextPx = metrics.minimumProjectedNodeTextPx == null
1950
+ ? null
1951
+ : Number(metrics.minimumProjectedNodeTextPx);
1952
+ const minimumProjectedNonEdgeTextPx = metrics.minimumProjectedNonEdgeTextPx == null
1953
+ ? null
1954
+ : Number(metrics.minimumProjectedNonEdgeTextPx);
1955
+ const minimumProjectedEdgeTextPx = metrics.minimumProjectedEdgeTextPx == null
1956
+ ? null
1957
+ : Number(metrics.minimumProjectedEdgeTextPx);
1958
+ const readabilityOk = minimumProjectedNodeTextPx == null
1959
+ || minimumProjectedNodeTextPx >= MIN_PROJECTED_NODE_TEXT_PX;
1960
+ const readerLayout = metrics.readerLayout || null;
1961
+ const readerOverflow = metrics.readerOverflow || null;
1962
+ const readerFit = metrics.readerFit || null;
1963
+ const verticalScrollAccepted = Boolean(
1964
+ overflowY
1965
+ && !overflowX
1966
+ && readabilityOk
1967
+ && Number.isFinite(minimumProjectedNodeTextPx)
1968
+ && ((readerLayout === 'adaptive' && readerOverflow === 'authored' && (readerFit === 'intrinsic-height' || readerFit === 'width-first'))
1969
+ || (readerFit === 'authored-height' && metrics.diagramType === 'architecture'
1970
+ && metrics.documentScrollUnclipped === true))
1971
+ );
1972
+ const authoredClipped = readerFit === 'authored-height' && metrics.diagramType === 'architecture'
1973
+ && metrics.documentScrollUnclipped !== true;
1974
+ const containmentOk = !authoredClipped && !overflowX && (!overflowY || verticalScrollAccepted);
1975
+ const legendDockIntersectionArea = Number(metrics.legendDockIntersectionArea) || 0;
1976
+ const dockStageIntersectionArea = Number(metrics.dockStageIntersectionArea) || 0;
1977
+ const dockStageGap = metrics.dockStageGap == null ? null : Number(metrics.dockStageGap);
1978
+ const receiptDockStageGap = metrics.viewerChromeRequiredGap == null
1979
+ ? null
1980
+ : Number(metrics.viewerChromeRequiredGap);
1981
+ const requiredDockStageGap = Number.isFinite(receiptDockStageGap) ? receiptDockStageGap : 0;
1982
+ const viewerChromeStageOk = !metrics.hasNavigationDock || (
1983
+ Number.isFinite(dockStageGap)
1984
+ && dockStageIntersectionArea <= 0.5
1985
+ && dockStageGap >= requiredDockStageGap - 1
1986
+ );
1987
+ const viewerChromeOk = legendDockIntersectionArea <= 0.5 && viewerChromeStageOk;
1988
+ return {
1989
+ width,
1990
+ height,
1991
+ theme,
1992
+ innerWidth,
1993
+ innerHeight,
1994
+ scrollWidth,
1995
+ scrollHeight,
1996
+ overflowX,
1997
+ overflowY,
1998
+ verticalScrollAccepted,
1999
+ overflowDisposition: authoredClipped || overflowX || (overflowY && !verticalScrollAccepted)
2000
+ ? 'unexpected-overflow'
2001
+ : verticalScrollAccepted ? 'readable-vertical-scroll' : 'contained',
2002
+ readerLayout,
2003
+ readerOverflow,
2004
+ readerFit,
2005
+ ...(readerFit === 'authored-height' ? { diagramType: metrics.diagramType, documentScrollUnclipped: metrics.documentScrollUnclipped === true } : {}),
2006
+ ok: containmentOk,
2007
+ readerWidth: Number(metrics.readerWidth) || null,
2008
+ diagramWidth: Number(metrics.diagramWidth) || null,
2009
+ ...(metrics.pageComposition ? { pageComposition: metrics.pageComposition } : {}),
2010
+ viewBoxWidth: Number(metrics.viewBoxWidth) || null,
2011
+ ...(metrics.workflowLanes?.length ? { workflowLanes: metrics.workflowLanes } : {}),
2012
+ minimumProjectedNodeTextPx,
2013
+ minimumProjectedNonEdgeTextPx,
2014
+ minimumProjectedEdgeTextPx,
2015
+ minimumProjectedNodeText: metrics.minimumProjectedNodeText || null,
2016
+ minimumProjectedNodeTextDetail: metrics.minimumProjectedNodeTextDetail || null,
2017
+ minimumProjectedNodeTextOwner: metrics.minimumProjectedNodeTextOwner || null,
2018
+ minimumRequiredNodeTextPx: MIN_PROJECTED_NODE_TEXT_PX,
2019
+ readabilityOk,
2020
+ hasLegend: Boolean(metrics.hasLegend),
2021
+ hasNavigationDock: Boolean(metrics.hasNavigationDock),
2022
+ legendDockIntersectionArea,
2023
+ dockStageIntersectionArea,
2024
+ dockStageGap,
2025
+ requiredDockStageGap,
2026
+ viewerChromeStageOk,
2027
+ viewerChromeReserve: Number(metrics.viewerChromeReserve) || 0,
2028
+ viewerChromeActive: Boolean(metrics.viewerChromeActive),
2029
+ viewerChromeOk,
2030
+ resolvedTheme: metrics.resolvedTheme || theme,
2031
+ };
2032
+ }
2033
+
2034
+ function contactSheetHtml({ artifactPath, receipt, screenshots }) {
2035
+ const cards = screenshots.map((entry) => `
2036
+ <figure>
2037
+ <img src="${htmlEscape(entry.file)}" alt="${htmlEscape(`${entry.theme} ${entry.width} by ${entry.height}`)}">
2038
+ <figcaption><strong>${htmlEscape(entry.theme.toUpperCase())}</strong> · ${entry.width}×${entry.height} · containment ${entry.ok ? 'pass' : 'fail'}${entry.verticalScrollAccepted ? ' · readable vertical scroll' : ''}</figcaption>
2039
+ </figure>`).join('');
2040
+ return `<!doctype html>
2041
+ <html lang="en">
2042
+ <head>
2043
+ <meta charset="utf-8">${softwareNoticesHtml}
2044
+ <meta name="viewport" content="width=device-width,initial-scale=1">
2045
+ <title>Archify automated browser evidence · ${htmlEscape(path.basename(artifactPath))}</title>
2046
+ <style>
2047
+ *{box-sizing:border-box}body{margin:0;padding:24px;background:#e9eef5;color:#172033;font:14px/1.5 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}header{max-width:1500px;margin:0 auto 18px}h1{margin:0 0 6px;font-size:20px}p{margin:0;color:#526176}.grid{max-width:1500px;margin:auto;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}figure{margin:0;padding:10px;background:white;border:1px solid #c9d4e3;border-radius:12px;box-shadow:0 10px 30px rgba(15,23,42,.08)}img{display:block;width:100%;height:auto;border:1px solid #e2e8f0}figcaption{padding:9px 4px 2px;color:#526176}@media(max-width:900px){.grid{grid-template-columns:1fr}}
2048
+ </style>
2049
+ </head>
2050
+ <body>
2051
+ <header><h1>Automated browser evidence</h1><p>${htmlEscape(path.basename(artifactPath))} · visual-check containment ${htmlEscape(receipt.containment.status)} · perceptual visual review pending</p></header>
2052
+ <main class="grid">${cards}
2053
+ </main>
2054
+ </body>
2055
+ </html>
2056
+ `;
2057
+ }
2058
+
2059
+ const publishedBrowserEvidenceReceipts = new WeakSet();
2060
+
2061
+ // Keep detailed observations in the bound receipt; expose every review image and
2062
+ // every failure without repeating the same viewport metrics in CLI context.
2063
+ export function summarizeBrowserEvidence(receipt) {
2064
+ const directory = receipt.sidecars?.directory || path.dirname(receipt.artifact.path);
2065
+ const evidencePath = (file) => file ? path.resolve(directory, file) : undefined;
2066
+ const published = publishedBrowserEvidenceReceipts.has(receipt);
2067
+ return {
2068
+ schemaVersion: receipt.schemaVersion,
2069
+ command: receipt.command,
2070
+ ok: receipt.ok,
2071
+ status: receipt.status,
2072
+ evidenceKind: receipt.evidenceKind,
2073
+ visualReview: receipt.visualReview,
2074
+ artifact: receipt.artifact,
2075
+ provenance: receipt.provenance,
2076
+ deliveryReceiptId: receipt.deliveryReceiptId,
2077
+ state: receipt.state,
2078
+ chrome: receipt.chrome,
2079
+ checks: Object.fromEntries(['containment', 'readability', 'viewerChrome', 'themeStates', 'captures']
2080
+ .filter((key) => receipt[key])
2081
+ .map((key) => [key, receipt[key].status])),
2082
+ error: receipt.error,
2083
+ publication: receipt.publication,
2084
+ diagnostics: receipt.diagnostics || [],
2085
+ evidence: {
2086
+ receipt: published ? evidencePath(receipt.sidecars?.receipt) : undefined,
2087
+ contactSheet: published ? evidencePath(receipt.captures?.contactSheet) : undefined,
2088
+ screenshots: (published ? receipt.captures?.screenshots || [] : []).map((entry) => ({
2089
+ path: evidencePath(entry.file),
2090
+ width: entry.width,
2091
+ height: entry.height,
2092
+ theme: entry.theme,
2093
+ resolvedTheme: entry.resolvedTheme,
2094
+ })),
2095
+ },
2096
+ };
2097
+ }
2098
+
2099
+ function viewportSubject(artifact, entry) {
2100
+ return {
2101
+ artifact,
2102
+ viewport: { width: entry.width, height: entry.height, theme: entry.theme },
2103
+ };
2104
+ }
2105
+
2106
+ function failureDiagnostic({ code, message, subject, evidence, supportedFixes, severity = 'error' }) {
2107
+ return { code, severity, message, subject, evidence, supportedFixes };
2108
+ }
2109
+
2110
+ function resolveSidecarDirectory(artifactPath, outputs, compareParents) {
2111
+ const artifact = path.resolve(artifactPath);
2112
+ const artifactDirectory = path.dirname(artifact);
2113
+ const sidecarDirectory = path.dirname(outputs.receipt);
2114
+ const comparison = compareParents(outputs.receipt, artifact);
2115
+
2116
+ const sidecars = {
2117
+ ...(comparison?.status === 'different' ? { directory: sidecarDirectory } : {}),
2118
+ receipt: path.basename(outputs.receipt),
2119
+ ...(outputs.capture === false ? {} : { contactSheet: path.basename(outputs.contactSheet) }),
2120
+ };
2121
+ if (comparison?.status === 'match' || comparison?.status === 'different') {
2122
+ return { ok: true, sidecars };
2123
+ }
2124
+
2125
+ const reason = comparison?.reason || { code: 'invalid-path-identity-result' };
2126
+ const error = `visual-check could not determine the physical identity of its evidence directory "${sidecarDirectory}" relative to the artifact directory "${artifactDirectory}".`;
2127
+ return {
2128
+ ok: false,
2129
+ sidecars,
2130
+ error,
2131
+ diagnostic: failureDiagnostic({
2132
+ code: 'viewer/sidecar-directory-identity',
2133
+ message: error,
2134
+ subject: { artifact, sidecarDirectory },
2135
+ evidence: { comparison: reason },
2136
+ supportedFixes: [
2137
+ 'use existing, accessible artifact and evidence directories, then rerun visual-check',
2138
+ ],
2139
+ }),
2140
+ };
2141
+ }
2142
+
2143
+ // Turn a measured vertical overflow into the pixel budget an author can act on:
2144
+ // which stacked block holds the height, and what the SVG or cards must shrink to.
2145
+ export function verticalBudgetFixes(entry) {
2146
+ const page = entry.pageComposition;
2147
+ if (!entry.overflowY || !page) return [];
2148
+ const excess = entry.scrollHeight - entry.innerHeight;
2149
+ const fixes = [];
2150
+ const stacked = `${page.bodyPaddingPx}px body padding + ${page.headerPx}px header + ${page.diagramChromePx}px diagram chrome + ${page.svgPx}px SVG + ${page.cardsPx}px cards = ${entry.scrollHeight}px against ${entry.innerHeight}px`;
2151
+ if (page.svgPx > 0 && page.viewBoxHeight > 0) {
2152
+ const targetSvg = page.svgPx - excess;
2153
+ const targetViewBoxHeight = Math.floor(page.viewBoxHeight * targetSvg / page.svgPx);
2154
+ if (entry.readerLayout === 'adaptive') {
2155
+ fixes.push(targetSvg > 0
2156
+ ? `the page is ${excess}px too tall (${stacked}); the Reader already narrowed the stage to its ${entry.diagramWidth}px minimum, so the SVG height only follows meta.viewBox: keep every node and relationship and reduce the viewBox height to at most ${targetViewBoxHeight} (from ${page.viewBoxHeight}) by tightening vertical gaps and empty rows`
2157
+ : `the page is ${excess}px too tall (${stacked}) and the SVG alone exceeds the viewport at the minimum reader width; split the diagram into two`);
2158
+ } else {
2159
+ fixes.push(`the page is ${excess}px too tall (${stacked}); the SVG spans the full ${entry.diagramWidth}px reader width because its viewBox ratio is below 1.55 and it declares no automatic Reader fit, so the Reader can neither narrow it nor accept readable vertical scroll: either remove meta.viewBox so the renderer sizes the canvas and declares the fit, or make the viewBox at least 1.55x wider than tall`);
2160
+ }
2161
+ }
2162
+ if (page.cardsPx >= excess) {
2163
+ fixes.push(`alternatively, conclusion cards occupy ${page.cardsPx}px below the diagram; shortening card copy or dropping a card row so cards take at most ${page.cardsPx - excess}px also fits`);
2164
+ }
2165
+ return fixes;
2166
+ }
2167
+
2168
+ function observationDiagnostics({ artifact, allObservations, readabilityObservations, command }) {
2169
+ const diagnostics = [];
2170
+ for (const entry of allObservations) {
2171
+ if (entry.resolvedTheme !== entry.theme) {
2172
+ diagnostics.push(failureDiagnostic({
2173
+ code: 'viewer/theme-state',
2174
+ message: `The rendered artifact resolved ${entry.resolvedTheme || 'no theme'} instead of the requested ${entry.theme} theme at ${entry.width}x${entry.height}.`,
2175
+ subject: viewportSubject(artifact, entry),
2176
+ evidence: {
2177
+ requestedTheme: entry.theme,
2178
+ resolvedTheme: entry.resolvedTheme,
2179
+ },
2180
+ supportedFixes: [
2181
+ `restore deterministic ${entry.theme} theme resolution, then rerun ${command}`,
2182
+ ],
2183
+ }));
2184
+ }
2185
+ if (!entry.ok) {
2186
+ const authoredClipped = entry.readerFit === 'authored-height' && entry.diagramType === 'architecture'
2187
+ && !entry.documentScrollUnclipped;
2188
+ const budgetFixes = authoredClipped
2189
+ ? ['restore the full SVG inside the diagram panel and allow normal document scrolling; remove internal scrollers and clipping without changing authored geometry']
2190
+ : verticalBudgetFixes(entry);
2191
+ diagnostics.push(failureDiagnostic({
2192
+ code: authoredClipped ? 'viewer/diagram-clipped' : 'viewer/viewport-overflow',
2193
+ message: authoredClipped
2194
+ ? `The authored Architecture canvas is clipped or cannot scroll in the document at ${entry.width}x${entry.height} (${entry.theme}).`
2195
+ : `The rendered artifact overflows the ${entry.width}x${entry.height} ${entry.theme} viewport.`,
2196
+ subject: viewportSubject(artifact, entry),
2197
+ evidence: {
2198
+ innerWidth: entry.innerWidth,
2199
+ innerHeight: entry.innerHeight,
2200
+ scrollWidth: entry.scrollWidth,
2201
+ scrollHeight: entry.scrollHeight,
2202
+ overflowX: entry.overflowX,
2203
+ overflowY: entry.overflowY,
2204
+ overflowDisposition: entry.overflowDisposition,
2205
+ readerLayout: entry.readerLayout,
2206
+ readerOverflow: entry.readerOverflow,
2207
+ readerFit: entry.readerFit,
2208
+ ...(authoredClipped ? { documentScrollUnclipped: false } : {}),
2209
+ ...(entry.overflowY && entry.pageComposition ? {
2210
+ pageComposition: entry.pageComposition,
2211
+ pageCompositionMeasurement: 'CSS pixels at this viewport; body padding, header, diagram chrome, SVG and cards stack vertically and sum to scrollHeight',
2212
+ } : {}),
2213
+ ...(entry.overflowY && entry.workflowLanes?.length ? {
2214
+ workflowLanes: entry.workflowLanes,
2215
+ measurement: 'CSS pixels; rendered node boxes geometrically contained in each lane frame; spaces include headers and routing, not guaranteed removable space',
2216
+ } : {}),
2217
+ },
2218
+ supportedFixes: [
2219
+ ...budgetFixes,
2220
+ ...(entry.overflowY && entry.workflowLanes?.length ? [
2221
+ 'run validate workflow <source.json> --layout-json and compare the tallest rendered lane frames with source lanes, col and yOffset; frame IDs are rendered indices, not source lane IDs',
2222
+ 'where ownership and explicit geometry permit, distribute stacked steps across logical columns and meaningful lanes before increasing yOffset; preserve nodes, branches, labels and hard pins',
2223
+ `read references/authoring-contract.md#workflow-viewport-repair, then validate and deliver the changed source before rerunning ${command} on the new artifact; this is inspection guidance, not a verified coordinate fix`,
2224
+ ] : budgetFixes.length ? [] : [`contain the rendered layout within ${entry.width}x${entry.height}, then rerun ${command}`]),
2225
+ ],
2226
+ }));
2227
+ }
2228
+ if (entry.legendDockIntersectionArea > 0.5) {
2229
+ diagnostics.push(failureDiagnostic({
2230
+ code: 'viewer/chrome-legend-clearance',
2231
+ message: `The navigation Dock obscures the SVG Legend at ${entry.width}x${entry.height} (${entry.theme}).`,
2232
+ subject: viewportSubject(artifact, entry),
2233
+ evidence: { legendDockIntersectionArea: entry.legendDockIntersectionArea },
2234
+ supportedFixes: [
2235
+ `move the SVG Legend or Viewer Dock until legendDockIntersectionArea is 0, then rerun ${command}`,
2236
+ ],
2237
+ }));
2238
+ }
2239
+ if (!entry.viewerChromeStageOk) {
2240
+ const stageOverlapsDock = entry.dockStageIntersectionArea > 0.5;
2241
+ diagnostics.push(failureDiagnostic({
2242
+ code: 'viewer/chrome-stage-clearance',
2243
+ message: stageOverlapsDock
2244
+ ? `Navigation Dock enters the protected SVG stage at ${entry.width}x${entry.height} (${entry.theme}).`
2245
+ : `Navigation Dock clearance from the protected SVG stage is below the required gap at ${entry.width}x${entry.height} (${entry.theme}).`,
2246
+ subject: viewportSubject(artifact, entry),
2247
+ evidence: {
2248
+ dockStageIntersectionArea: entry.dockStageIntersectionArea,
2249
+ dockStageGap: entry.dockStageGap,
2250
+ requiredDockStageGap: entry.requiredDockStageGap,
2251
+ },
2252
+ supportedFixes: [
2253
+ `adjust Viewer stage reservation or clipping until dockStageGap is at least ${entry.requiredDockStageGap} and dockStageIntersectionArea is 0, then rerun ${command}`,
2254
+ ],
2255
+ }));
2256
+ }
2257
+ }
2258
+ for (const entry of readabilityObservations) {
2259
+ if (entry.readabilityOk) continue;
2260
+ diagnostics.push(failureDiagnostic({
2261
+ code: 'viewer/projected-text-readability',
2262
+ message: `Projected ${entry.minimumProjectedNodeTextDetail || 'node'} text is below the readability floor at ${entry.width}x${entry.height}.`,
2263
+ subject: viewportSubject(artifact, entry),
2264
+ evidence: {
2265
+ text: entry.minimumProjectedNodeText,
2266
+ detail: entry.minimumProjectedNodeTextDetail,
2267
+ owner: entry.minimumProjectedNodeTextOwner,
2268
+ minimumProjectedNodeTextPx: entry.minimumProjectedNodeTextPx,
2269
+ minimumRequiredNodeTextPx: entry.minimumRequiredNodeTextPx,
2270
+ },
2271
+ supportedFixes: [
2272
+ `increase projected ${entry.minimumProjectedNodeTextOwner?.kind === 'edge' ? 'relationship label' : entry.minimumProjectedNodeTextOwner?.kind === 'boundary' ? 'boundary label' : 'node text'} to at least ${entry.minimumRequiredNodeTextPx}px at ${entry.width}x${entry.height}, then rerun ${command}`,
2273
+ ],
2274
+ }));
2275
+ }
2276
+ return diagnostics;
2277
+ }
2278
+
2279
+ function baseReceipt({ artifactPath, artifact, sidecars, chrome, deliveryProvenance, command, capture }) {
2280
+ return {
2281
+ schemaVersion: 1,
2282
+ ok: false,
2283
+ command,
2284
+ evidenceKind: 'automated-browser',
2285
+ status: 'fail',
2286
+ visualReview: capture ? 'pending' : 'not-requested',
2287
+ ...(deliveryProvenance ? {
2288
+ provenance: deliveryProvenance.status,
2289
+ ...(deliveryProvenance.receiptId ? { deliveryReceiptId: deliveryProvenance.receiptId } : {}),
2290
+ } : {}),
2291
+ artifact: {
2292
+ path: artifactPath,
2293
+ sha256: sha256(artifact),
2294
+ bytes: artifact.byteLength,
2295
+ },
2296
+ state: { detail: 'read', motion: 'still' },
2297
+ chrome,
2298
+ diagnostics: [],
2299
+ containment: {
2300
+ status: 'fail',
2301
+ policy: 'fit-or-reader-declared-readable-vertical-scroll',
2302
+ viewports: [],
2303
+ },
2304
+ themeStates: { status: 'fail', viewports: [] },
2305
+ readability: { status: 'fail', minimumProjectedNodeTextPx: MIN_PROJECTED_NODE_TEXT_PX, viewports: [] },
2306
+ viewerChrome: { status: 'fail', viewports: [] },
2307
+ captures: { status: capture ? 'fail' : 'not-requested', screenshots: [], contactSheet: null },
2308
+ sidecars: { ...sidecars, files: [] },
2309
+ };
2310
+ }
2311
+
2312
+ function appendEvidencePublicationFailure(receipt, failure) {
2313
+ if (!failure?.ok) {
2314
+ if (!receipt.error) receipt.error = failure.error;
2315
+ receipt.diagnostics = [...(receipt.diagnostics || []), failure.diagnostic];
2316
+ }
2317
+ }
2318
+
2319
+ function appendEvidenceCleanupWarning(receipt, publication) {
2320
+ if (publication?.status !== 'committed-with-warning') return false;
2321
+ const committedStatus = receipt.status;
2322
+ const cleanupErrors = publication.cleanupErrors || [];
2323
+ const cleanupMessage = publication.recoveryDirectory
2324
+ ? `The evidence set was committed, but cleanup is incomplete. Recovery directory: "${publication.recoveryDirectory}".`
2325
+ : 'The evidence set was committed, but cleanup is incomplete.';
2326
+ receipt.ok = false;
2327
+ receipt.status = 'fail';
2328
+ receipt.error = receipt.error ? `${receipt.error} ${cleanupMessage}` : cleanupMessage;
2329
+ receipt.publication = {
2330
+ status: publication.status,
2331
+ committedReceipt: publication.committedReceipt,
2332
+ ...(publication.recoveryDirectory
2333
+ ? { recoveryDirectory: publication.recoveryDirectory } : {}),
2334
+ cleanupErrors,
2335
+ committedStatus,
2336
+ };
2337
+ receipt.diagnostics = [...(receipt.diagnostics || []), failureDiagnostic({
2338
+ code: 'viewer/evidence-cleanup-incomplete',
2339
+ severity: 'warning',
2340
+ message: cleanupMessage,
2341
+ subject: {
2342
+ artifact: receipt.artifact?.path,
2343
+ receipt: publication.committedReceipt,
2344
+ },
2345
+ evidence: {
2346
+ publicationStatus: publication.status,
2347
+ ...(publication.recoveryDirectory
2348
+ ? { recoveryDirectory: publication.recoveryDirectory } : {}),
2349
+ cleanupErrors,
2350
+ },
2351
+ supportedFixes: publication.recoveryDirectory
2352
+ ? [`inspect and safely retire the retained files under "${publication.recoveryDirectory}"`]
2353
+ : ['resolve the reported filesystem cleanup failure before rerunning visual-check'],
2354
+ })];
2355
+ return true;
2356
+ }
2357
+
2358
+ function publishReceiptOnly(artifactPath, outputs, receipt, ownership) {
2359
+ const cleanupErrors = cleanupStagedEvidence(ownership);
2360
+ if (cleanupErrors.length) {
2361
+ const failure = evidenceWriteFailure(
2362
+ artifactPath,
2363
+ 'visual-check could not safely retire this run\'s incomplete staged evidence.',
2364
+ cleanupErrors,
2365
+ );
2366
+ cleanupStagedEvidence(ownership, { removeDirectory: true });
2367
+ ownership.active = false;
2368
+ return failure;
2369
+ }
2370
+ try {
2371
+ writeStagedEvidence(ownership, outputs.receipt, `${JSON.stringify(receipt, null, 2)}\n`);
2372
+ } catch (error) {
2373
+ const failure = evidenceWriteFailure(
2374
+ artifactPath,
2375
+ 'visual-check could not stage its evidence receipt.',
2376
+ [{ file: stagedPathFor(ownership, outputs.receipt), reason: error.message }],
2377
+ );
2378
+ cleanupStagedEvidence(ownership, { removeDirectory: true });
2379
+ ownership.active = false;
2380
+ return failure;
2381
+ }
2382
+ return commitVisualEvidence(artifactPath, outputs, ownership, [outputs.receipt]);
2383
+ }
2384
+
2385
+ function persistBrowserEvidenceFailure(
2386
+ artifactPath,
2387
+ failure,
2388
+ { outDir, compareSidecarParents = sameParent, ownership, command = 'visual-check', capture = true, captureViewports = CAPTURE_VIEWPORTS } = {},
2389
+ ) {
2390
+ const outputs = evidenceSidecarPaths(artifactPath, { outDir, command, capture, captureViewports });
2391
+ const directory = resolveSidecarDirectory(artifactPath, outputs, compareSidecarParents);
2392
+ const capturedArtifact = readRegularFileContents(artifactPath, {
2393
+ subject: 'failure-artifact',
2394
+ });
2395
+ const artifactBytes = capturedArtifact.ok ? capturedArtifact.bytes : null;
2396
+ const receipt = {
2397
+ ...failure,
2398
+ ok: false, status: 'fail',
2399
+ ...(artifactBytes ? {
2400
+ artifact: {
2401
+ path: path.resolve(artifactPath),
2402
+ sha256: sha256(artifactBytes),
2403
+ bytes: artifactBytes.byteLength,
2404
+ },
2405
+ } : {}),
2406
+ containment: {
2407
+ status: 'fail',
2408
+ policy: 'fit-or-reader-declared-readable-vertical-scroll',
2409
+ viewports: [],
2410
+ },
2411
+ captures: { status: capture ? 'fail' : 'not-requested', screenshots: [], contactSheet: null },
2412
+ sidecars: { ...directory.sidecars, files: [] },
2413
+ };
2414
+ if (!directory.ok) {
2415
+ receipt.error = directory.error;
2416
+ receipt.diagnostics = [...(failure.diagnostics || []), directory.diagnostic];
2417
+ return receipt;
2418
+ }
2419
+ let activeOwnership = ownership;
2420
+ if (!visualEvidenceOwnershipMatches(activeOwnership, artifactPath, outputs)) {
2421
+ if (!artifactBytes) {
2422
+ const conflict = evidencePathConflict(artifactPath, outputs, outputs.receipt, {
2423
+ code: 'artifact-unreadable',
2424
+ });
2425
+ receipt.error = conflict.error;
2426
+ receipt.diagnostics = [...(failure.diagnostics || []), conflict.diagnostic];
2427
+ return receipt;
2428
+ }
2429
+ const preflight = beginVisualEvidenceWrite(artifactPath, artifactBytes, outputs);
2430
+ if (!preflight.ok) {
2431
+ receipt.error = preflight.error;
2432
+ receipt.diagnostics = [...(failure.diagnostics || []), preflight.diagnostic];
2433
+ return receipt;
2434
+ }
2435
+ activeOwnership = preflight.ownership;
2436
+ }
2437
+ const publication = publishReceiptOnly(artifactPath, outputs, receipt, activeOwnership);
2438
+ if (publication.ok) publishedBrowserEvidenceReceipts.add(receipt);
2439
+ appendEvidencePublicationFailure(receipt, publication);
2440
+ appendEvidenceCleanupWarning(receipt, publication);
2441
+ return receipt;
2442
+ }
2443
+
2444
+ async function runBrowserEvidence({
2445
+ artifactPath,
2446
+ outDir,
2447
+ chromePath,
2448
+ resolveChrome = findChrome,
2449
+ browserFactory = async (resolvedChrome) => new ChromeVisualBrowser(resolvedChrome),
2450
+ deliveryProvenance,
2451
+ verifyArtifact,
2452
+ compareSidecarParents = sameParent,
2453
+ command, capture,
2454
+ } = {}) {
2455
+ if (!artifactPath) throw new Error(`${command} requires one delivered HTML artifact.`);
2456
+ const artifact = path.resolve(artifactPath);
2457
+ if (!/\.html?$/i.test(artifact)) throw new Error(`${command} requires an .html artifact.`);
2458
+ const capturedArtifact = captureRegularFileBinding(artifact, {
2459
+ subject: 'visual-check-artifact',
2460
+ expectedLinks: 1,
2461
+ includeContent: true,
2462
+ });
2463
+ if (capturedArtifact.status !== 'captured') {
2464
+ throw regularFileCaptureError('The visual-check artifact', capturedArtifact);
2465
+ }
2466
+ const artifactBytes = capturedArtifact.content.buffer;
2467
+ const explainer = isExplainerHtml(artifactBytes.toString('utf8'));
2468
+ const inspectionViewports = explainer ? EXPLAINER_VIEWPORTS : VISUAL_CHECK_VIEWPORTS;
2469
+ const captureViewports = explainer ? EXPLAINER_VIEWPORTS : CAPTURE_VIEWPORTS;
2470
+ const observe = explainer ? explainerObservation : observation;
2471
+ try {
2472
+ const outputs = evidenceSidecarPaths(artifact, { outDir, command, capture, captureViewports });
2473
+ const directory = resolveSidecarDirectory(artifact, outputs, compareSidecarParents);
2474
+ const receipt = baseReceipt({
2475
+ artifactPath: artifact,
2476
+ artifact: artifactBytes,
2477
+ sidecars: directory.sidecars,
2478
+ chrome: { status: 'not-checked', executable: null },
2479
+ deliveryProvenance, command, capture,
2480
+ });
2481
+ if (explainer) {
2482
+ receipt.family = 'explainer';
2483
+ receipt.viewportPolicy = 'explainer-desktop-v1';
2484
+ receipt.containment.policy = 'horizontal-containment-readable-document-scroll';
2485
+ }
2486
+ if (!directory.ok) {
2487
+ receipt.error = directory.error;
2488
+ receipt.diagnostics = [directory.diagnostic];
2489
+ return { exitCode: EXIT.fail, receipt };
2490
+ }
2491
+ const preflight = beginVisualEvidenceWrite(artifact, artifactBytes, outputs);
2492
+ if (!preflight.ok) {
2493
+ receipt.error = preflight.error;
2494
+ receipt.diagnostics = [preflight.diagnostic];
2495
+ return { exitCode: EXIT.fail, receipt };
2496
+ }
2497
+ const ownership = preflight.ownership;
2498
+ let inspectionArtifact;
2499
+ try {
2500
+ // Chrome's file loader cannot reliably open long Windows/UNC paths. Keep
2501
+ // the one inspected snapshot local; publish evidence on its target volume.
2502
+ ownership.inspection = {
2503
+ directory: fs.mkdtempSync(path.join(os.tmpdir(), 'archify-inspection-')),
2504
+ };
2505
+ const stat = fs.lstatSync(ownership.inspection.directory, { bigint: true });
2506
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.ino === 0n) {
2507
+ throw new Error('the private inspection directory has no stable identity');
2508
+ }
2509
+ ownership.inspection.identity = fileIdentity(stat);
2510
+ inspectionArtifact = path.join(ownership.inspection.directory, 'artifact-snapshot.html');
2511
+ ownership.stagingPaths.set(artifact, inspectionArtifact);
2512
+ writeStagedEvidence(ownership, artifact, artifactBytes);
2513
+ } catch (error) {
2514
+ return { exitCode: EXIT.fail, receipt: persistBrowserEvidenceFailure(artifact, {
2515
+ ...receipt,
2516
+ status: 'fail',
2517
+ ok: false,
2518
+ error: `visual-check could not stage its private artifact snapshot: ${error.message}`,
2519
+ diagnostics: [failureDiagnostic({
2520
+ code: 'viewer/artifact-snapshot',
2521
+ message: 'visual-check could not bind a private artifact snapshot.',
2522
+ subject: { artifact },
2523
+ evidence: { reason: error.message },
2524
+ supportedFixes: ['retry after resolving the reported staging filesystem error'],
2525
+ })],
2526
+ }, { outDir, compareSidecarParents, ownership, command, capture, captureViewports }) };
2527
+ }
2528
+ const verifyInspectionArtifact = () => {
2529
+ const entry = ownership.stagedEntries.get(artifact);
2530
+ if (!entry || !currentEvidenceMatches(entry.path, entry.identity, entry.evidence)) {
2531
+ throw new Error('The private visual-check artifact snapshot changed during inspection.');
2532
+ }
2533
+ };
2534
+ try {
2535
+ verifyArtifact?.(artifactBytes);
2536
+ } catch (error) {
2537
+ return { exitCode: EXIT.fail, receipt: persistBrowserEvidenceFailure(artifact, {
2538
+ schemaVersion: 1, command, evidenceKind: 'automated-browser', visualReview: capture ? 'pending' : 'not-requested',
2539
+ artifact: { path: artifact, sha256: sha256(artifactBytes), bytes: artifactBytes.byteLength },
2540
+ provenance: error.deliveryProvenance?.status, error: error.message,
2541
+ diagnostics: error.archifyDiagnostics || [],
2542
+ }, { outDir, compareSidecarParents, ownership, command, capture, captureViewports }) };
2543
+ }
2544
+
2545
+ const resolvedChrome = chromePath || resolveChrome();
2546
+ receipt.chrome = resolvedChrome
2547
+ ? { status: 'available', executable: resolvedChrome }
2548
+ : { status: 'unavailable', executable: null };
2549
+
2550
+ if (!resolvedChrome) {
2551
+ receipt.status = 'skipped';
2552
+ receipt.containment.status = 'skipped';
2553
+ receipt.readability.status = 'skipped';
2554
+ receipt.viewerChrome.status = 'skipped';
2555
+ receipt.themeStates.status = 'skipped';
2556
+ if (capture) receipt.captures.status = 'skipped';
2557
+ receipt.error = 'No supported browser found. Install Chrome/Chromium (or Microsoft Edge), or set ARCHIFY_CHROME to its executable path.';
2558
+ receipt.diagnostics = [failureDiagnostic({
2559
+ code: 'viewer/chrome-unavailable',
2560
+ severity: 'warning',
2561
+ message: receipt.error,
2562
+ subject: { artifact },
2563
+ evidence: { executable: null },
2564
+ supportedFixes: [`set ARCHIFY_CHROME to a Chrome/Chromium executable (or Microsoft Edge) and rerun ${command}`],
2565
+ })];
2566
+ const publication = publishReceiptOnly(artifact, outputs, receipt, ownership);
2567
+ if (publication.ok) publishedBrowserEvidenceReceipts.add(receipt);
2568
+ if (!publication.ok) {
2569
+ appendEvidencePublicationFailure(receipt, publication);
2570
+ return { exitCode: EXIT.fail, receipt };
2571
+ }
2572
+ if (appendEvidenceCleanupWarning(receipt, publication)) {
2573
+ return { exitCode: EXIT.fail, receipt };
2574
+ }
2575
+ return { exitCode: EXIT.skipped, receipt };
2576
+ }
2577
+
2578
+ let browser;
2579
+ try {
2580
+ browser = await browserFactory(resolvedChrome);
2581
+ const observations = new Map();
2582
+ const screenshotsByKey = new Map(outputs.screenshots.map((entry, index) => [
2583
+ screenshotKey(entry.width, entry.height, entry.theme),
2584
+ { ...entry, stagedPath: ownership.stagedOutputs.screenshots[index].path },
2585
+ ]));
2586
+
2587
+ try {
2588
+ const inspect = (options) => explainer ? inspectExplainerBrowser(browser, options) : browser.inspect(options);
2589
+ for (const viewport of inspectionViewports) {
2590
+ const key = screenshotKey(viewport.width, viewport.height, 'light');
2591
+ const screenshot = screenshotsByKey.get(key);
2592
+ const metrics = await inspect({
2593
+ artifactPath: inspectionArtifact,
2594
+ ...viewport,
2595
+ theme: 'light',
2596
+ ...(screenshot ? {
2597
+ screenshotPath: screenshot.stagedPath,
2598
+ writeScreenshot: (bytes) => writeStagedEvidence(ownership, screenshot.path, bytes),
2599
+ } : {}),
2600
+ });
2601
+ verifyInspectionArtifact();
2602
+ if (screenshot) {
2603
+ if (screenshot && !ownership.stagedEntries.has(screenshot.path)) {
2604
+ registerStagedEvidence(ownership, screenshot.path);
2605
+ } else {
2606
+ const staged = ownership.stagedEntries.get(screenshot.path);
2607
+ if (!currentEvidenceMatches(staged.path, staged.identity, staged.evidence)) {
2608
+ throw new Error('The staged visual-check screenshot changed after capture.');
2609
+ }
2610
+ }
2611
+ }
2612
+ observations.set(key, observe({ ...viewport, theme: 'light', metrics }));
2613
+ }
2614
+ for (const viewport of captureViewports) {
2615
+ const key = screenshotKey(viewport.width, viewport.height, 'dark');
2616
+ const screenshot = screenshotsByKey.get(key);
2617
+ const metrics = await inspect({
2618
+ artifactPath: inspectionArtifact,
2619
+ ...viewport,
2620
+ theme: 'dark',
2621
+ ...(screenshot ? {
2622
+ screenshotPath: screenshot.stagedPath,
2623
+ writeScreenshot: (bytes) => writeStagedEvidence(ownership, screenshot.path, bytes),
2624
+ } : {}),
2625
+ });
2626
+ verifyInspectionArtifact();
2627
+ if (screenshot && !ownership.stagedEntries.has(screenshot.path)) {
2628
+ registerStagedEvidence(ownership, screenshot.path);
2629
+ } else if (screenshot) {
2630
+ const staged = ownership.stagedEntries.get(screenshot.path);
2631
+ if (!currentEvidenceMatches(staged.path, staged.identity, staged.evidence)) {
2632
+ throw new Error('The staged visual-check screenshot changed after capture.');
2633
+ }
2634
+ }
2635
+ observations.set(key, observe({ ...viewport, theme: 'dark', metrics }));
2636
+ }
2637
+
2638
+ } finally {
2639
+ if (browser?.close) await browser.close();
2640
+ }
2641
+
2642
+ let artifactVerification = verifyRegularFileBinding(capturedArtifact.binding);
2643
+ if (artifactVerification.status !== 'match') {
2644
+ throw regularFileCaptureError(`The delivered artifact changed while ${command} was running`, artifactVerification);
2645
+ }
2646
+ verifyArtifact?.(artifactBytes);
2647
+ artifactVerification = verifyRegularFileBinding(capturedArtifact.binding);
2648
+ if (artifactVerification.status !== 'match') {
2649
+ throw regularFileCaptureError(`The delivered artifact changed while ${command} was running`, artifactVerification);
2650
+ }
2651
+
2652
+ receipt.containment.viewports = inspectionViewports.map(({ width, height }) => (
2653
+ observations.get(screenshotKey(width, height, 'light'))
2654
+ ));
2655
+ receipt.readability.viewports = receipt.containment.viewports.map((entry) => ({ ...entry }));
2656
+ receipt.viewerChrome.viewports = receipt.containment.viewports.map((entry) => ({ ...entry }));
2657
+ receipt.captures.screenshots = outputs.screenshots.map((entry) => ({
2658
+ ...observations.get(screenshotKey(entry.width, entry.height, entry.theme)),
2659
+ file: path.basename(entry.path),
2660
+ }));
2661
+ const allObservations = [...observations.values()];
2662
+ receipt.themeStates.viewports = allObservations.map((entry) => ({
2663
+ width: entry.width,
2664
+ height: entry.height,
2665
+ requestedTheme: entry.theme,
2666
+ resolvedTheme: entry.resolvedTheme,
2667
+ ok: entry.resolvedTheme === entry.theme,
2668
+ }));
2669
+ const themeStatePass = receipt.themeStates.viewports.every(entry => entry.ok);
2670
+ const containmentPass = allObservations.every((entry) => entry.ok);
2671
+ const readabilityPass = receipt.readability.viewports.every((entry) => entry.readabilityOk);
2672
+ const viewerChromePass = allObservations.every((entry) => entry.viewerChromeOk);
2673
+ receipt.diagnostics = (explainer ? explainerObservationDiagnostics : observationDiagnostics)({
2674
+ artifact,
2675
+ allObservations,
2676
+ readabilityObservations: receipt.readability.viewports, command,
2677
+ });
2678
+ receipt.themeStates.status = themeStatePass ? 'pass' : 'fail';
2679
+ receipt.containment.status = containmentPass ? 'pass' : 'fail';
2680
+ receipt.readability.status = readabilityPass ? 'pass' : 'fail';
2681
+ receipt.viewerChrome.status = viewerChromePass ? 'pass' : 'fail';
2682
+ if (capture) {
2683
+ receipt.captures.status = 'pass';
2684
+ receipt.captures.contactSheet = path.basename(outputs.contactSheet);
2685
+ }
2686
+ if (explainer) {
2687
+ receipt.containment.viewports = allObservations.map(entry => ({ ...entry }));
2688
+ receipt.readability.viewports = allObservations.map(entry => ({ ...entry }));
2689
+ receipt.viewerChrome.viewports = allObservations.map(entry => ({ ...entry }));
2690
+ receipt.commonQa = { status: allObservations.every(e => e.consoleErrors.length === 0 && e.duplicateIds.length === 0 && e.keyboardIssues.length === 0 && e.keyboardTraversal?.ok) ? 'pass' : 'fail', observations: allObservations.map(e => ({width:e.width,theme:e.theme,ok:e.consoleErrors.length===0&&e.duplicateIds.length===0&&e.keyboardIssues.length===0&&e.keyboardTraversal?.ok===true})) };
2691
+ receipt.interactions = { status: allObservations.every(e => e.interactionFailures.length === 0) ? 'pass' : 'fail', observations: allObservations.map(e => ({width:e.width,theme:e.theme,ok:e.interactionFailures.length===0,failures:e.interactionFailures})) };
2692
+ receipt.references = { status: allObservations.every(e => e.references.length === 0) ? 'pass' : 'fail', observations: allObservations.map(e => ({width:e.width,theme:e.theme,ok:e.references.length===0,failures:e.references})) };
2693
+ receipt.noJavaScript = { status: allObservations.every(e => e.noJavaScript.every(n => n.ok)) ? 'pass' : 'fail', observations: allObservations.map(e => ({width:e.width,theme:e.theme,ok:e.noJavaScript.every(n=>n.ok),states:e.noJavaScript})) };
2694
+ receipt.print = { status: allObservations.every(e => e.print.ok) ? 'pass' : 'fail', observations: allObservations.map(e => ({width:e.width,...e.print})) };
2695
+ }
2696
+ receipt.ok = containmentPass && themeStatePass && readabilityPass && viewerChromePass && (!explainer || receipt.diagnostics.length === 0);
2697
+ receipt.status = receipt.ok ? 'pass' : 'fail';
2698
+ if (capture) writeStagedEvidence(ownership, outputs.contactSheet, contactSheetHtml({
2699
+ artifactPath: artifact,
2700
+ receipt,
2701
+ screenshots: receipt.captures.screenshots,
2702
+ }));
2703
+ recordVisualEvidenceFiles(receipt, outputs, ownership);
2704
+ writeStagedEvidence(ownership, outputs.receipt, `${JSON.stringify(receipt, null, 2)}\n`);
2705
+ const publication = commitVisualEvidence(
2706
+ artifact,
2707
+ outputs,
2708
+ ownership,
2709
+ visualEvidenceTargets(outputs).map((target) => target.path),
2710
+ );
2711
+ if (!publication.ok) {
2712
+ appendEvidencePublicationFailure(receipt, publication);
2713
+ receipt.ok = false;
2714
+ receipt.status = 'fail';
2715
+ return { exitCode: EXIT.fail, receipt };
2716
+ }
2717
+ publishedBrowserEvidenceReceipts.add(receipt);
2718
+ if (appendEvidenceCleanupWarning(receipt, publication)) {
2719
+ return { exitCode: EXIT.fail, receipt };
2720
+ }
2721
+ return { exitCode: receipt.ok ? EXIT.pass : EXIT.fail, receipt };
2722
+ } catch (error) {
2723
+ const startupTimeout = error.code === 'ERR_CHROME_CDP_TIMEOUT'
2724
+ && error.method === 'Target.getTargets';
2725
+ receipt.status = 'fail';
2726
+ receipt.ok = false;
2727
+ receipt.error = error.message;
2728
+ receipt.containment.status = 'fail';
2729
+ receipt.readability.status = 'fail';
2730
+ receipt.viewerChrome.status = 'fail';
2731
+ receipt.themeStates.status = 'fail';
2732
+ receipt.captures.status = capture ? 'fail' : 'not-requested';
2733
+ receipt.captures.screenshots = [];
2734
+ receipt.captures.contactSheet = null;
2735
+ if (error.deliveryProvenance) receipt.provenance = error.deliveryProvenance.status;
2736
+ receipt.diagnostics = error.archifyDiagnostics || [failureDiagnostic({
2737
+ code: error.code === 'ARCHIFY_TEMP_CLEANUP' ? 'viewer/temp-cleanup-incomplete'
2738
+ : startupTimeout ? 'viewer/chrome-startup-timeout' : `viewer/${command}-runtime`,
2739
+ message: error.code === 'ARCHIFY_TEMP_CLEANUP'
2740
+ ? 'Browser cleanup could not safely finish; inspect the reported retained path.'
2741
+ : startupTimeout
2742
+ ? 'Chrome did not finish its initial DevTools handshake within the startup window.'
2743
+ : `${command} could not complete its Chrome inspection.`,
2744
+ subject: { artifact },
2745
+ evidence: { reason: error.message, ...(error.directory ? { retainedDirectory: error.directory } : {}) },
2746
+ supportedFixes: error.code === 'ARCHIFY_TEMP_CLEANUP'
2747
+ ? ['resolve the reported process or filesystem failure; verify directory ownership before manual cleanup']
2748
+ : startupTimeout
2749
+ ? [
2750
+ 'do not edit or simplify the artifact because this is a browser-startup failure',
2751
+ `retry ${command} once after host load subsides; if it repeats, stop and report the environment failure`,
2752
+ ]
2753
+ : [`resolve the reported Chrome inspection error, then rerun ${command}`],
2754
+ })];
2755
+ return {
2756
+ exitCode: EXIT.fail,
2757
+ receipt: persistBrowserEvidenceFailure(artifact, receipt, {
2758
+ outDir,
2759
+ compareSidecarParents,
2760
+ ownership, command, capture, captureViewports,
2761
+ }),
2762
+ };
2763
+ }
2764
+ } finally {
2765
+ releaseRegularFileBinding(capturedArtifact.binding);
2766
+ }
2767
+ }
2768
+
2769
+ export function persistVisualCheckFailure(artifactPath, failure, options = {}) {
2770
+ return persistBrowserEvidenceFailure(artifactPath, failure, { ...options, command: 'visual-check', capture: true });
2771
+ }
2772
+ export function persistBrowserCheckFailure(artifactPath, failure, options = {}) {
2773
+ return persistBrowserEvidenceFailure(artifactPath, failure, { ...options, command: 'browser-check', capture: false });
2774
+ }
2775
+ export function runVisualCheck(options = {}) {
2776
+ return runBrowserEvidence({ ...options, command: 'visual-check', capture: true });
2777
+ }
2778
+ export function runBrowserCheck(options = {}) {
2779
+ return runBrowserEvidence({ ...options, command: 'browser-check', capture: false });
2780
+ }