rtl-analyzer 0.3.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.
@@ -1,3 +1,5 @@
1
+ import { captureScopedDirectionEvidence, sameScopedDirectionEvidence } from './scoped-direction-evidence.js';
2
+ import { initializeOriginalPreview } from './original-preview-runtime.js';
1
3
  import { configuredWorkflowChecks, workflowValidationPresentation, workflowValidationEvidenceIssue } from './workflow-validation.js';
2
4
  import { createHash, randomUUID } from 'node:crypto';
3
5
  import { mkdir, readFile, readdir, rename, realpath, writeFile } from 'node:fs/promises';
@@ -8,8 +10,9 @@ import { chromium } from '@playwright/test';
8
10
  import { loadProjectConfiguration, PROJECT_CONFIGURATION } from './project-configuration.js';
9
11
  import { previewConfigurationDigest, loadPreviewConfiguration, configuredMapping, routeUrl } from './preview-configuration.js';
10
12
  import { scan } from './scan.js';
13
+ import { retryAcrossNavigation } from './page-navigation.js';
11
14
  import { verifiedSourceTransition } from './source-context.js';
12
- import { proposeTransformation } from './transformations.js';
15
+ import { directionRequirement, proposeTransformation } from './transformations.js';
13
16
  import { approvedPreviewForSource } from './preview-manifest.js';
14
17
  import { createReviewSession, startCandidateRuntime, stopCandidateRuntime, validateProjectSourcePath, REVIEW_SOURCE } from './review-session.js';
15
18
  const run = promisify(execFile);
@@ -30,6 +33,12 @@ export function composeWorkflowFile(before, patches) {
30
33
  return result;
31
34
  }
32
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
+ };
33
42
  const signature = (w) => sha(JSON.stringify(w.entries.filter(e => e.decision === 'Accepted' && included(e)).map(e => e.patch)));
34
43
  export class ReviewWorkflowStore {
35
44
  root;
@@ -50,7 +59,20 @@ export class ReviewWorkflowStore {
50
59
  if (data.version !== 1 || !Array.isArray(data.workflows))
51
60
  throw new Error('WORKFLOW_STORE_INVALID');
52
61
  this.workflows = data.workflows.filter(w => w.root === this.root);
62
+ const current = await scan(this.root);
53
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
+ }
54
76
  if (w.session)
55
77
  w.session.runtime = undefined;
56
78
  if (w.state === 'Applying')
@@ -121,7 +143,7 @@ export class ReviewWorkflowStore {
121
143
  sourcePaths[path] = await validateProjectSourcePath(this.root, path);
122
144
  baseline[path] = await readFile(sourcePaths[path], 'utf8');
123
145
  }
124
- const entries = report.findings.filter(f => !scope.length || scope.includes(f.path)).map(finding => {
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 => {
125
147
  const entry = { finding, reason: '', applied: false, decision: 'Pending', notes: '', history: [] };
126
148
  try {
127
149
  if (!report.complete)
@@ -133,7 +155,7 @@ export class ReviewWorkflowStore {
133
155
  entry.reason = proposal.transformationId + ': ' + proposal.reason;
134
156
  }
135
157
  catch (error) {
136
- entry.reason = `${error instanceof Error ? error.message : 'UNSUPPORTED'}: inspect code and resolve manually; no automatic change.`;
158
+ entry.reason = `${error instanceof Error ? error.message : 'UNSUPPORTED'}: ${finding.rationale} ${finding.treatment} No supported candidate patch; approval unavailable.`;
137
159
  }
138
160
  return entry;
139
161
  });
@@ -158,6 +180,66 @@ export class ReviewWorkflowStore {
158
180
  return w;
159
181
  }
160
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
+ }
161
243
  async resumeAfterRollback(id) {
162
244
  const historical = this.get(id);
163
245
  if (historical.state !== 'Rolled Back')
@@ -188,7 +270,7 @@ export class ReviewWorkflowStore {
188
270
  if (!w.session)
189
271
  throw new Error('CANDIDATE_REQUIRED');
190
272
  for (const [path, before] of Object.entries(w.baseline)) {
191
- const expected = composeWorkflowFile(before, w.entries.filter(e => included(e) && e.patch.path === path).map(e => e.patch));
273
+ const expected = composeWorkflowFile(before, candidateEntries(w).filter(e => e.patch.path === path).map(e => e.patch));
192
274
  const actual = await readFile(await validateProjectSourcePath(w.session.candidateRoot, path), 'utf8');
193
275
  if (actual !== expected)
194
276
  throw new Error('STALE_CANDIDATE_SOURCE');
@@ -206,7 +288,7 @@ export class ReviewWorkflowStore {
206
288
  if (w.session.runtime)
207
289
  w.session = await stopCandidateRuntime(w.session);
208
290
  for (const path of new Set(w.entries.filter(e => e.patch).map(e => e.finding.path))) {
209
- const after = composeWorkflowFile(w.baseline[path], w.entries.filter(e => included(e) && e.patch.path === path).map(e => e.patch));
291
+ const after = composeWorkflowFile(w.baseline[path], candidateEntries(w).filter(e => e.patch.path === path).map(e => e.patch));
210
292
  await writeFile(await validateProjectSourcePath(w.session.candidateRoot, path), after, 'utf8');
211
293
  }
212
294
  w.session.candidateSha256 = sha(await readFile(join(w.session.candidateRoot, w.session.sourcePath), 'utf8'));
@@ -237,16 +319,20 @@ export class ReviewWorkflowStore {
237
319
  if (w.session)
238
320
  await this.candidateFresh(w);
239
321
  const previous = { ...e };
322
+ const previousState = this.previewState(w);
240
323
  if (input.action === 'apply') {
241
324
  e.applied = true;
242
325
  if (['Rejected', 'Deferred', 'Flagged'].includes(e.decision))
243
326
  e.decision = 'Pending';
327
+ w.previewFocus = undefined; /* explicit apply composes every applied entry; previews re-focus */
244
328
  }
245
329
  else {
246
330
  e.decision = input.action;
247
331
  e.notes = input.notes ?? '';
248
332
  if (e.decision !== 'Accepted')
249
333
  e.applied = false;
334
+ if (w.previewFocus === e.finding.id && !included(e))
335
+ w.previewFocus = undefined;
250
336
  e.history.push({ decision: e.decision, notes: e.notes, at: new Date().toISOString() });
251
337
  }
252
338
  // Rebuild from original coordinates, not from the previously patched content.
@@ -257,12 +343,38 @@ export class ReviewWorkflowStore {
257
343
  }
258
344
  catch (error) {
259
345
  Object.assign(e, previous);
346
+ this.restorePreviewState(w, previousState);
260
347
  throw error;
261
348
  }
262
349
  }
263
- async writeComposition(w) {
264
- if (!w.session && !w.entries.some(included)) {
265
- w.validation = undefined;
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;
266
378
  return;
267
379
  }
268
380
  if (!w.session)
@@ -270,8 +382,12 @@ export class ReviewWorkflowStore {
270
382
  if (w.session.runtime)
271
383
  w.session = await stopCandidateRuntime(w.session);
272
384
  for (const path of new Set(w.entries.filter(e => e.patch).map(e => e.finding.path)))
273
- await writeFile(await validateProjectSourcePath(w.session.candidateRoot, path), composeWorkflowFile(w.baseline[path], w.entries.filter(e => included(e) && e.patch.path === path).map(e => e.patch)), 'utf8');
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');
274
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.';
275
391
  w.validation = undefined;
276
392
  }
277
393
  async runtime(id, application) {
@@ -300,13 +416,112 @@ export class ReviewWorkflowStore {
300
416
  throw Error('PREVIEW_MAPPING_UNAVAILABLE');
301
417
  if (w.session)
302
418
  await this.candidateFresh(w);
303
- if (!entry.applied)
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)
304
437
  await this.change(id, entry.finding.id, { action: 'apply' });
305
438
  const prepared = await this.runtime(id, input.application);
306
439
  if (prepared.session?.runtime?.status !== 'healthy')
307
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); });
308
443
  return prepared;
309
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
+ }
310
525
  async preview(id, findingId, mode) {
311
526
  const w = this.get(id);
312
527
  const e = w.entries.find(e => e.finding.id === findingId);
@@ -326,6 +541,15 @@ export class ReviewWorkflowStore {
326
541
  const candidateOrigin = w.session?.runtime?.status === 'healthy' ? w.session.runtime.origin : null;
327
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 };
328
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
+ }
329
553
  async validate(id) {
330
554
  const w = this.get(id);
331
555
  this.ensureReviewing(w);
@@ -335,6 +559,7 @@ export class ReviewWorkflowStore {
335
559
  if (w.session)
336
560
  await this.candidateFresh(w);
337
561
  // The final candidate contains only explicit acceptances. Pending batch edits remain pending in the inventory.
562
+ w.previewFocus = undefined;
338
563
  for (const e of w.entries)
339
564
  if (e.decision !== 'Accepted')
340
565
  e.applied = false;
@@ -402,22 +627,27 @@ export class ReviewWorkflowStore {
402
627
  const targets = [];
403
628
  for (const entry of entries) {
404
629
  const mapping = configuredMapping(entry.finding, configuration);
405
- await page.locator(mapping.selector).first().waitFor({ state: 'visible', timeout: 10000 });
406
- const evidence = await page.evaluate(({ selector, sourceSelector, path, bidi }) => {
407
- const nodes = [...document.querySelectorAll(selector)], styles = [...document.querySelectorAll('style[data-vite-dev-id]')].filter(n => n.getAttribute('data-vite-dev-id')?.replaceAll('\\', '/').endsWith('/' + path));
408
- const rules = [];
409
- function walk(items) { for (const rule of items) {
410
- if ('selectorText' in rule)
411
- rules.push(rule);
412
- else if ('cssRules' in rule)
413
- walk(rule.cssRules);
414
- } }
415
- for (const style of styles)
416
- if (style.sheet)
417
- walk(style.sheet.cssRules);
418
- const matched = !sourceSelector || rules.some(r => r.selectorText.split(',').map(s => s.trim()).includes(sourceSelector) && nodes.some(n => n.matches(r.selectorText)));
419
- 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 })) };
420
- }, { selector: mapping.selector, sourceSelector: mapping.sourceSelector, path: entry.finding.path, bidi: entry.finding.ruleId === 'RTL.BIDI.ISOLATION' });
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
+ });
421
651
  if (!evidence.sourceRuleMatched || !evidence.bdi)
422
652
  throw Error('CONFIGURED_SOURCE_TARGET_NOT_VERIFIED:' + entry.finding.path);
423
653
  targets.push(evidence);
@@ -468,12 +698,21 @@ export class ReviewWorkflowStore {
468
698
  if (!approvedPreviewForSource(e.finding.path))
469
699
  checks.push({ name: 'live-preview:' + e.finding.path, state: 'Unavailable', detail: 'No approved owning-route mapping. Code review remains available.' });
470
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
+ }
471
710
  await this.candidateFresh(w);
472
711
  await this.fresh(w);
473
712
  for (const path of Object.keys(w.baseline))
474
713
  hashes[path] = sha(await readFile(await validateProjectSourcePath(w.session.candidateRoot, path), 'utf8'));
475
714
  const required = checks.filter(c => !c.name.startsWith('live-preview:') && !(['Not configured', 'Not applicable'].includes(c.state) && ['typecheck', 'build', 'test'].includes(c.name)));
476
- 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, at: new Date().toISOString() };
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() };
477
716
  await this.persist();
478
717
  return w;
479
718
  }
@@ -488,6 +727,8 @@ export class ReviewWorkflowStore {
488
727
  const evidenceIssue = workflowValidationEvidenceIssue(w);
489
728
  if (evidenceIssue)
490
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');
491
732
  if (w.state === 'Reviewing')
492
733
  await this.fresh(w);
493
734
  if (!['Reviewing', 'Applying'].includes(w.state))
@@ -501,7 +742,18 @@ export class ReviewWorkflowStore {
501
742
  throw new Error('STALE_APPLY_SOURCE');
502
743
  }
503
744
  }
745
+ if (w.state === 'Reviewing')
746
+ await this.restoreAcceptedCandidate(w);
504
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
+ }
505
757
  for (const [path, hash] of Object.entries(w.validation.hashes))
506
758
  if (sha(await readFile(await validateProjectSourcePath(w.session.candidateRoot, path), 'utf8')) !== hash)
507
759
  throw new Error('STALE_VALIDATED_CANDIDATE');
@@ -514,6 +766,8 @@ export class ReviewWorkflowStore {
514
766
  w.receipts = await this.applyService.applyAcceptedFiles(w.id, files, confirmation);
515
767
  w.state = 'Applied';
516
768
  await this.persist();
769
+ await this.releaseRuntime(w).catch(() => undefined);
770
+ await this.persist();
517
771
  return w;
518
772
  }
519
773
  catch (error) {
@@ -534,15 +788,27 @@ export class ReviewWorkflowStore {
534
788
  w.state = 'Rolled Back';
535
789
  w.rolledBackAt = new Date().toISOString();
536
790
  await this.persist();
791
+ await this.releaseRuntime(w).catch(() => undefined);
792
+ await this.persist();
537
793
  return w;
538
794
  }
539
- async shutdown() { for (const w of this.workflows)
540
- if (w.session)
541
- w.session = await stopCandidateRuntime(w.session); await this.persist(); }
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); }
542
808
  view(w) {
543
809
  const { baseline, sourcePaths: _paths, ...rest } = w;
544
810
  const files = [...new Set(w.entries.map(e => e.finding.path))].map(path => {
545
- const before = baseline[path], after = composeWorkflowFile(before, w.entries.filter(e => included(e) && e.finding.path === path).map(e => e.patch));
811
+ const before = baseline[path], after = composeWorkflowFile(before, candidateEntries(w).filter(e => e.finding.path === path).map(e => e.patch));
546
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+ ')}` };
547
813
  });
548
814
  const fresh = !!w.validation && w.validation.signature === signature(w);
package/dist/rules.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import ts from 'typescript';
2
2
  import { hasIsolation } from './codemod.js';
3
+ import { hasMirroredCssOffset } from './css-configured-proposal.js';
3
4
  import { cssIconAnchors } from './css-icons.js';
4
5
  import { analyzeRuntimeDirection } from './runtime-direction.js';
5
6
  import valueParser from 'postcss-value-parser';
6
7
  import { hash, range } from './model.js';
7
8
  const plain = (v) => v.replace(/^['"`]|['"`]$/g, '');
9
+ const ownerIsLocalCss = (f) => f.ownership === 'custom-css' && f.sourceMechanism === 'css';
8
10
  const cssKey = (p) => p.replace(/[A-Z]/g, c => '-' + c.toLowerCase());
9
11
  export function detect(evidence, sources, policy, diagnostics) {
10
12
  const findings = [];
@@ -18,7 +20,14 @@ export function detect(evidence, sources, policy, diagnostics) {
18
20
  const occurrence = findingOccurrences.get(key) ?? 0;
19
21
  findingOccurrences.set(key, occurrence + 1);
20
22
  findings.push({ id: ruleId + ':' + hash(a.id + '|' + occurrence).slice(0, 24), ruleId, ruleVersion: 1, category, severity: category === 'INFORMATIONAL' || category === 'INTENTIONAL_LTR' ? 'Info' : severity, confidence, title, sourceMechanism: 'mechanism' in a ? a.mechanism : 'typescript-structure', applications: a.path.startsWith('apps/') ? [a.path.split('/')[1]] : [], path: a.path, range: a.range, original: a.original, context: a.context, ownership, rationale, treatment, evidenceIds: refs.map(e => e.id).sort(), relatedLocations: refs.filter(e => e.id !== a.id).map(e => ({ path: e.path, range: e.range })), issueIds: policy.issueBindings.filter(b => b.ruleId === ruleId && b.path === a.path && a.context.includes(b.contextIncludes) && (!b.originalIncludes || a.original.includes(b.originalIncludes))).map(b => b.issueId).sort(), suggestion: exception ? null : suggestion, limitation, ...(exception ? { exceptionReason: exception.reason, originalCategory } : {}) });
21
- return findings.at(-1);
23
+ const finding = findings.at(-1);
24
+ if (!exception && ownerIsLocalCss(finding) && refs[0]?.id === a.id) {
25
+ const declaration = refs[0];
26
+ const intent = policy.cssProposals?.find(i => i.path === a.path && i.context === a.context && i.property === declaration.property && i.value === declaration.value);
27
+ if (intent)
28
+ finding.cssProposal = { kind: intent.kind, sourceDigest: intent.sourceDigest };
29
+ }
30
+ return finding;
22
31
  }
23
32
  for (const e of evidence) {
24
33
  if (['tailwind-utility', 'bootstrap-utility'].includes(e.semantics)) {
@@ -55,10 +64,10 @@ export function detect(evidence, sources, policy, diagnostics) {
55
64
  const simple = tokens.every(n => n.type === 'word');
56
65
  const words = tokens.map(n => valueParser.stringify(n));
57
66
  const asymmetric = p === 'border-radius' ? words.length > 1 && new Set(words).size > 1 : words.length === 4 && words[1] !== words[3];
58
- if (asymmetric || !simple && words.length > 0 && !/^[-\d.%pxemauto ]+$/.test(v))
67
+ if (asymmetric || !simple && !(p !== 'border-radius' && words.length >= 1 && words.length <= 3 && tokens.every(n => n.type === 'word' || n.type === 'function' && n.value.toLowerCase() !== 'var')) && words.length > 0 && !/^[-\d.%pxemauto ]+$/.test(v))
59
68
  add('RTL.CSS.SHORTHAND', 'Shorthand needs side/corner review', e, 'MANUAL_REVIEW', 'Shorthand may encode unequal physical sides, elliptical corners or unresolved values.', 'Review tokenized values and cascade; do not split functions or reverse corner order blindly.', owner, [e], simple ? 'High' : 'Medium');
60
69
  }
61
- else if ((p === 'transform' && /translateX\((?!0\))/i.test(v)) || (/^(transform-origin|background-position|box-shadow)$/.test(p) && /left|right|\d/.test(v)) || p === 'order' || p === 'flex-direction' && v === 'row-reverse' || /^grid-(column|row|area)/.test(p) && !/^auto$/.test(v) && !/^1\s*\/\s*-1$/.test(v))
70
+ else if (!hasMirroredCssOffset(e, evidence) && ((p === 'transform' && /translateX\((?!0\))/i.test(v)) || (/^(transform-origin|background-position|box-shadow)$/.test(p) && /left|right|\d/.test(v)) || p === 'order' || p === 'flex-direction' && v === 'row-reverse' || /^grid-(column|row|area)/.test(p) && !/^auto$/.test(v) && !/^1\s*\/\s*-1$/.test(v)))
62
71
  add('RTL.GEOMETRY.ORDER', 'Directional geometry or explicit order', e, 'MANUAL_REVIEW', 'Transform/axis/order semantics require geometric and reading-order decisions.', 'Review spatial intent, focus order and companion positioning; no numeric sign reversal.', owner, [e], 'Medium');
63
72
  }
64
73
  for (const [path, text] of sources)
@@ -123,7 +132,7 @@ export function detect(evidence, sources, policy, diagnostics) {
123
132
  if (values?.includes('rtl'))
124
133
  rtl.push(a);
125
134
  if (!values) {
126
- diagnostics.push({ path, range: a.range, code: 'RUNTIME_DIRECTION_UNKNOWN', message: 'Document direction expression not statically resolved.', impact: 'DIRECTIONAL_UNSUPPORTED', blocking: true, rationale: 'Potential output direction cannot be correlated safely.' });
135
+ diagnostics.push({ path, range: a.range, code: 'RUNTIME_DIRECTION_UNKNOWN', message: 'Document direction expression not statically resolved.', impact: 'DIRECTIONAL_UNSUPPORTED', blocking: false, rationale: 'Static findings remain available; runtime direction is unknown and direction-dependent changes require verified runtime evidence.' });
127
136
  add('RTL.RUNTIME.DIRECTION_UNKNOWN', 'Dynamic document direction requires review', a, 'RUNTIME_CONFIG', 'Direction output comes from an unresolved expression.', 'Review output values and runtime synchronization; do not infer direction from strings in a condition.', 'document-runtime', [], 'Low');
128
137
  }
129
138
  }