rtl-analyzer 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +90 -56
- package/dist/cli.js +18 -1
- package/dist/codemod.js +50 -12
- package/dist/companion-security.js +2 -0
- package/dist/contextual-preview-bridge.js +118 -0
- package/dist/contextual-preview.js +74 -0
- package/dist/controlled-apply.js +222 -0
- package/dist/css-configured-proposal.js +98 -0
- package/dist/css-directional.js +60 -0
- package/dist/css-icons.js +51 -0
- package/dist/css-spacing.js +65 -0
- package/dist/dashboard-batch-review.js +37 -0
- package/dist/dashboard-client.js +73 -50
- package/dist/dashboard-contextual-preview.js +127 -0
- package/dist/dashboard-data.js +4 -4
- package/dist/dashboard-embedded-preview.js +202 -0
- package/dist/dashboard-html.js +13 -10
- package/dist/dashboard-operation-flow.js +47 -0
- package/dist/dashboard-review-details.js +175 -0
- package/dist/dashboard-review-navigation.js +19 -0
- package/dist/dashboard-review-workflow.js +219 -0
- package/dist/dashboard-themes.js +34 -0
- package/dist/directional-properties.js +53 -0
- package/dist/discovery.js +1 -2
- package/dist/eligibility.js +8 -8
- package/dist/evidence-store.js +110 -0
- package/dist/example-preview-mappings.js +98 -0
- package/dist/manual-change-store.js +27 -0
- package/dist/migration-lifecycle.js +19 -0
- package/dist/original-preview-runtime.js +78 -0
- package/dist/output-path.js +65 -0
- package/dist/page-navigation.js +17 -0
- package/dist/policy-validation.js +7 -4
- package/dist/preview-cli.js +22 -0
- package/dist/preview-companion.js +649 -0
- package/dist/preview-configuration.js +171 -0
- package/dist/preview-runtime.js +102 -0
- package/dist/project-configuration.js +48 -0
- package/dist/project-root.js +12 -0
- package/dist/react-inline.js +65 -0
- package/dist/report-publisher.js +4 -7
- package/dist/review-approval.js +9 -0
- package/dist/review-session.js +211 -56
- package/dist/review-store.js +175 -0
- package/dist/review-workflow.js +820 -0
- package/dist/rules.js +27 -17
- package/dist/runtime-process.js +35 -0
- package/dist/scan-history.js +35 -0
- package/dist/scan-manifest-store.js +26 -0
- package/dist/scan.js +55 -4
- package/dist/scoped-direction-evidence.js +117 -0
- package/dist/serialization.js +1 -0
- package/dist/source-context.js +93 -0
- package/dist/source-snippets.js +3 -3
- package/dist/standalone-cli.js +14 -1
- package/dist/tailwind.js +3 -1
- package/dist/transformations.js +34 -0
- package/dist/validation.js +75 -0
- package/dist/workflow-validation.js +46 -0
- package/package.json +17 -8
|
@@ -0,0 +1,820 @@
|
|
|
1
|
+
import { captureScopedDirectionEvidence, sameScopedDirectionEvidence } from './scoped-direction-evidence.js';
|
|
2
|
+
import { initializeOriginalPreview } from './original-preview-runtime.js';
|
|
3
|
+
import { configuredWorkflowChecks, workflowValidationPresentation, workflowValidationEvidenceIssue } from './workflow-validation.js';
|
|
4
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
5
|
+
import { mkdir, readFile, readdir, rename, realpath, writeFile } from 'node:fs/promises';
|
|
6
|
+
import { dirname, join } from 'node:path';
|
|
7
|
+
import { execFile } from 'node:child_process';
|
|
8
|
+
import { promisify } from 'node:util';
|
|
9
|
+
import { chromium } from '@playwright/test';
|
|
10
|
+
import { loadProjectConfiguration, PROJECT_CONFIGURATION } from './project-configuration.js';
|
|
11
|
+
import { previewConfigurationDigest, loadPreviewConfiguration, configuredMapping, routeUrl } from './preview-configuration.js';
|
|
12
|
+
import { scan } from './scan.js';
|
|
13
|
+
import { retryAcrossNavigation } from './page-navigation.js';
|
|
14
|
+
import { verifiedSourceTransition } from './source-context.js';
|
|
15
|
+
import { directionRequirement, proposeTransformation } from './transformations.js';
|
|
16
|
+
import { approvedPreviewForSource } from './preview-manifest.js';
|
|
17
|
+
import { createReviewSession, startCandidateRuntime, stopCandidateRuntime, validateProjectSourcePath, REVIEW_SOURCE } from './review-session.js';
|
|
18
|
+
const run = promisify(execFile);
|
|
19
|
+
const sha = (text) => createHash('sha256').update(text).digest('hex');
|
|
20
|
+
/** Patches always address immutable originals. Recomposition avoids drift and removes only the rejected edit. */
|
|
21
|
+
export function composeWorkflowFile(before, patches) {
|
|
22
|
+
const sorted = [...patches].sort((a, b) => b.startOffset - a.startOffset);
|
|
23
|
+
let boundary = before.length;
|
|
24
|
+
let result = before;
|
|
25
|
+
for (const p of sorted) {
|
|
26
|
+
if (!Number.isInteger(p.startOffset) || !Number.isInteger(p.endOffset) || p.startOffset < 0 || p.endOffset <= p.startOffset || p.endOffset > boundary)
|
|
27
|
+
throw new Error('OVERLAPPING_OR_INVALID_PATCH');
|
|
28
|
+
if (sha(before.slice(p.startOffset, p.endOffset)) !== p.expectedSha256)
|
|
29
|
+
throw new Error('STALE_PATCH_RANGE');
|
|
30
|
+
result = result.slice(0, p.startOffset) + p.replacement + result.slice(p.endOffset);
|
|
31
|
+
boundary = p.startOffset;
|
|
32
|
+
}
|
|
33
|
+
return result;
|
|
34
|
+
}
|
|
35
|
+
const included = (e) => !!e.patch && e.applied && !['Rejected', 'Deferred', 'Flagged'].includes(e.decision);
|
|
36
|
+
/** Entries whose patches the candidate files contain. In one-by-one review the candidate is a per-finding preview: it holds only the
|
|
37
|
+
* focused finding, so Live After always equals that finding's code diff. Validate and Apply recompose from accepted entries only. */
|
|
38
|
+
export const candidateEntries = (w) => {
|
|
39
|
+
const focus = w.mode === 'one-by-one' && w.previewFocus ? w.entries.find(e => e.finding.id === w.previewFocus && included(e)) : undefined;
|
|
40
|
+
return focus ? [focus] : w.entries.filter(included);
|
|
41
|
+
};
|
|
42
|
+
const signature = (w) => sha(JSON.stringify(w.entries.filter(e => e.decision === 'Accepted' && included(e)).map(e => e.patch)));
|
|
43
|
+
export class ReviewWorkflowStore {
|
|
44
|
+
root;
|
|
45
|
+
path;
|
|
46
|
+
applyService;
|
|
47
|
+
originalOrigin;
|
|
48
|
+
workflows = [];
|
|
49
|
+
queue = Promise.resolve();
|
|
50
|
+
constructor(root, path, applyService, originalOrigin = 'http://127.0.0.1:4200') {
|
|
51
|
+
this.root = root;
|
|
52
|
+
this.path = path;
|
|
53
|
+
this.applyService = applyService;
|
|
54
|
+
this.originalOrigin = originalOrigin;
|
|
55
|
+
}
|
|
56
|
+
async load() {
|
|
57
|
+
try {
|
|
58
|
+
const data = JSON.parse(await readFile(this.path, 'utf8'));
|
|
59
|
+
if (data.version !== 1 || !Array.isArray(data.workflows))
|
|
60
|
+
throw new Error('WORKFLOW_STORE_INVALID');
|
|
61
|
+
this.workflows = data.workflows.filter(w => w.root === this.root);
|
|
62
|
+
const current = await scan(this.root);
|
|
63
|
+
for (const w of this.workflows) {
|
|
64
|
+
if (w.state === 'Reviewing' && w.inputDigest === current.inputDigest && w.policyDigest === current.policyDigest) {
|
|
65
|
+
const ids = new Set(current.findings.filter(f => !['INFORMATIONAL', 'INTENTIONAL_LTR'].includes(f.category) && f.ruleId !== 'RTL.RUNTIME.DIRECTION_UNKNOWN').map(f => f.id));
|
|
66
|
+
w.entries = w.entries.filter(e => !!e.patch || ids.has(e.finding.id));
|
|
67
|
+
for (const e of w.entries)
|
|
68
|
+
if (!e.patch)
|
|
69
|
+
e.reason = e.finding.rationale + ' ' + e.finding.treatment + ' No supported candidate patch; approval unavailable.';
|
|
70
|
+
}
|
|
71
|
+
for (const op of w.operations ?? [])
|
|
72
|
+
if (op.state === 'Running') {
|
|
73
|
+
op.state = 'Uncertain';
|
|
74
|
+
op.error = 'Server restarted during operation. Inspect operation details and source receipts before retrying.';
|
|
75
|
+
}
|
|
76
|
+
if (w.session)
|
|
77
|
+
w.session.runtime = undefined;
|
|
78
|
+
if (w.state === 'Applying')
|
|
79
|
+
w.receipts = await this.applyService.recoverAcceptedFileReceipts(w.id);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
if (error.code !== 'ENOENT')
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
async persist() {
|
|
88
|
+
await mkdir(dirname(this.path), { recursive: true, mode: 0o700 });
|
|
89
|
+
const tmp = `${this.path}.${randomUUID()}.tmp`;
|
|
90
|
+
await writeFile(tmp, JSON.stringify({ version: 1, workflows: this.workflows }, null, 2), { flag: 'wx', mode: 0o600 });
|
|
91
|
+
await rename(tmp, this.path);
|
|
92
|
+
}
|
|
93
|
+
exclusive(operation) {
|
|
94
|
+
const result = this.queue.then(operation);
|
|
95
|
+
this.queue = result.catch(() => undefined);
|
|
96
|
+
return result;
|
|
97
|
+
}
|
|
98
|
+
list() { return [...this.workflows].reverse(); }
|
|
99
|
+
get(id) { const w = this.workflows.find(w => w.id === id); if (!w)
|
|
100
|
+
throw new Error('WORKFLOW_NOT_FOUND'); return w; }
|
|
101
|
+
find(inputDigest, policyDigest, mode) { return [...this.workflows].reverse().find(w => w.inputDigest === inputDigest && w.policyDigest === policyDigest && w.mode === mode); }
|
|
102
|
+
async begin(input, resuming) {
|
|
103
|
+
if (!['one-by-one', 'apply-first'].includes(input.mode))
|
|
104
|
+
throw new Error('INVALID_WORKFLOW_MODE');
|
|
105
|
+
const scope = input.scope ?? [];
|
|
106
|
+
if (!Array.isArray(scope) || scope.some(p => typeof p !== 'string'))
|
|
107
|
+
throw new Error('INVALID_WORKFLOW_SCOPE');
|
|
108
|
+
const prior = this.find(input.inputDigest, input.policyDigest, input.mode);
|
|
109
|
+
const restartable = prior && ['Rolled Back', 'Reviewing'].includes(prior.state);
|
|
110
|
+
if (prior && !resuming && !(input.restart === true && restartable)) {
|
|
111
|
+
if (JSON.stringify(prior.scope) !== JSON.stringify(scope))
|
|
112
|
+
throw new Error('WORKFLOW_SCOPE_MISMATCH');
|
|
113
|
+
return prior;
|
|
114
|
+
}
|
|
115
|
+
const report = await scan(this.root);
|
|
116
|
+
if (report.inputDigest !== input.inputDigest || report.policyDigest !== input.policyDigest)
|
|
117
|
+
throw new Error('DASHBOARD_SOURCE_IDENTITY_MISMATCH');
|
|
118
|
+
if (scope.some(path => !report.files.includes(path)))
|
|
119
|
+
throw new Error('INVALID_WORKFLOW_SCOPE');
|
|
120
|
+
const previewConfigDigest = await previewConfigurationDigest(this.root);
|
|
121
|
+
let configuredFiles = [];
|
|
122
|
+
try {
|
|
123
|
+
configuredFiles = Object.values((await loadPreviewConfiguration(this.root)).applications).flatMap(a => [a.viteConfig, a.entry]);
|
|
124
|
+
}
|
|
125
|
+
catch { /* Invalid preview configuration cannot disable code-only proposals. */ }
|
|
126
|
+
const baseline = {}, sourcePaths = {};
|
|
127
|
+
// Whole scanned source/config identity protects unchanged files too.
|
|
128
|
+
const rootConfigs = (await readdir(this.root)).filter(p => /^(tsconfig.*\.json|(?:vite|vitest|playwright|eslint)(?:\.[\w-]+)*\.config\.[cm]?[jt]s|package-lock\.json|rtl-preview\.config\.json)$/.test(p));
|
|
129
|
+
const project = await loadProjectConfiguration(this.root);
|
|
130
|
+
const projectConfigs = [];
|
|
131
|
+
if (!project) {
|
|
132
|
+
for (const group of ['apps', 'libs'])
|
|
133
|
+
for (const project of await readdir(join(this.root, group))) {
|
|
134
|
+
const directory = join(group, project);
|
|
135
|
+
for (const name of await readdir(join(this.root, directory)))
|
|
136
|
+
if (/^(project\.json|tsconfig.*\.json|vite\.config\.[cm]?[jt]s)$/.test(name))
|
|
137
|
+
projectConfigs.push(join(directory, name));
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const optionalConfigs = await Promise.all(['nx.json', 'rtl-scanner.config.json', PROJECT_CONFIGURATION].map(async (path) => await readFile(join(this.root, path)).then(() => path).catch(error => { if (error.code === 'ENOENT')
|
|
141
|
+
return ''; throw error; })));
|
|
142
|
+
for (const path of [...new Set([...report.files, 'package.json', ...optionalConfigs.filter(Boolean), ...rootConfigs, ...projectConfigs, ...configuredFiles])]) {
|
|
143
|
+
sourcePaths[path] = await validateProjectSourcePath(this.root, path);
|
|
144
|
+
baseline[path] = await readFile(sourcePaths[path], 'utf8');
|
|
145
|
+
}
|
|
146
|
+
const entries = report.findings.filter(f => !['INFORMATIONAL', 'INTENTIONAL_LTR'].includes(f.category) && f.ruleId !== 'RTL.RUNTIME.DIRECTION_UNKNOWN' && (!scope.length || scope.includes(f.path))).map(finding => {
|
|
147
|
+
const entry = { finding, reason: '', applied: false, decision: 'Pending', notes: '', history: [] };
|
|
148
|
+
try {
|
|
149
|
+
if (!report.complete)
|
|
150
|
+
throw new Error('INCOMPLETE_SCAN_REQUIRES_MANUAL_RESOLUTION');
|
|
151
|
+
if (finding.exceptionReason)
|
|
152
|
+
throw new Error('POLICY_EXCEPTION_REQUIRES_REVIEW');
|
|
153
|
+
const proposal = proposeTransformation(finding, baseline[finding.path]);
|
|
154
|
+
entry.patch = proposal.patch;
|
|
155
|
+
entry.reason = proposal.transformationId + ': ' + proposal.reason;
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
entry.reason = `${error instanceof Error ? error.message : 'UNSUPPORTED'}: ${finding.rationale} ${finding.treatment} No supported candidate patch; approval unavailable.`;
|
|
159
|
+
}
|
|
160
|
+
return entry;
|
|
161
|
+
});
|
|
162
|
+
const conflicting = entries.filter(e => e.patch && entries.some(other => other !== e && other.patch && other.patch.path === e.patch.path && other.patch.startOffset < e.patch.endOffset && e.patch.startOffset < other.patch.endOffset));
|
|
163
|
+
for (const e of conflicting) {
|
|
164
|
+
e.reason = 'CONFLICTING_PATCH: overlapping transformations need manual resolution.';
|
|
165
|
+
e.patch = undefined;
|
|
166
|
+
}
|
|
167
|
+
const w = { id: randomUUID(), root: this.root, ...(resuming ? { resumedFrom: resuming.id } : {}), previewConfigDigest, inputDigest: report.inputDigest, policyDigest: report.policyDigest, mode: input.mode, scope, entries, baseline, sourcePaths, state: 'Reviewing', createdAt: new Date().toISOString() };
|
|
168
|
+
if (input.restart && prior && restartable && !resuming) {
|
|
169
|
+
if (prior.session)
|
|
170
|
+
prior.session = await stopCandidateRuntime(prior.session);
|
|
171
|
+
prior.supersededBy = w.id;
|
|
172
|
+
}
|
|
173
|
+
this.workflows.push(w);
|
|
174
|
+
if (!resuming && w.mode === 'apply-first' && entries.some(e => e.patch)) {
|
|
175
|
+
for (const e of entries)
|
|
176
|
+
e.applied = !!e.patch;
|
|
177
|
+
await this.rebuild(w);
|
|
178
|
+
}
|
|
179
|
+
await this.persist();
|
|
180
|
+
return w;
|
|
181
|
+
}
|
|
182
|
+
/** Resume analysis only. Historical decisions, candidates and validation never enter the new review. */
|
|
183
|
+
async runOperation(id, kind, operationId, run) {
|
|
184
|
+
if (!/^[a-zA-Z0-9-]{8,100}$/.test(operationId))
|
|
185
|
+
throw Error('INVALID_OPERATION_ID');
|
|
186
|
+
const w = this.get(id), prior = w.operations?.find(op => op.id === operationId);
|
|
187
|
+
if (prior) {
|
|
188
|
+
if (prior.kind !== kind)
|
|
189
|
+
throw Error('OPERATION_IDENTITY_MISMATCH');
|
|
190
|
+
return w;
|
|
191
|
+
}
|
|
192
|
+
if (w.operations?.some(op => ['Running', 'Uncertain'].includes(op.state)))
|
|
193
|
+
throw Error('OPERATION_RECONCILIATION_REQUIRED');
|
|
194
|
+
const op = { id: operationId, kind, state: 'Running', count: w.entries.filter(e => e.decision === 'Accepted' && included(e)).length, at: new Date().toISOString() };
|
|
195
|
+
(w.operations ??= []).push(op);
|
|
196
|
+
await this.persist();
|
|
197
|
+
try {
|
|
198
|
+
await run();
|
|
199
|
+
op.state = kind === 'apply' ? w.state === 'Applied' ? 'Succeeded' : 'Failed' : w.validation?.state === 'Passed' ? 'Succeeded' : 'Failed';
|
|
200
|
+
if (op.state === 'Failed')
|
|
201
|
+
op.error = w.validation?.checks.filter(c => ['Failed', 'Unavailable', 'Error'].includes(c.state) && !c.name.startsWith('live-preview:')).map(c => c.name + ': ' + c.detail).join('\n') || 'Validation requirements were not satisfied.';
|
|
202
|
+
}
|
|
203
|
+
catch (error) {
|
|
204
|
+
op.state = 'Failed';
|
|
205
|
+
op.error = error instanceof Error ? error.message : String(error);
|
|
206
|
+
if (w.state === 'Applying')
|
|
207
|
+
op.error += ' Source write may be partial; inspect receipts and use protected rollback.';
|
|
208
|
+
}
|
|
209
|
+
await this.persist();
|
|
210
|
+
return w;
|
|
211
|
+
}
|
|
212
|
+
async reviewRemaining(id) {
|
|
213
|
+
const historical = this.get(id);
|
|
214
|
+
if (historical.state !== 'Applied')
|
|
215
|
+
throw Error('SUCCESSFUL_APPLY_REQUIRED');
|
|
216
|
+
const report = await verifiedSourceTransition(this.root, historical), prior = this.workflows.find(w => w.continuedFrom === id);
|
|
217
|
+
if (prior) {
|
|
218
|
+
await this.fresh(prior);
|
|
219
|
+
return prior;
|
|
220
|
+
}
|
|
221
|
+
const next = await this.begin({ inputDigest: report.inputDigest, policyDigest: report.policyDigest, mode: historical.mode, scope: historical.scope }, historical);
|
|
222
|
+
delete next.resumedFrom;
|
|
223
|
+
next.continuedFrom = id;
|
|
224
|
+
for (const old of historical.entries.filter(e => e.decision !== 'Accepted')) {
|
|
225
|
+
const start = old.finding.range.start.offset, end = old.finding.range.end.offset;
|
|
226
|
+
const patches = historical.entries.filter(e => e.finding.path === old.finding.path && e.decision === 'Accepted' && e.applied && e.patch).map(e => e.patch);
|
|
227
|
+
if (patches.some(p => p.startOffset < end && p.endOffset > start))
|
|
228
|
+
continue;
|
|
229
|
+
const shift = patches.filter(p => p.endOffset <= start).reduce((n, p) => n + p.replacement.length - (p.endOffset - p.startOffset), 0);
|
|
230
|
+
const matches = next.entries.filter(e => e.finding.path === old.finding.path && e.finding.ruleId === old.finding.ruleId && e.finding.context === old.finding.context && e.finding.sourceMechanism === old.finding.sourceMechanism && e.finding.original === old.finding.original && e.finding.range.start.offset === start + shift && e.finding.range.end.offset === end + shift);
|
|
231
|
+
const oldMatches = historical.entries.filter(e => e.finding.path === old.finding.path && e.finding.range.start.offset === start && e.finding.range.end.offset === end);
|
|
232
|
+
if (matches.length !== 1 || oldMatches.length !== 1 || historical.baseline[old.finding.path]?.slice(start, end) !== old.finding.original)
|
|
233
|
+
continue;
|
|
234
|
+
const entry = matches[0];
|
|
235
|
+
entry.decision = old.decision;
|
|
236
|
+
entry.notes = old.notes;
|
|
237
|
+
entry.history = [...old.history];
|
|
238
|
+
entry.carriedFrom = { workflowId: id, findingId: old.finding.id, decision: old.decision };
|
|
239
|
+
}
|
|
240
|
+
await this.persist();
|
|
241
|
+
return next;
|
|
242
|
+
}
|
|
243
|
+
async resumeAfterRollback(id) {
|
|
244
|
+
const historical = this.get(id);
|
|
245
|
+
if (historical.state !== 'Rolled Back')
|
|
246
|
+
throw Error('SUCCESSFUL_ROLLBACK_REQUIRED');
|
|
247
|
+
const report = await verifiedSourceTransition(this.root, historical);
|
|
248
|
+
const prior = this.workflows.find(w => w.resumedFrom === id);
|
|
249
|
+
if (prior) {
|
|
250
|
+
await this.fresh(prior);
|
|
251
|
+
return prior;
|
|
252
|
+
}
|
|
253
|
+
return this.begin({ inputDigest: report.inputDigest, policyDigest: report.policyDigest, mode: historical.mode, scope: historical.scope }, historical);
|
|
254
|
+
}
|
|
255
|
+
async fresh(w) {
|
|
256
|
+
if (await previewConfigurationDigest(this.root) !== (w.previewConfigDigest ?? sha('')))
|
|
257
|
+
throw Error('PREVIEW_CONFIGURATION_CHANGED');
|
|
258
|
+
if (await realpath(w.root) !== w.root || w.root !== this.root)
|
|
259
|
+
throw new Error('PROJECT_ROOT_IDENTITY_MISMATCH');
|
|
260
|
+
for (const [path, before] of Object.entries(w.baseline)) {
|
|
261
|
+
const target = await validateProjectSourcePath(this.root, path);
|
|
262
|
+
if (target !== w.sourcePaths[path] || sha(await readFile(target, 'utf8')) !== sha(before))
|
|
263
|
+
throw new Error('STALE_ORIGINAL_SOURCE');
|
|
264
|
+
}
|
|
265
|
+
const report = await scan(this.root);
|
|
266
|
+
if (report.inputDigest !== w.inputDigest || report.policyDigest !== w.policyDigest)
|
|
267
|
+
throw new Error('STALE_PROJECT_IDENTITY');
|
|
268
|
+
}
|
|
269
|
+
async candidateFresh(w) {
|
|
270
|
+
if (!w.session)
|
|
271
|
+
throw new Error('CANDIDATE_REQUIRED');
|
|
272
|
+
for (const [path, before] of Object.entries(w.baseline)) {
|
|
273
|
+
const expected = composeWorkflowFile(before, candidateEntries(w).filter(e => e.patch.path === path).map(e => e.patch));
|
|
274
|
+
const actual = await readFile(await validateProjectSourcePath(w.session.candidateRoot, path), 'utf8');
|
|
275
|
+
if (actual !== expected)
|
|
276
|
+
throw new Error('STALE_CANDIDATE_SOURCE');
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
ensureReviewing(w) { if (w.supersededBy)
|
|
280
|
+
throw new Error('HISTORICAL_REVIEW_LOCKED'); if (w.state !== 'Reviewing')
|
|
281
|
+
throw new Error('WORKFLOW_LOCKED_' + w.state); }
|
|
282
|
+
async rebuild(w) {
|
|
283
|
+
await this.fresh(w);
|
|
284
|
+
if (w.session)
|
|
285
|
+
await this.candidateFresh(w);
|
|
286
|
+
if (!w.session)
|
|
287
|
+
w.session = await createReviewSession(this.root, Object.hasOwn(w.baseline, REVIEW_SOURCE) ? REVIEW_SOURCE : w.entries.find(e => e.patch)?.finding.path);
|
|
288
|
+
if (w.session.runtime)
|
|
289
|
+
w.session = await stopCandidateRuntime(w.session);
|
|
290
|
+
for (const path of new Set(w.entries.filter(e => e.patch).map(e => e.finding.path))) {
|
|
291
|
+
const after = composeWorkflowFile(w.baseline[path], candidateEntries(w).filter(e => e.patch.path === path).map(e => e.patch));
|
|
292
|
+
await writeFile(await validateProjectSourcePath(w.session.candidateRoot, path), after, 'utf8');
|
|
293
|
+
}
|
|
294
|
+
w.session.candidateSha256 = sha(await readFile(join(w.session.candidateRoot, w.session.sourcePath), 'utf8'));
|
|
295
|
+
w.validation = undefined;
|
|
296
|
+
}
|
|
297
|
+
async change(id, findingId, input) {
|
|
298
|
+
const w = this.get(id);
|
|
299
|
+
this.ensureReviewing(w);
|
|
300
|
+
await this.fresh(w);
|
|
301
|
+
const e = w.entries.find(e => e.finding.id === findingId);
|
|
302
|
+
if (!e)
|
|
303
|
+
throw new Error('FINDING_NOT_IN_SCOPE');
|
|
304
|
+
if (!['apply', 'notes', 'Accepted', 'Rejected', 'Deferred', 'Flagged'].includes(input.action))
|
|
305
|
+
throw new Error('INVALID_REVIEW_ACTION');
|
|
306
|
+
if (input.notes !== undefined && (typeof input.notes !== 'string' || input.notes.length > 4000))
|
|
307
|
+
throw new Error('INVALID_REVIEW_NOTES');
|
|
308
|
+
if (input.action === 'notes') {
|
|
309
|
+
e.notes = input.notes ?? '';
|
|
310
|
+
e.history.push({ decision: e.decision, notes: e.notes, at: new Date().toISOString() });
|
|
311
|
+
await this.persist();
|
|
312
|
+
return w;
|
|
313
|
+
}
|
|
314
|
+
if (input.action === 'apply' && !e.patch)
|
|
315
|
+
throw new Error('UNSUPPORTED_TRANSFORMATION');
|
|
316
|
+
if (input.action === 'Accepted' && (!e.patch || !e.applied || ['Rejected', 'Deferred', 'Flagged'].includes(e.decision)))
|
|
317
|
+
throw new Error('APPLY_CANDIDATE_BEFORE_ACCEPTANCE');
|
|
318
|
+
// Check the previous composition before changing membership.
|
|
319
|
+
if (w.session)
|
|
320
|
+
await this.candidateFresh(w);
|
|
321
|
+
const previous = { ...e };
|
|
322
|
+
const previousState = this.previewState(w);
|
|
323
|
+
if (input.action === 'apply') {
|
|
324
|
+
e.applied = true;
|
|
325
|
+
if (['Rejected', 'Deferred', 'Flagged'].includes(e.decision))
|
|
326
|
+
e.decision = 'Pending';
|
|
327
|
+
w.previewFocus = undefined; /* explicit apply composes every applied entry; previews re-focus */
|
|
328
|
+
}
|
|
329
|
+
else {
|
|
330
|
+
e.decision = input.action;
|
|
331
|
+
e.notes = input.notes ?? '';
|
|
332
|
+
if (e.decision !== 'Accepted')
|
|
333
|
+
e.applied = false;
|
|
334
|
+
if (w.previewFocus === e.finding.id && !included(e))
|
|
335
|
+
w.previewFocus = undefined;
|
|
336
|
+
e.history.push({ decision: e.decision, notes: e.notes, at: new Date().toISOString() });
|
|
337
|
+
}
|
|
338
|
+
// Rebuild from original coordinates, not from the previously patched content.
|
|
339
|
+
try {
|
|
340
|
+
await this.writeComposition(w);
|
|
341
|
+
await this.persist();
|
|
342
|
+
return w;
|
|
343
|
+
}
|
|
344
|
+
catch (error) {
|
|
345
|
+
Object.assign(e, previous);
|
|
346
|
+
this.restorePreviewState(w, previousState);
|
|
347
|
+
throw error;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
/** One-by-one invariant: the only pending entry in the candidate is the focused one. Accepted entries keep their membership. */
|
|
351
|
+
focusEntry(w, entry) {
|
|
352
|
+
if (w.mode !== 'one-by-one')
|
|
353
|
+
return;
|
|
354
|
+
for (const other of w.entries)
|
|
355
|
+
if (other !== entry && other.decision === 'Pending')
|
|
356
|
+
other.applied = false;
|
|
357
|
+
w.previewFocus = entry.finding.id;
|
|
358
|
+
}
|
|
359
|
+
previewState(w) { return { focus: w.previewFocus, applied: w.entries.map(e => e.applied) }; }
|
|
360
|
+
restorePreviewState(w, state) { w.previewFocus = state.focus; w.entries.forEach((e, i) => { e.applied = state.applied[i]; }); }
|
|
361
|
+
/** Recompose the candidate from accepted entries only (no preview focus). Used before Apply so validated hashes still match after previews. */
|
|
362
|
+
async restoreAcceptedCandidate(w) {
|
|
363
|
+
if (w.mode !== 'one-by-one' || (!w.previewFocus && !w.entries.some(e => e.decision !== 'Accepted' && e.applied)))
|
|
364
|
+
return;
|
|
365
|
+
if (w.session)
|
|
366
|
+
await this.candidateFresh(w);
|
|
367
|
+
w.previewFocus = undefined;
|
|
368
|
+
for (const e of w.entries)
|
|
369
|
+
if (e.decision !== 'Accepted')
|
|
370
|
+
e.applied = false;
|
|
371
|
+
await this.writeComposition(w, true);
|
|
372
|
+
await this.persist();
|
|
373
|
+
}
|
|
374
|
+
async writeComposition(w, preserveValidation = false) {
|
|
375
|
+
if (!w.session && !candidateEntries(w).length) {
|
|
376
|
+
if (!preserveValidation)
|
|
377
|
+
w.validation = undefined;
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
if (!w.session)
|
|
381
|
+
w.session = await createReviewSession(this.root, Object.hasOwn(w.baseline, REVIEW_SOURCE) ? REVIEW_SOURCE : w.entries.find(e => e.patch)?.finding.path);
|
|
382
|
+
if (w.session.runtime)
|
|
383
|
+
w.session = await stopCandidateRuntime(w.session);
|
|
384
|
+
for (const path of new Set(w.entries.filter(e => e.patch).map(e => e.finding.path)))
|
|
385
|
+
await writeFile(await validateProjectSourcePath(w.session.candidateRoot, path), composeWorkflowFile(w.baseline[path], candidateEntries(w).filter(e => e.patch.path === path).map(e => e.patch)), 'utf8');
|
|
386
|
+
w.session.candidateSha256 = sha(await readFile(join(w.session.candidateRoot, w.session.sourcePath), 'utf8'));
|
|
387
|
+
if (preserveValidation)
|
|
388
|
+
return; // Preview-only recomposition: the accepted set (and its signature) did not change.
|
|
389
|
+
if (w.validation)
|
|
390
|
+
w.validationInvalidation = 'The accepted candidate changed; previous validation no longer applies. Validate the new accepted subset.';
|
|
391
|
+
w.validation = undefined;
|
|
392
|
+
}
|
|
393
|
+
async runtime(id, application) {
|
|
394
|
+
const w = this.get(id);
|
|
395
|
+
await this.fresh(w);
|
|
396
|
+
await this.candidateFresh(w);
|
|
397
|
+
w.session = await startCandidateRuntime(w.session, application);
|
|
398
|
+
await this.persist();
|
|
399
|
+
return w;
|
|
400
|
+
}
|
|
401
|
+
/** Called only after the client verifies the original target. Serialized by Companion.
|
|
402
|
+
* Reuses the current composition/runtime; never changes a decision or applies to source. */
|
|
403
|
+
async preparePreview(id, input) {
|
|
404
|
+
const w = this.get(id);
|
|
405
|
+
this.ensureReviewing(w);
|
|
406
|
+
await this.fresh(w);
|
|
407
|
+
if (input.inputDigest !== w.inputDigest || input.policyDigest !== w.policyDigest)
|
|
408
|
+
throw Error('PREVIEW_SOURCE_IDENTITY_MISMATCH');
|
|
409
|
+
const entry = w.entries.find(e => e.finding.id === input.findingId);
|
|
410
|
+
if (!entry?.patch)
|
|
411
|
+
throw Error(entry?.reason || 'PREVIEW_FIX_UNSUPPORTED');
|
|
412
|
+
if (['Rejected', 'Deferred', 'Flagged'].includes(entry.decision))
|
|
413
|
+
throw Error('PREVIEW_DECISION_' + entry.decision.toUpperCase());
|
|
414
|
+
const mapping = configuredMapping(entry.finding, await loadPreviewConfiguration(this.root));
|
|
415
|
+
if (!mapping.routes.some(r => r.id === input.routeId && r.application === input.application))
|
|
416
|
+
throw Error('PREVIEW_MAPPING_UNAVAILABLE');
|
|
417
|
+
if (w.session)
|
|
418
|
+
await this.candidateFresh(w);
|
|
419
|
+
if (w.mode === 'one-by-one') {
|
|
420
|
+
// Live After must equal this finding's code diff: other pending findings leave the candidate. Validation of the accepted set is kept.
|
|
421
|
+
const unchanged = w.previewFocus === entry.finding.id && entry.applied && !w.entries.some(o => o !== entry && o.decision === 'Pending' && o.applied);
|
|
422
|
+
if (!unchanged) {
|
|
423
|
+
const previousState = this.previewState(w);
|
|
424
|
+
entry.applied = true;
|
|
425
|
+
this.focusEntry(w, entry);
|
|
426
|
+
try {
|
|
427
|
+
await this.writeComposition(w, true);
|
|
428
|
+
await this.persist();
|
|
429
|
+
}
|
|
430
|
+
catch (error) {
|
|
431
|
+
this.restorePreviewState(w, previousState);
|
|
432
|
+
throw error;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
else if (!entry.applied)
|
|
437
|
+
await this.change(id, entry.finding.id, { action: 'apply' });
|
|
438
|
+
const prepared = await this.runtime(id, input.application);
|
|
439
|
+
if (prepared.session?.runtime?.status !== 'healthy')
|
|
440
|
+
throw Error(prepared.session?.runtime?.error || 'CANDIDATE_RUNTIME_UNAVAILABLE');
|
|
441
|
+
if (directionRequirement(entry.finding) === 'dependent')
|
|
442
|
+
await captureScopedDirectionEvidence(this.root, w, [entry], async (application) => { await initializeOriginalPreview(this.root, application); await this.runtime(id, application); });
|
|
443
|
+
return prepared;
|
|
444
|
+
}
|
|
445
|
+
/** Explicit batch preparation verifies real mapped targets before offering batch approval. */
|
|
446
|
+
async prepareBatch(id) {
|
|
447
|
+
const w = this.get(id);
|
|
448
|
+
this.ensureReviewing(w);
|
|
449
|
+
await this.fresh(w);
|
|
450
|
+
if (w.mode !== 'apply-first')
|
|
451
|
+
throw Error('BATCH_MODE_REQUIRED');
|
|
452
|
+
if (w.session)
|
|
453
|
+
await this.candidateFresh(w);
|
|
454
|
+
w.batchPreparation = 'running';
|
|
455
|
+
await this.persist();
|
|
456
|
+
let config;
|
|
457
|
+
try {
|
|
458
|
+
config = await loadPreviewConfiguration(this.root);
|
|
459
|
+
}
|
|
460
|
+
catch { /* Each entry receives an honest mapping blocker. */ }
|
|
461
|
+
for (const e of w.entries) {
|
|
462
|
+
const mapping = config && configuredMapping(e.finding, config);
|
|
463
|
+
const reason = !e.patch ? e.reason : !mapping?.configured || !mapping.routes.length ? 'No verified preview target: explicit page/element mapping is required.' : directionRequirement(e.finding) === 'unknown' ? 'Runtime direction strategy is unknown.' : '';
|
|
464
|
+
e.batch = reason ? { state: 'blocked', reason } : { state: 'ready', reason: 'Prepared in the isolated candidate; pending explicit approval.' };
|
|
465
|
+
if (e.decision === 'Pending')
|
|
466
|
+
e.applied = !reason;
|
|
467
|
+
}
|
|
468
|
+
await this.writeComposition(w);
|
|
469
|
+
await this.persist();
|
|
470
|
+
const targets = w.entries.filter(e => e.batch?.state === 'ready' && !['Rejected', 'Deferred', 'Flagged'].includes(e.decision));
|
|
471
|
+
const verify = (entries) => captureScopedDirectionEvidence(this.root, w, entries, async (application) => { await initializeOriginalPreview(this.root, application); await this.runtime(id, application); });
|
|
472
|
+
if (targets.length)
|
|
473
|
+
try {
|
|
474
|
+
await verify(targets);
|
|
475
|
+
}
|
|
476
|
+
catch {
|
|
477
|
+
// A partially supported batch isolates failures without weakening any target proof.
|
|
478
|
+
for (const e of targets)
|
|
479
|
+
try {
|
|
480
|
+
await verify([e]);
|
|
481
|
+
}
|
|
482
|
+
catch (error) {
|
|
483
|
+
e.batch = { state: 'blocked', reason: 'Preview verification failed: ' + (error instanceof Error ? error.message : String(error)) };
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
const unavailable = targets.filter(e => e.batch?.state === 'blocked' && e.decision === 'Pending');
|
|
487
|
+
for (const e of unavailable)
|
|
488
|
+
e.applied = false;
|
|
489
|
+
if (unavailable.length)
|
|
490
|
+
await this.writeComposition(w);
|
|
491
|
+
w.batchPreparation = 'ready';
|
|
492
|
+
w.batchPreparedAt = new Date().toISOString();
|
|
493
|
+
await this.persist();
|
|
494
|
+
return w;
|
|
495
|
+
}
|
|
496
|
+
async approveBatch(id, findingIds) {
|
|
497
|
+
const w = this.get(id);
|
|
498
|
+
this.ensureReviewing(w);
|
|
499
|
+
await this.fresh(w);
|
|
500
|
+
if (w.mode !== 'apply-first' || w.batchPreparation !== 'ready')
|
|
501
|
+
throw Error('PREPARE_BATCH_BEFORE_APPROVAL');
|
|
502
|
+
if (!Array.isArray(findingIds) || !findingIds.length || new Set(findingIds).size !== findingIds.length || findingIds.length > w.entries.length)
|
|
503
|
+
throw Error('INVALID_BATCH_SELECTION');
|
|
504
|
+
const selected = findingIds.map(id => w.entries.find(e => e.finding.id === id));
|
|
505
|
+
if (selected.some(e => !e?.patch || e.batch?.state !== 'ready' || e.decision !== 'Pending'))
|
|
506
|
+
throw Error('BATCH_SELECTION_NOT_ELIGIBLE');
|
|
507
|
+
if (w.session)
|
|
508
|
+
await this.candidateFresh(w);
|
|
509
|
+
const previous = selected.map(e => ({ ...e, history: [...e.history] }));
|
|
510
|
+
for (const e of selected) {
|
|
511
|
+
e.applied = true;
|
|
512
|
+
e.decision = 'Accepted';
|
|
513
|
+
e.history.push({ decision: 'Accepted', notes: e.notes, at: new Date().toISOString() });
|
|
514
|
+
}
|
|
515
|
+
try {
|
|
516
|
+
await this.writeComposition(w);
|
|
517
|
+
await this.persist();
|
|
518
|
+
return w;
|
|
519
|
+
}
|
|
520
|
+
catch (error) {
|
|
521
|
+
selected.forEach((e, i) => Object.assign(e, previous[i]));
|
|
522
|
+
throw error;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
async preview(id, findingId, mode) {
|
|
526
|
+
const w = this.get(id);
|
|
527
|
+
const e = w.entries.find(e => e.finding.id === findingId);
|
|
528
|
+
const mapping = e && approvedPreviewForSource(e.finding.path);
|
|
529
|
+
if (!mapping || !e?.patch || !['ltr', 'rtl'].includes(mode))
|
|
530
|
+
throw new Error('LIVE_PREVIEW_MAPPING_UNAVAILABLE');
|
|
531
|
+
await this.fresh(w);
|
|
532
|
+
if (w.session)
|
|
533
|
+
await this.candidateFresh(w);
|
|
534
|
+
let originalAvailable = false;
|
|
535
|
+
try {
|
|
536
|
+
const identity = await fetch(this.originalOrigin + '/__rtl_preview_identity', { signal: AbortSignal.timeout(1200) }).then(r => r.json());
|
|
537
|
+
originalAvailable = identity.projectRoot === this.root && identity.role === 'original' && identity.sourceSha256 === sha(w.baseline[REVIEW_SOURCE]);
|
|
538
|
+
}
|
|
539
|
+
catch { /* show unavailable */ }
|
|
540
|
+
const route = mapping.routes[mode];
|
|
541
|
+
const candidateOrigin = w.session?.runtime?.status === 'healthy' ? w.session.runtime.origin : null;
|
|
542
|
+
return { originalAvailable, originalUrl: this.originalOrigin + route, originalSourceSha256: sha(w.baseline[REVIEW_SOURCE]), candidateSessionId: w.session?.id ?? null, candidateSourceSha256: w.session?.candidateSha256 ?? null, candidateOrigin, url: (candidateOrigin ?? this.originalOrigin) + route, findingId };
|
|
543
|
+
}
|
|
544
|
+
async directionEvidence(w) {
|
|
545
|
+
const selected = w.entries.filter(e => e.decision === 'Accepted' && included(e));
|
|
546
|
+
if (selected.some(e => directionRequirement(e.finding) === 'unknown'))
|
|
547
|
+
throw Error('RUNTIME_DIRECTION_STRATEGY_UNKNOWN');
|
|
548
|
+
const dependent = selected.filter(e => directionRequirement(e.finding) === 'dependent');
|
|
549
|
+
if (!dependent.length)
|
|
550
|
+
return undefined;
|
|
551
|
+
return captureScopedDirectionEvidence(this.root, w, dependent, async (application) => { await initializeOriginalPreview(this.root, application); await this.runtime(w.id, application); });
|
|
552
|
+
}
|
|
553
|
+
async validate(id) {
|
|
554
|
+
const w = this.get(id);
|
|
555
|
+
this.ensureReviewing(w);
|
|
556
|
+
await this.fresh(w);
|
|
557
|
+
if (!w.entries.some(e => e.decision === 'Accepted' && included(e)))
|
|
558
|
+
throw new Error('ACCEPTED_CHANGES_REQUIRED');
|
|
559
|
+
if (w.session)
|
|
560
|
+
await this.candidateFresh(w);
|
|
561
|
+
// The final candidate contains only explicit acceptances. Pending batch edits remain pending in the inventory.
|
|
562
|
+
w.previewFocus = undefined;
|
|
563
|
+
for (const e of w.entries)
|
|
564
|
+
if (e.decision !== 'Accepted')
|
|
565
|
+
e.applied = false;
|
|
566
|
+
await this.writeComposition(w);
|
|
567
|
+
await this.persist();
|
|
568
|
+
const checks = [];
|
|
569
|
+
const hashes = {};
|
|
570
|
+
const pkg = JSON.parse(w.baseline['package.json']);
|
|
571
|
+
const project = await loadProjectConfiguration(this.root);
|
|
572
|
+
for (const name of ['typecheck', 'build', 'test']) {
|
|
573
|
+
const args = project ? project.validation[name] : pkg.scripts?.[name] ? ['run', name] : undefined;
|
|
574
|
+
const configured = configuredWorkflowChecks(w).find(c => c.name === name);
|
|
575
|
+
if (!args) {
|
|
576
|
+
checks.push(configured);
|
|
577
|
+
continue;
|
|
578
|
+
}
|
|
579
|
+
try {
|
|
580
|
+
const result = await run(project?.packageManager ?? 'npm', args, { cwd: w.session.candidateRoot, env: { ...process.env, NX_DAEMON: 'false', NX_ISOLATE_PLUGINS: 'false' }, timeout: 180_000, maxBuffer: 2_000_000 });
|
|
581
|
+
checks.push({ ...configured, name, state: 'Passed', detail: (result.stdout + result.stderr).slice(-8000) });
|
|
582
|
+
}
|
|
583
|
+
catch (error) {
|
|
584
|
+
const failure = error;
|
|
585
|
+
checks.push({ ...configured, name, state: typeof failure.code === 'number' || failure.signal ? 'Failed' : 'Error', detail: ((failure.stdout ?? '') + (failure.stderr ?? '') + failure.message).slice(-8000) });
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
try {
|
|
589
|
+
const before = await scan(this.root), after = await scan(w.session.candidateRoot);
|
|
590
|
+
const unresolved = w.entries.filter(e => e.decision === 'Accepted' && after.findings.filter(f => f.ruleId === e.finding.ruleId && f.path === e.finding.path).length !== before.findings.filter(f => f.ruleId === e.finding.ruleId && f.path === e.finding.path).length - w.entries.filter(a => a.decision === 'Accepted' && a.finding.ruleId === e.finding.ruleId && a.finding.path === e.finding.path).length);
|
|
591
|
+
checks.push({ name: 'scanner', state: after.complete && !unresolved.length ? 'Passed' : 'Failed', detail: JSON.stringify({ before: before.inputDigest, after: after.inputDigest, beforeFindings: before.findings.length, afterFindings: after.findings.length, unresolved: unresolved.map(e => e.finding.id), complete: after.complete }) });
|
|
592
|
+
}
|
|
593
|
+
catch (error) {
|
|
594
|
+
checks.push({ name: 'scanner', state: 'Failed', detail: String(error) });
|
|
595
|
+
}
|
|
596
|
+
const configuration = await loadPreviewConfiguration(this.root);
|
|
597
|
+
if (project || (!Object.hasOwn(w.baseline, REVIEW_SOURCE) && Object.keys(configuration.applications).length)) {
|
|
598
|
+
const accepted = w.entries.filter(e => e.decision === 'Accepted' && included(e));
|
|
599
|
+
const routes = new Map();
|
|
600
|
+
for (const entry of accepted) {
|
|
601
|
+
const mapping = configuredMapping(entry.finding, configuration);
|
|
602
|
+
if (!mapping.configured || !mapping.routes.length) {
|
|
603
|
+
checks.push({ name: 'runtime:' + entry.finding.id, state: 'Unavailable', detail: 'Accepted change has no explicit configured source-to-target route.' });
|
|
604
|
+
continue;
|
|
605
|
+
}
|
|
606
|
+
for (const route of mapping.routes) {
|
|
607
|
+
const prior = routes.get(route.id);
|
|
608
|
+
if (prior)
|
|
609
|
+
prior.entries.push(entry);
|
|
610
|
+
else
|
|
611
|
+
routes.set(route.id, { application: route.application, route, entries: [entry] });
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
for (const { application, route, entries } of routes.values())
|
|
615
|
+
try {
|
|
616
|
+
await this.runtime(id, application);
|
|
617
|
+
if (w.session?.runtime?.status !== 'healthy')
|
|
618
|
+
throw Error('CANDIDATE_RUNTIME_UNAVAILABLE');
|
|
619
|
+
const browser = await chromium.launch({ headless: true });
|
|
620
|
+
try {
|
|
621
|
+
for (const mode of ['ltr', 'rtl']) {
|
|
622
|
+
const page = await browser.newPage({ viewport: { width: 1280, height: 800 } }), errors = [];
|
|
623
|
+
page.on('pageerror', e => errors.push(e.message));
|
|
624
|
+
await page.goto(routeUrl(route, mode, w.session.runtime.origin), { waitUntil: 'domcontentloaded', timeout: 20000 });
|
|
625
|
+
await page.locator(configuration.applications[application].readySelector).first().waitFor();
|
|
626
|
+
await page.waitForFunction(mode => document.documentElement.dir === mode, mode, { timeout: 10000 });
|
|
627
|
+
const targets = [];
|
|
628
|
+
for (const entry of entries) {
|
|
629
|
+
const mapping = configuredMapping(entry.finding, configuration);
|
|
630
|
+
const evidence = await retryAcrossNavigation(async () => {
|
|
631
|
+
await page.locator(mapping.selector).first().waitFor({ state: 'visible', timeout: 10000 });
|
|
632
|
+
return await page.evaluate(({ selector, sourceSelector, path, bidi }) => {
|
|
633
|
+
const nodes = [...document.querySelectorAll(selector)], styles = [...document.querySelectorAll('style[data-vite-dev-id],link[rel=stylesheet]')].filter(n => { if (n.tagName === 'LINK') {
|
|
634
|
+
const u = new URL(n.href, location.href);
|
|
635
|
+
return u.origin === location.origin && decodeURIComponent(u.pathname) === '/' + path;
|
|
636
|
+
} return n.getAttribute('data-vite-dev-id')?.replaceAll('\\', '/').endsWith('/' + path); });
|
|
637
|
+
const rules = [];
|
|
638
|
+
function walk(items) { for (const rule of items) {
|
|
639
|
+
if ('selectorText' in rule)
|
|
640
|
+
rules.push(rule);
|
|
641
|
+
else if ('cssRules' in rule)
|
|
642
|
+
walk(rule.cssRules);
|
|
643
|
+
} }
|
|
644
|
+
for (const style of styles)
|
|
645
|
+
if (style.sheet)
|
|
646
|
+
walk(style.sheet.cssRules);
|
|
647
|
+
const matched = !sourceSelector || rules.some(r => r.selectorText.split(',').map(s => s.trim()).includes(sourceSelector) && nodes.some(n => n.matches(r.selectorText)));
|
|
648
|
+
return { path, selector, sourceRuleMatched: matched, count: nodes.length, bdi: !bidi || nodes.some(n => n.matches('bdi[dir="auto"]') || n.querySelector('bdi[dir="auto"]')), computed: nodes.slice(0, 5).map(n => ({ direction: getComputedStyle(n).direction, textAlign: getComputedStyle(n).textAlign, insetInlineStart: getComputedStyle(n).insetInlineStart, insetInlineEnd: getComputedStyle(n).insetInlineEnd })) };
|
|
649
|
+
}, { selector: mapping.selector, sourceSelector: mapping.sourceSelector, path: entry.finding.path, bidi: entry.finding.ruleId === 'RTL.BIDI.ISOLATION' });
|
|
650
|
+
});
|
|
651
|
+
if (!evidence.sourceRuleMatched || !evidence.bdi)
|
|
652
|
+
throw Error('CONFIGURED_SOURCE_TARGET_NOT_VERIFIED:' + entry.finding.path);
|
|
653
|
+
targets.push(evidence);
|
|
654
|
+
}
|
|
655
|
+
if (errors.length)
|
|
656
|
+
throw Error('RUNTIME_DOM_FAILED:' + errors.join(';'));
|
|
657
|
+
checks.push({ name: 'runtime-' + route.id + '-' + mode, state: 'Passed', detail: JSON.stringify({ route: page.url(), direction: mode, viewport: { width: 1280, height: 800 }, targets, errors }) });
|
|
658
|
+
await page.close();
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
finally {
|
|
662
|
+
await browser.close();
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
catch (error) {
|
|
666
|
+
checks.push({ name: 'runtime-' + route.id, state: 'Unavailable', detail: String(error) });
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
else {
|
|
670
|
+
try {
|
|
671
|
+
await this.runtime(id);
|
|
672
|
+
if (w.session?.runtime?.status !== 'healthy')
|
|
673
|
+
throw new Error('CANDIDATE_RUNTIME_UNAVAILABLE');
|
|
674
|
+
const browser = await chromium.launch({ headless: true });
|
|
675
|
+
try {
|
|
676
|
+
for (const mode of ['ltr', 'rtl']) {
|
|
677
|
+
const page = await browser.newPage();
|
|
678
|
+
const errors = [];
|
|
679
|
+
page.on('pageerror', e => errors.push(e.message));
|
|
680
|
+
await page.goto(w.session.runtime.origin + (mode === 'ltr' ? '/invoices' : '/invoices?demo=unmigrated-rtl&lang=ar'), { waitUntil: 'domcontentloaded', timeout: 20_000 });
|
|
681
|
+
await page.locator('.invoice-link').first().waitFor();
|
|
682
|
+
if (await page.locator('html').getAttribute('dir') !== mode || errors.length)
|
|
683
|
+
throw new Error('RUNTIME_DOM_FAILED:' + errors.join(';'));
|
|
684
|
+
if (w.entries.some(e => e.finding.ruleId === 'RTL.BIDI.ISOLATION' && e.finding.path === REVIEW_SOURCE && e.decision === 'Accepted') && await page.locator('.invoice-link bdi[dir="auto"]').count() === 0)
|
|
685
|
+
throw new Error('PATCHED_DOM_MISSING');
|
|
686
|
+
checks.push({ name: 'runtime-' + mode, state: 'Passed', detail: 'Real /invoices route rendered; direction and supported patched DOM verified.' });
|
|
687
|
+
await page.close();
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
finally {
|
|
691
|
+
await browser.close();
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
catch (error) {
|
|
695
|
+
checks.push({ name: 'runtime', state: 'Unavailable', detail: String(error) });
|
|
696
|
+
}
|
|
697
|
+
for (const e of w.entries.filter(e => e.decision === 'Accepted'))
|
|
698
|
+
if (!approvedPreviewForSource(e.finding.path))
|
|
699
|
+
checks.push({ name: 'live-preview:' + e.finding.path, state: 'Unavailable', detail: 'No approved owning-route mapping. Code review remains available.' });
|
|
700
|
+
}
|
|
701
|
+
let directionEvidence;
|
|
702
|
+
try {
|
|
703
|
+
directionEvidence = await this.directionEvidence(w);
|
|
704
|
+
if (directionEvidence)
|
|
705
|
+
checks.push({ name: 'runtime-scoped-direction', state: 'Passed', detail: 'Server observed matching mapped target direction in configured LTR and RTL application states; semantic review remains required.' });
|
|
706
|
+
}
|
|
707
|
+
catch (error) {
|
|
708
|
+
checks.push({ name: 'runtime-scoped-direction', state: 'Unavailable', detail: String(error) });
|
|
709
|
+
}
|
|
710
|
+
await this.candidateFresh(w);
|
|
711
|
+
await this.fresh(w);
|
|
712
|
+
for (const path of Object.keys(w.baseline))
|
|
713
|
+
hashes[path] = sha(await readFile(await validateProjectSourcePath(w.session.candidateRoot, path), 'utf8'));
|
|
714
|
+
const required = checks.filter(c => !c.name.startsWith('live-preview:') && !(['Not configured', 'Not applicable'].includes(c.state) && ['typecheck', 'build', 'test'].includes(c.name)));
|
|
715
|
+
w.validation = { state: required.some(c => c.state === 'Failed') ? 'Failed' : required.some(c => ['Unavailable', 'Error', 'Not run'].includes(c.state)) ? 'Unavailable' : 'Passed', signature: signature(w), checks, hashes, ...(directionEvidence ? { directionEvidence } : {}), at: new Date().toISOString() };
|
|
716
|
+
await this.persist();
|
|
717
|
+
return w;
|
|
718
|
+
}
|
|
719
|
+
async apply(id, confirmation) {
|
|
720
|
+
const w = this.get(id);
|
|
721
|
+
if (w.supersededBy)
|
|
722
|
+
throw Error('HISTORICAL_REVIEW_LOCKED');
|
|
723
|
+
if (w.state === 'Applied')
|
|
724
|
+
return w;
|
|
725
|
+
if (!w.validation || w.validation.state !== 'Passed' || w.validation.signature !== signature(w))
|
|
726
|
+
throw new Error('VALIDATED_ACCEPTED_CANDIDATE_REQUIRED');
|
|
727
|
+
const evidenceIssue = workflowValidationEvidenceIssue(w);
|
|
728
|
+
if (evidenceIssue)
|
|
729
|
+
throw Error('VALIDATION_EVIDENCE_MISSING: ' + evidenceIssue);
|
|
730
|
+
if (w.entries.some(e => e.decision === 'Accepted' && included(e) && directionRequirement(e.finding) === 'unknown'))
|
|
731
|
+
throw Error('RUNTIME_DIRECTION_STRATEGY_UNKNOWN');
|
|
732
|
+
if (w.state === 'Reviewing')
|
|
733
|
+
await this.fresh(w);
|
|
734
|
+
if (!['Reviewing', 'Applying'].includes(w.state))
|
|
735
|
+
throw new Error('WORKFLOW_LOCKED_' + w.state);
|
|
736
|
+
if (w.state === 'Applying') {
|
|
737
|
+
for (const [path, before] of Object.entries(w.baseline)) {
|
|
738
|
+
const target = await validateProjectSourcePath(this.root, path);
|
|
739
|
+
const after = composeWorkflowFile(before, w.entries.filter(e => e.decision === 'Accepted' && included(e) && e.finding.path === path).map(e => e.patch));
|
|
740
|
+
const current = sha(await readFile(target, 'utf8'));
|
|
741
|
+
if (target !== w.sourcePaths[path] || (current !== sha(before) && current !== sha(after)))
|
|
742
|
+
throw new Error('STALE_APPLY_SOURCE');
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
if (w.state === 'Reviewing')
|
|
746
|
+
await this.restoreAcceptedCandidate(w);
|
|
747
|
+
await this.candidateFresh(w);
|
|
748
|
+
if (w.entries.some(e => e.decision === 'Accepted' && included(e) && directionRequirement(e.finding) === 'dependent')) {
|
|
749
|
+
if (w.state !== 'Reviewing' || !w.validation.directionEvidence)
|
|
750
|
+
throw Error('DIRECTION_EVIDENCE_REVALIDATION_REQUIRED');
|
|
751
|
+
const current = await this.directionEvidence(w);
|
|
752
|
+
if (!current || !sameScopedDirectionEvidence(w.validation.directionEvidence, current))
|
|
753
|
+
throw Error('DIRECTION_EVIDENCE_STALE');
|
|
754
|
+
await this.fresh(w);
|
|
755
|
+
await this.candidateFresh(w);
|
|
756
|
+
}
|
|
757
|
+
for (const [path, hash] of Object.entries(w.validation.hashes))
|
|
758
|
+
if (sha(await readFile(await validateProjectSourcePath(w.session.candidateRoot, path), 'utf8')) !== hash)
|
|
759
|
+
throw new Error('STALE_VALIDATED_CANDIDATE');
|
|
760
|
+
if (confirmation !== 'APPLY_CONFIRMED')
|
|
761
|
+
throw new Error('APPLY_CONFIRMATION_REQUIRED');
|
|
762
|
+
w.state = 'Applying';
|
|
763
|
+
await this.persist();
|
|
764
|
+
const files = [...new Set(w.entries.filter(e => e.decision === 'Accepted' && included(e)).map(e => e.finding.path))].map(path => ({ path, before: w.baseline[path], after: composeWorkflowFile(w.baseline[path], w.entries.filter(e => e.decision === 'Accepted' && included(e) && e.finding.path === path).map(e => e.patch)) }));
|
|
765
|
+
try {
|
|
766
|
+
w.receipts = await this.applyService.applyAcceptedFiles(w.id, files, confirmation);
|
|
767
|
+
w.state = 'Applied';
|
|
768
|
+
await this.persist();
|
|
769
|
+
await this.releaseRuntime(w).catch(() => undefined);
|
|
770
|
+
await this.persist();
|
|
771
|
+
return w;
|
|
772
|
+
}
|
|
773
|
+
catch (error) {
|
|
774
|
+
w.receipts = await this.applyService.recoverAcceptedFileReceipts(w.id);
|
|
775
|
+
await this.persist();
|
|
776
|
+
throw error;
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
async rollback(id, confirmation) {
|
|
780
|
+
const w = this.get(id);
|
|
781
|
+
if (confirmation !== 'ROLLBACK_CONFIRMED')
|
|
782
|
+
throw new Error('ROLLBACK_CONFIRMATION_REQUIRED');
|
|
783
|
+
if (w.state === 'Rolled Back')
|
|
784
|
+
return w;
|
|
785
|
+
if (!w.receipts?.length)
|
|
786
|
+
throw new Error('APPLY_RECEIPTS_REQUIRED');
|
|
787
|
+
await this.applyService.rollbackAcceptedFiles(w.receipts);
|
|
788
|
+
w.state = 'Rolled Back';
|
|
789
|
+
w.rolledBackAt = new Date().toISOString();
|
|
790
|
+
await this.persist();
|
|
791
|
+
await this.releaseRuntime(w).catch(() => undefined);
|
|
792
|
+
await this.persist();
|
|
793
|
+
return w;
|
|
794
|
+
}
|
|
795
|
+
/** Stops every candidate runtime in parallel (a failing stop never blocks the others) and always records the stopped state. Sessions and receipts stay for protected rollback. */
|
|
796
|
+
async shutdown() {
|
|
797
|
+
try {
|
|
798
|
+
await Promise.allSettled(this.workflows.map(async (w) => { if (w.session)
|
|
799
|
+
w.session = await stopCandidateRuntime(w.session); }));
|
|
800
|
+
}
|
|
801
|
+
finally {
|
|
802
|
+
await this.persist();
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
/** A finished Apply or Rollback no longer needs its candidate runtime; the session and receipts remain for protected rollback. */
|
|
806
|
+
async releaseRuntime(w) { if (w.session)
|
|
807
|
+
w.session = await stopCandidateRuntime(w.session); }
|
|
808
|
+
view(w) {
|
|
809
|
+
const { baseline, sourcePaths: _paths, ...rest } = w;
|
|
810
|
+
const files = [...new Set(w.entries.map(e => e.finding.path))].map(path => {
|
|
811
|
+
const before = baseline[path], after = composeWorkflowFile(before, candidateEntries(w).filter(e => e.finding.path === path).map(e => e.patch));
|
|
812
|
+
return { path, originalSha256: sha(before), candidateSha256: sha(after), before, after, diff: before === after ? 'No candidate changes.' : `--- ${path}\n+++ ${path}\n- ${before.split('\n').join('\n- ')}\n+ ${after.split('\n').join('\n+ ')}` };
|
|
813
|
+
});
|
|
814
|
+
const fresh = !!w.validation && w.validation.signature === signature(w);
|
|
815
|
+
const evidenceIssue = w.validation ? workflowValidationEvidenceIssue(w) : undefined;
|
|
816
|
+
const eligible = !evidenceIssue && !w.supersededBy && fresh && w.validation?.state === 'Passed' && ['Reviewing', 'Applying'].includes(w.state) && w.entries.some(e => e.decision === 'Accepted' && included(e));
|
|
817
|
+
const reason = w.supersededBy ? 'Historical review was superseded; start from the current review.' : eligible ? 'Snapshot eligible under existing Apply policy: missing or explicitly excluded project commands are not required; scanner/runtime checks and source/candidate identity guards still apply.' : w.state !== 'Reviewing' && w.state !== 'Applying' ? 'Historical review cannot apply changes.' : !w.entries.some(e => e.decision === 'Accepted' && included(e)) ? 'Approve at least one prepared change.' : !fresh ? 'Validate the current accepted candidate before Apply.' : evidenceIssue ? evidenceIssue : 'Resolve required checks: ' + (w.validation?.checks.filter(c => ['Failed', 'Unavailable', 'Error', 'Not run'].includes(c.state) && !c.name.startsWith('live-preview:')).map(c => c.name + ': ' + c.state + ' · ' + c.detail.slice(0, 180)).join('; ') || w.validation?.state);
|
|
818
|
+
return { ...rest, schemaVersion: 2, files, validationPresentation: workflowValidationPresentation(w, fresh), applyEligibility: { eligible, reason } };
|
|
819
|
+
}
|
|
820
|
+
}
|