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.
Files changed (60) hide show
  1. package/README.md +90 -56
  2. package/dist/cli.js +18 -1
  3. package/dist/codemod.js +50 -12
  4. package/dist/companion-security.js +2 -0
  5. package/dist/contextual-preview-bridge.js +118 -0
  6. package/dist/contextual-preview.js +74 -0
  7. package/dist/controlled-apply.js +222 -0
  8. package/dist/css-configured-proposal.js +98 -0
  9. package/dist/css-directional.js +60 -0
  10. package/dist/css-icons.js +51 -0
  11. package/dist/css-spacing.js +65 -0
  12. package/dist/dashboard-batch-review.js +37 -0
  13. package/dist/dashboard-client.js +73 -50
  14. package/dist/dashboard-contextual-preview.js +127 -0
  15. package/dist/dashboard-data.js +4 -4
  16. package/dist/dashboard-embedded-preview.js +202 -0
  17. package/dist/dashboard-html.js +13 -10
  18. package/dist/dashboard-operation-flow.js +47 -0
  19. package/dist/dashboard-review-details.js +175 -0
  20. package/dist/dashboard-review-navigation.js +19 -0
  21. package/dist/dashboard-review-workflow.js +219 -0
  22. package/dist/dashboard-themes.js +34 -0
  23. package/dist/directional-properties.js +53 -0
  24. package/dist/discovery.js +1 -2
  25. package/dist/eligibility.js +8 -8
  26. package/dist/evidence-store.js +110 -0
  27. package/dist/example-preview-mappings.js +98 -0
  28. package/dist/manual-change-store.js +27 -0
  29. package/dist/migration-lifecycle.js +19 -0
  30. package/dist/original-preview-runtime.js +78 -0
  31. package/dist/output-path.js +65 -0
  32. package/dist/page-navigation.js +17 -0
  33. package/dist/policy-validation.js +7 -4
  34. package/dist/preview-cli.js +22 -0
  35. package/dist/preview-companion.js +649 -0
  36. package/dist/preview-configuration.js +171 -0
  37. package/dist/preview-runtime.js +102 -0
  38. package/dist/project-configuration.js +48 -0
  39. package/dist/project-root.js +12 -0
  40. package/dist/react-inline.js +65 -0
  41. package/dist/report-publisher.js +4 -7
  42. package/dist/review-approval.js +9 -0
  43. package/dist/review-session.js +211 -56
  44. package/dist/review-store.js +175 -0
  45. package/dist/review-workflow.js +820 -0
  46. package/dist/rules.js +27 -17
  47. package/dist/runtime-process.js +35 -0
  48. package/dist/scan-history.js +35 -0
  49. package/dist/scan-manifest-store.js +26 -0
  50. package/dist/scan.js +55 -4
  51. package/dist/scoped-direction-evidence.js +117 -0
  52. package/dist/serialization.js +1 -0
  53. package/dist/source-context.js +93 -0
  54. package/dist/source-snippets.js +3 -3
  55. package/dist/standalone-cli.js +14 -1
  56. package/dist/tailwind.js +3 -1
  57. package/dist/transformations.js +34 -0
  58. package/dist/validation.js +75 -0
  59. package/dist/workflow-validation.js +46 -0
  60. package/package.json +17 -8
@@ -0,0 +1,34 @@
1
+ /** Semantic colors shared by generated CSS and the dynamic dashboard surfaces. */
2
+ export const themes = [
3
+ { id: 'studio', name: 'Studio Dark', bg: '#060d1a', surface: '#0e1a2e', raised: '#182b46', text: '#f4f7ff', muted: '#bdc9dc', line: '#526d91', accent: '#7541bc', focus: '#cfb0ff', ok: '#5de0a6', warn: '#ffd166', bad: '#ff8193', before: '#321c2a', after: '#12382f' },
4
+ { id: 'dracula', name: 'Dracula', bg: '#282a36', surface: '#30323f', raised: '#44475a', text: '#f8f8f2', muted: '#d1cde1', line: '#73748d', accent: '#7548ad', focus: '#bd93f9', ok: '#50fa7b', warn: '#f1fa8c', bad: '#ff777f', before: '#4b283b', after: '#203e37' },
5
+ { id: 'nord', name: 'Nord', bg: '#2e3440', surface: '#353e4d', raised: '#434c5e', text: '#eceff4', muted: '#c7d1df', line: '#75869d', accent: '#5263a4', focus: '#88c0d0', ok: '#b0d69b', warn: '#ebcb8b', bad: '#f09ba0', before: '#493643', after: '#304740' },
6
+ { id: 'solarized', name: 'Solarized Light', bg: '#fdf6e3', surface: '#fffbed', raised: '#eee8d5', text: '#263f46', muted: '#4d6268', line: '#8b9997', accent: '#6b45a3', focus: '#5c319d', ok: '#286843', warn: '#795400', bad: '#a3292c', before: '#fbe6e0', after: '#e4f0d9' },
7
+ { id: 'github', name: 'GitHub Light', bg: '#ffffff', surface: '#f6f8fa', raised: '#eaeef2', text: '#1f2328', muted: '#505b66', line: '#8c959f', accent: '#6638aa', focus: '#6633bb', ok: '#216e39', warn: '#795000', bad: '#b4232b', before: '#ffebe9', after: '#dafbe1' },
8
+ ];
9
+ const colors = new Set();
10
+ /** Every legacy literal retains its exact default, with a semantic alternate per theme. */
11
+ export function dashboardThemeTokens(source) { return source.replace(/#[\da-f]{8}\b|#[\da-f]{6}\b|#[\da-f]{4}\b|#[\da-f]{3}\b/gi, color => { colors.add(color.toLowerCase()); return 'var(--rtl-' + color.slice(1).toLowerCase() + ')'; }); }
12
+ function semantic(hex) { let s = hex.slice(1); if (s.length <= 4)
13
+ s = s.split('').map(c => c + c).join(''); const [r, g, b] = [0, 2, 4].map(i => parseInt(s.slice(i, i + 2), 16) / 255), max = Math.max(r, g, b), min = Math.min(r, g, b); if (max > .7 && max - min < .27)
14
+ return 'text'; if (max < .27)
15
+ return 'bg'; if (max < .48)
16
+ return 'surface'; if (max - min < .18)
17
+ return 'muted'; if (r > g * 1.3 && b > g * 1.2)
18
+ return max > .7 ? 'focus' : 'accent'; if (g > r * 1.2 && g > b * .85)
19
+ return 'ok'; if (r > g * 1.4 && r > b)
20
+ return 'bad'; if (r > .6 && g > .45 && b < g * .8)
21
+ return 'warn'; return max > .66 ? 'muted' : 'line'; }
22
+ export function dashboardThemeDefinitions() { return ':root{' + [...colors].map(c => '--rtl-' + c.slice(1) + ':' + c).join(';') + '}' + themes.filter(t => t.id !== 'studio').map(t => 'html[data-theme="' + t.id + '"]{' + [...colors].map(c => '--rtl-' + c.slice(1) + ':' + t[semantic(c)]).join(';') + '}').join('') + themes.map(t => 'html[data-theme="' + t.id + '"]{color-scheme:' + (['github', 'solarized'].includes(t.id) ? 'light' : 'dark') + ';' + Object.entries(t).filter(([k]) => !['id', 'name'].includes(k)).map(([k, v]) => '--theme-' + k + ':' + v).join(';') + '}').join('') + '.workflow-screen{background:var(--theme-bg)!important;color:var(--theme-text)!important}.workflow-screen header{background:var(--theme-surface)!important;border-color:var(--theme-line)!important}.workflow-screen h1,.workflow-screen h2,.workflow-screen p,.workflow-screen strong{color:var(--theme-text)!important}.workflow-screen .workflow-mode-status,.workflow-screen .workflow-card p,.workflow-screen .workflow-reassurance{color:var(--theme-muted)!important}.workflow-screen .workflow-card{background:var(--theme-surface)!important;border-color:var(--theme-line)!important;box-shadow:none!important}.workflow-screen .workflow-card.workflow-selected{background:color-mix(in srgb,var(--theme-accent) 20%,var(--theme-surface))!important;border-color:var(--theme-accent)!important}.workflow-screen .workflow-card button{background:var(--theme-accent)!important;border-color:var(--theme-focus)!important;color:#fff!important}.workflow-screen .workflow-reassurance{background:var(--theme-raised)!important;border-color:var(--theme-line)!important}.workflow-screen .workflow-scan{color:var(--theme-ok)!important}.workflow-screen .workflow-scan small{color:var(--theme-muted)!important}.workflow-screen .color-theme-trigger{margin-left:auto}@media(max-width:700px){.workflow-screen header{padding:10px 16px!important;gap:12px!important}.workflow-screen .color-theme-trigger{margin-left:0}.workflow-screen .workflow-brand strong{font-size:20px!important}}'; }
23
+ export const themeClientSource = String.raw `
24
+ (()=>{const themes=__RTL_THEMES__;let saved=localStorage.getItem('rtl-color-theme')||'studio';if(!themes.some(t=>t.id===saved))saved='studio';const root=document.documentElement;root.dataset.theme=saved;const style=document.createElement('style');style.textContent='body,.app{background:var(--theme-bg)!important;color:var(--theme-text)!important}.theme-menu{position:fixed;inset:auto;z-index:120;width:260px;max-width:calc(100vw - 24px);padding:8px;border:1px solid var(--theme-line);border-radius:10px;background:var(--theme-surface);color:var(--theme-text);box-shadow:0 10px 30px #0005}.theme-menu button{display:flex;align-items:center;gap:8px;width:100%;padding:10px;border:1px solid transparent;background:transparent;color:var(--theme-text);text-align:left}.theme-menu button:focus-visible,.theme-menu button:hover{outline:2px solid var(--theme-focus);outline-offset:-2px;background:var(--theme-raised)}.theme-swatch{display:inline-block;width:14px;height:14px;border-radius:50%;border:1px solid var(--theme-line)}.theme-check{margin-left:auto}.color-theme-trigger{min-width:38px;min-height:38px;border:1px solid var(--theme-line);border-radius:8px;background:var(--theme-surface);color:var(--theme-text);font-size:22px}.panel-controls{flex-wrap:wrap}.review-section,.batch-review,.batch-panel,.review-operation,.review-details-dialog,.approval-confirmation{background:var(--theme-surface)!important;color:var(--theme-text)!important;border-color:var(--theme-line)!important}.before-card{background:var(--theme-before)!important}.after-card{background:var(--theme-after)!important}.before-card pre,.after-card pre,.line,.finding-title{color:var(--theme-text)!important}.finding-range{background:var(--theme-accent)!important;color:#fff!important;border-color:var(--theme-focus)!important}html[data-theme] .panel-controls .panel-toggle-btn{transition:none!important;background:var(--theme-raised)!important;color:var(--theme-text)!important;border-color:var(--theme-line)!important}html[data-theme] .panel-controls .panel-toggle-btn[aria-expanded=true],html[data-theme] .nav button.active,html[data-theme] .logo,html[data-theme] .workflow-brand>span,html[data-theme] [role=tab][aria-selected=true],html[data-theme] .workflow-screen .workflow-card button{background:var(--theme-accent)!important;color:#fff!important;border-color:var(--theme-focus)!important}.session-primary,.actions button,.batch-primary,.review-operation button{background:var(--theme-accent)!important;color:#fff!important;border-color:var(--theme-focus)!important}.session-validation[data-status=Passed],.operation-success{color:var(--theme-ok)!important}.session-validation[data-status=Failed]{color:var(--theme-bad)!important}.review-operation::backdrop,.approval-confirmation::backdrop{background:#050a16b8!important}:focus-visible{outline:2px solid var(--theme-focus)!important;outline-offset:2px}';document.head.append(style);
25
+ style.textContent+='html[data-theme] body{background:var(--theme-bg)!important}html[data-theme] .top{background:var(--theme-surface)!important;box-shadow:0 1px 0 var(--theme-line)!important}html[data-theme] .brand:before{box-shadow:0 2px 8px color-mix(in srgb,var(--theme-accent) 28%,transparent)!important}html[data-theme] .nav .active{background:var(--theme-raised)!important;border-color:var(--theme-accent)!important;box-shadow:inset 0 -2px 0 var(--theme-accent)!important}html[data-theme] .nav button:not(:disabled):hover{background:var(--theme-raised)!important;color:var(--theme-text)!important}html[data-theme] .summary .card,html[data-theme] .scope,html[data-theme] .project{background:var(--theme-surface)!important;box-shadow:none!important;border-color:var(--theme-line)!important}html[data-theme] .workspace{background:var(--theme-line)!important;box-shadow:none!important}html[data-theme] .pane,html[data-theme] .details{background:var(--theme-surface)!important}html[data-theme] .head{background:var(--theme-raised)!important;color:var(--theme-muted)!important}html[data-theme] .finding:hover,html[data-theme] .file:hover{background:var(--theme-raised)!important}html[data-theme] .finding.selected,html[data-theme] .file.selected{background:color-mix(in srgb,var(--theme-accent) 22%,var(--theme-surface))!important;border-color:var(--theme-accent)!important;box-shadow:inset 3px 0 var(--theme-focus)!important}html[data-theme] .search-wrap{background:var(--theme-surface)!important;border-color:var(--theme-line)!important}html[data-theme] .status{color:var(--theme-ok)!important}html[data-theme] .batch-review{box-shadow:none!important}html[data-theme] .batch-panel{background:var(--theme-surface)!important}html[data-theme] .batch-review th{color:var(--theme-muted)!important}html[data-theme] .batch-review tbody tr:hover{background:color-mix(in srgb,var(--theme-raised) 72%,transparent)!important}html[data-theme] .batch-review tbody tr:last-child td{border-bottom:0}html[data-theme] .batch-footer{background:var(--theme-surface)!important;box-shadow:0 -1px 0 var(--theme-line)}';const trigger=el('button','🎨','color-theme-trigger');trigger.title='Color theme';trigger.setAttribute('aria-label','Color theme');trigger.setAttribute('aria-haspopup','menu');trigger.setAttribute('aria-expanded','false');const host=document.querySelector('.search-wrap');host?.after(trigger);const menu=el('div','','theme-menu');menu.setAttribute('popover','manual');menu.setAttribute('role','menu');menu.setAttribute('aria-label','Color theme');document.body.append(menu);let open=false,activeTrigger=trigger;
26
+ function close(focus=false){if(!open)return;open=false;menu.hidePopover();root.dataset.theme=saved;activeTrigger.setAttribute('aria-expanded','false');if(focus)activeTrigger.focus()}
27
+ function position(anchor=activeTrigger){const box=anchor.getBoundingClientRect(),width=Math.min(260,innerWidth-24),height=menu.offsetHeight,left=Math.max(12,Math.min(box.left,innerWidth-width-12)),below=box.bottom+8,top=below+height<=innerHeight-12?below:Math.max(12,box.top-height-8);menu.style.left=left+'px';menu.style.top=top+'px'}
28
+ function openFor(anchor){if(open)close(false);activeTrigger=anchor;for(const button of buttons){const checked=button.dataset.themeId===saved;button.setAttribute('aria-checked',String(checked));button.querySelector('.theme-check').textContent=checked?'✓':''}open=true;menu.showPopover();activeTrigger.setAttribute('aria-expanded','true');position(activeTrigger)}
29
+ const buttons=themes.map(t=>{const button=el('button');button.setAttribute('role','menuitemradio');button.dataset.themeId=t.id;for(const color of [t.bg,t.accent,t.text]){const swatch=el('span','','theme-swatch');swatch.style.background=color;swatch.setAttribute('aria-hidden','true');button.append(swatch)}const check=el('span','','theme-check');check.setAttribute('aria-hidden','true');button.append(el('span',t.name),check);button.onpointerenter=()=>{root.dataset.theme=t.id};button.onfocus=()=>{root.dataset.theme=t.id};button.onclick=()=>{saved=t.id;localStorage.setItem('rtl-color-theme',saved);close(true)};menu.append(button);return button});
30
+ trigger.onclick=()=>{if(open){close(true);return}openFor(trigger)};trigger.onkeydown=e=>{if(['ArrowDown','ArrowUp'].includes(e.key)){e.preventDefault();if(!open)openFor(trigger);buttons[e.key==='ArrowDown'?0:buttons.length-1].focus()}};
31
+ menu.onkeydown=e=>{const i=buttons.indexOf(document.activeElement);if(['ArrowDown','ArrowUp','Home','End'].includes(e.key)){e.preventDefault();buttons[e.key==='Home'?0:e.key==='End'?buttons.length-1:(i+(e.key==='ArrowUp'?-1:1)+buttons.length)%buttons.length].focus()}if(e.key==='Escape'){e.preventDefault();close(true)}if(e.key==='Tab')close(false)};document.addEventListener('pointerdown',e=>{if(open&&!menu.contains(e.target)&&!e.target.closest('.color-theme-trigger'))close(false)});document.addEventListener('keydown',e=>{if(e.key==='Escape'&&open){e.preventDefault();close(true)}});addEventListener('resize',()=>{if(open)position(activeTrigger)});document.addEventListener('scroll',()=>{if(open)position(activeTrigger)},true);
32
+ document.addEventListener('rtl-workflow-screen-ready',()=>{const chooser=document.querySelector('.workflow-screen header');if(chooser&&!chooser.querySelector('.chooser-theme-trigger')){const chooserTrigger=document.createElement('button');chooserTrigger.type='button';chooserTrigger.className='color-theme-trigger chooser-theme-trigger';chooserTrigger.textContent='🎨';chooserTrigger.title='Color theme';chooserTrigger.setAttribute('aria-label','Color theme');chooserTrigger.setAttribute('aria-haspopup','menu');chooserTrigger.setAttribute('aria-expanded','false');chooserTrigger.onclick=()=>openFor(chooserTrigger);chooserTrigger.onkeydown=e=>{if(['ArrowDown','ArrowUp'].includes(e.key)){e.preventDefault();openFor(chooserTrigger);buttons[e.key==='ArrowDown'?0:buttons.length-1].focus()}};chooser.insertBefore(chooserTrigger,chooser.lastElementChild)}},{once:true});
33
+ })();
34
+ `.replace('__RTL_THEMES__', JSON.stringify(themes));
@@ -0,0 +1,53 @@
1
+ import valueParser from 'postcss-value-parser';
2
+ /** These mappings assume horizontal-tb and LTR-authored reading edges, never physical coordinates. */
3
+ export function directionalProperty(property, value, react = false) {
4
+ const length = (v, negative = true, auto = false) => {
5
+ if (auto && v === 'auto')
6
+ return true;
7
+ if (!/^-?(?:\d*\.)?\d+(?:px|em|rem|%|vw|vh|ch|ex)?$/.test(v) || !negative && v.startsWith('-'))
8
+ return false;
9
+ return react || /[a-z%]$/.test(v) || Number(v) === 0;
10
+ };
11
+ const alignmentTokens = valueParser(value).nodes.filter(n => n.type !== 'space' && n.type !== 'comment');
12
+ if (property === 'text-align' && alignmentTokens.length === 1 && alignmentTokens[0].type === 'word' && /^(left|right)$/.test(alignmentTokens[0].value))
13
+ return { logical: property, value: alignmentTokens[0].value === 'left' ? 'start' : 'end', family: 'alignment' };
14
+ if (/^(left|right)$/.test(property) && length(value, true, true))
15
+ return { logical: 'inset-inline-' + (property === 'left' ? 'start' : 'end'), value, family: 'positioning' };
16
+ const spacing = /^(margin|padding)-(left|right)$/.exec(property);
17
+ if (spacing && length(value, spacing[1] === 'margin', spacing[1] === 'margin'))
18
+ return { logical: spacing[1] + '-inline-' + (spacing[2] === 'left' ? 'start' : 'end'), value, family: 'spacing' };
19
+ const corner = /^border-(top|bottom)-(left|right)-radius$/.exec(property);
20
+ if (corner) {
21
+ const words = valueParser(value).nodes.filter(n => n.type !== 'space');
22
+ if (words.length >= 1 && words.length <= 2 && words.every(n => n.type === 'word' && length(n.value, false)))
23
+ return { logical: 'border-' + (corner[1] === 'top' ? 'start' : 'end') + '-' + (corner[2] === 'left' ? 'start' : 'end') + '-radius', value, family: 'corners' };
24
+ return;
25
+ }
26
+ const border = /^border-(left|right)(-(width|style|color))?$/.exec(property);
27
+ if (border) {
28
+ const width = (v) => length(v, false) || /^(thin|medium|thick)$/.test(v);
29
+ const style = (v) => /^(none|hidden|solid|dashed|dotted|double|groove|ridge|inset|outset)$/.test(v);
30
+ const color = (v) => /^(#[a-fA-F0-9]{3}|#[a-fA-F0-9]{4}|#[a-fA-F0-9]{6}|#[a-fA-F0-9]{8}|transparent|currentColor|black|white|red|green|blue|gray)$/.test(v);
31
+ const words = valueParser(value).nodes.filter(n => n.type !== 'space');
32
+ const valid = border[3] === 'width' ? width(value) : border[3] === 'style' ? style(value) : border[3] === 'color' ? color(value) : words.length === 3 && words.every(n => n.type === 'word') && width(words[0].value) && style(words[1].value) && color(words[2].value);
33
+ if (valid)
34
+ return { logical: 'border-inline-' + (border[1] === 'left' ? 'start' : 'end') + (border[2] ?? ''), value, family: 'borders' };
35
+ }
36
+ return;
37
+ }
38
+ export function propertyConflict(property, other, family) {
39
+ if (['all', 'direction', 'writing-mode'].includes(other) || other === property)
40
+ return true;
41
+ if (family === 'alignment')
42
+ return other === 'text-align';
43
+ if (family === 'positioning')
44
+ return /^(inset(?:-|$)|transform|translate|rotate|scale|float|clear|animation(?:-|$))/.test(other);
45
+ if (family === 'spacing') {
46
+ const kind = property.split('-')[0];
47
+ return other === kind || other.startsWith(kind + '-inline') || other.startsWith(kind + '-block');
48
+ }
49
+ if (family === 'corners')
50
+ return other === 'border-radius' || /^border-(start|end)-/.test(other);
51
+ return /^(border$|border-(width|style|color)$|border-(inline|block)(-|$))/.test(other) || other !== property && other.startsWith(property + '-') || property.startsWith(other + '-');
52
+ }
53
+ export const readingEdgeReason = 'Requires semantic review: horizontal-tb, LTR-authored reading-start/end intent. RTL intentionally changes the side; inspect inherited direction, writing mode, cross-stylesheet cascade and product semantics. Values, comments and !important are preserved.';
package/dist/discovery.js CHANGED
@@ -2,7 +2,6 @@ import { lstat, readdir, readFile, realpath } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
3
  const excludedDirectories = new Set(['node_modules', '.git', '.nx', 'dist', 'build', 'out', 'coverage', '.next', '.cache', 'test-results', 'playwright-report', '.vite', '.turbo']);
4
4
  const supported = /\.(css|scss|tsx?|jsx?|html)$/;
5
- const sourceLike = /\.(css|scss|sass|less|styl|tsx?|jsx?|html)$/;
6
5
  const compareNames = (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
7
6
  async function walk(root, relative, files, skipped) {
8
7
  for (const entry of (await readdir(join(root, relative), { withFileTypes: true })).sort(compareNames)) {
@@ -21,7 +20,7 @@ async function walk(root, relative, files, skipped) {
21
20
  if (supported.test(path) && !path.endsWith('.stories.tsx')) {
22
21
  files.add(path);
23
22
  }
24
- else if (sourceLike.test(path) && !path.endsWith('.stories.tsx')) {
23
+ else {
25
24
  skipped.push(path);
26
25
  }
27
26
  }
@@ -1,19 +1,19 @@
1
- import { BIDI_TRANSFORMATION_ID, proposeBidiIsolation } from './codemod.js';
2
- // Deliberately empty until a transformation implementation and its preconditions are verified.
3
- export const verifiedTransformationStrategies = { 'RTL.BIDI.ISOLATION:invoice-id': { preconditions: ['exact InvoiceTable.tsx finding range', 'direct i.id JSX expression', 'no bdi or dir ancestor'], transformationId: BIDI_TRANSFORMATION_ID } };
1
+ import { transformations, transformationFor, proposeTransformation } from './transformations.js';
2
+ // This registry describes implemented transformations, not scanner-rule coverage.
3
+ export const verifiedTransformationStrategies = Object.fromEntries(transformations.map(t => [t.key, { preconditions: ['verified scanner source range', 'parser and family-specific safeguards', 'explicit semantic acceptance'], transformationId: t.id }]));
4
4
  export function classifyEligibility(finding, evidenceComplete = true, sourceText) {
5
5
  if (!evidenceComplete)
6
6
  return { eligibility: 'MANUAL', reason: 'Required evidence is incomplete or stale.', evidence: finding.evidenceIds, transformationId: null, blockers: ['INCOMPLETE_OR_STALE_EVIDENCE'] };
7
- if (finding.ruleId === 'RTL.BIDI.ISOLATION' && sourceText) {
7
+ if (transformationFor(finding) && sourceText) {
8
8
  try {
9
- const proposal = proposeBidiIsolation(finding, sourceText);
10
- return { eligibility: 'AUTOMATED_ELIGIBLE', reason: 'The verified bidi-isolation transformation matches the exact supported AST shape and bounded source range.', evidence: finding.evidenceIds, transformationId: proposal.transformationId, blockers: [] };
9
+ const proposal = proposeTransformation(finding, sourceText);
10
+ return { eligibility: finding.ruleId === 'RTL.BIDI.ISOLATION' ? 'AUTOMATED_ELIGIBLE' : 'ASSISTED', reason: proposal.reason, evidence: finding.evidenceIds, transformationId: proposal.transformationId, blockers: [] };
11
11
  }
12
12
  catch (error) {
13
- return { eligibility: 'ASSISTED', reason: 'A bounded bidi-isolation proposal exists, but the source does not satisfy the verified transformation preconditions.', evidence: finding.evidenceIds, transformationId: BIDI_TRANSFORMATION_ID, blockers: [error instanceof Error ? error.message : 'TRANSFORMATION_PRECONDITION_FAILED'] };
13
+ return { eligibility: 'ASSISTED', reason: 'The transformation preconditions are not satisfied; inspect the concrete blocker before proposing a change.', evidence: finding.evidenceIds, transformationId: transformationFor(finding).id, blockers: [error instanceof Error ? error.message : 'TRANSFORMATION_PRECONDITION_FAILED'] };
14
14
  }
15
15
  }
16
- if (finding.ruleId === 'RTL.BIDI.ISOLATION' && finding.path === 'apps/invoicing/src/components/InvoiceTable.tsx')
16
+ if (finding.ruleId === 'RTL.BIDI.ISOLATION')
17
17
  return { eligibility: 'ASSISTED', reason: 'A bounded bidi-isolation proposal is possible, but rendered punctuation and product semantics still require human review.', evidence: finding.evidenceIds, transformationId: 'bidi-isolate-auto', blockers: ['HUMAN_SEMANTIC_REVIEW_REQUIRED', 'NO_VERIFIED_CODEMOD_IMPLEMENTATION'] };
18
18
  return { eligibility: 'MANUAL', reason: 'Semantic intent, runtime behavior, or styling ownership is not established by static evidence.', evidence: finding.evidenceIds, transformationId: null, blockers: ['SEMANTIC_OR_RUNTIME_INTENT_UNPROVEN'] };
19
19
  }
@@ -0,0 +1,110 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { access, mkdir, readFile, rename, lstat, writeFile } from 'node:fs/promises';
3
+ import { constants } from 'node:fs';
4
+ import { homedir, tmpdir } from 'node:os';
5
+ import { dirname, isAbsolute, join, parse, relative, resolve, sep } from 'node:path';
6
+ import { validateReviewIdentity } from './review-session.js';
7
+ export const EVIDENCE_STORE_VERSION = 1;
8
+ export const DEFAULT_EVIDENCE_STORE_PATH = process.env.RTL_EVIDENCE_STORE_PATH || join(homedir(), '.rtl-migration-analyzer', 'review-evidence-v1.json');
9
+ const inside = (root, target) => { const value = relative(root, target); return value === '' || (value !== '..' && !value.startsWith(`..${sep}`) && !isAbsolute(value)); };
10
+ async function rejectSymlinkPath(path) { const absolute = resolve(path); const root = parse(absolute).root; let cursor = root; for (const part of absolute.slice(root.length).split(sep).filter(Boolean)) {
11
+ cursor = join(cursor, part);
12
+ try {
13
+ if ((await lstat(cursor)).isSymbolicLink() && !inside(cursor, resolve(homedir())) && !inside(cursor, resolve(tmpdir())))
14
+ throw new Error('EVIDENCE_STORE_SYMLINK');
15
+ }
16
+ catch (error) {
17
+ if (error.code !== 'ENOENT')
18
+ throw error;
19
+ }
20
+ } }
21
+ function validateStorePath(path) { const absolute = resolve(path); if (!isAbsolute(absolute) || !absolute.endsWith(`${sep}review-evidence-v1.json`))
22
+ throw new Error('INVALID_EVIDENCE_STORE_PATH'); return absolute; }
23
+ const digest = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
24
+ const immutablePayload = (snapshot) => { const { integritySha256: _ignored, ...payload } = snapshot; return payload; };
25
+ export function evidenceIntegrity(snapshot) { return digest(immutablePayload(snapshot)); }
26
+ export function validateEvidenceSnapshot(snapshot) {
27
+ if (!snapshot || typeof snapshot !== 'object')
28
+ throw new Error('INVALID_EVIDENCE_SNAPSHOT');
29
+ const value = snapshot;
30
+ validateReviewIdentity(value);
31
+ if (!value.snapshotId || typeof value.snapshotId !== 'string' || value.snapshotId.length > 100)
32
+ throw new Error('INVALID_EVIDENCE_SNAPSHOT_ID');
33
+ if (!value.candidatePatchIdentity || value.candidatePatchIdentity.path !== 'apps/invoicing/src/components/InvoiceTable.tsx')
34
+ throw new Error('INVALID_EVIDENCE_PATCH_IDENTITY');
35
+ if (value.patch && (value.patch.path !== value.sourcePath || value.patch.findingId !== value.findingId || !Number.isInteger(value.patch.startOffset) || !Number.isInteger(value.patch.endOffset) || value.patch.endOffset < value.patch.startOffset || value.patch.expectedSha256 !== value.candidatePatchIdentity.expectedSha256 || createHash('sha256').update(value.patch.replacement).digest('hex') !== value.candidatePatchIdentity.replacementSha256))
36
+ throw new Error('INVALID_EVIDENCE_PATCH');
37
+ if (![value.candidatePatchIdentity.expectedSha256, value.candidatePatchIdentity.replacementSha256, value.originalSourceSha256, value.candidateSourceSha256].every(x => typeof x === 'string' && /^[a-f0-9]{64}$/.test(x)))
38
+ throw new Error('INVALID_EVIDENCE_DIGEST');
39
+ if (typeof value.codeDiff !== 'string' || value.codeDiff.length > 100_000 || !value.scannerBefore || !value.scannerAfter || !Array.isArray(value.browserDomValidation) || !Array.isArray(value.screenshotReferences) || !Number.isFinite(Date.parse(value.timestamp)) || !['Verified Correct', 'Ready for Review', 'Approved', 'Rejected'].includes(value.decision))
40
+ throw new Error('INVALID_EVIDENCE_SNAPSHOT');
41
+ for (const ref of [...value.browserDomValidation, ...value.screenshotReferences])
42
+ if (typeof ref !== 'string' || ref.length > 1000 || isAbsolute(ref) || ref.split(/[\\/]/).includes('..'))
43
+ throw new Error('INVALID_EVIDENCE_REFERENCE');
44
+ if (value.screenshotDigests !== undefined && (!Array.isArray(value.screenshotDigests) || value.screenshotDigests.length !== value.screenshotReferences.length || value.screenshotDigests.some(x => typeof x !== 'string' || !/^[a-f0-9]{64}$/.test(x))))
45
+ throw new Error('INVALID_SCREENSHOT_DIGESTS');
46
+ if (value.supersedesSnapshotId !== undefined && (typeof value.supersedesSnapshotId !== 'string' || value.supersedesSnapshotId.length > 100))
47
+ throw new Error('INVALID_SUPERSEDES_SNAPSHOT_ID');
48
+ if (value.integritySha256 !== evidenceIntegrity(value))
49
+ throw new Error('EVIDENCE_INTEGRITY_MISMATCH');
50
+ return { ...value, browserDomValidation: [...value.browserDomValidation], screenshotReferences: [...value.screenshotReferences] };
51
+ }
52
+ export class EvidenceSnapshotStore {
53
+ path;
54
+ snapshots = new Map();
55
+ loaded = false;
56
+ error = null;
57
+ constructor(path = DEFAULT_EVIDENCE_STORE_PATH) { this.path = validateStorePath(path); }
58
+ get loadError() { return this.error; }
59
+ async load() { await rejectSymlinkPath(dirname(this.path)); try {
60
+ const raw = JSON.parse(await readFile(this.path, 'utf8'));
61
+ if (raw.formatVersion !== EVIDENCE_STORE_VERSION || !Array.isArray(raw.snapshots))
62
+ throw new Error('INCOMPATIBLE_EVIDENCE_STORE');
63
+ const next = new Map();
64
+ for (const item of raw.snapshots) {
65
+ const snapshot = validateEvidenceSnapshot(item);
66
+ if (next.has(snapshot.snapshotId))
67
+ throw new Error('DUPLICATE_EVIDENCE_SNAPSHOT');
68
+ next.set(snapshot.snapshotId, snapshot);
69
+ }
70
+ this.snapshots = next;
71
+ this.error = null;
72
+ }
73
+ catch (error) {
74
+ if (error.code === 'ENOENT') {
75
+ this.snapshots.clear();
76
+ this.error = null;
77
+ }
78
+ else {
79
+ this.snapshots.clear();
80
+ this.error = error instanceof Error ? error.message : 'EVIDENCE_STORE_LOAD_FAILED';
81
+ }
82
+ } this.loaded = true; }
83
+ list(identity) { validateReviewIdentity(identity); return [...this.snapshots.values()].filter(x => x.findingId === identity.findingId && x.sourcePath === identity.sourcePath && x.inputDigest === identity.inputDigest && x.policyDigest === identity.policyDigest && x.schemaVersion === identity.schemaVersion); }
84
+ async append(input) { if (!this.loaded || this.error)
85
+ throw new Error(`EVIDENCE_STORE_UNAVAILABLE${this.error ? `:${this.error}` : ''}`); const snapshot = { ...input, snapshotId: input.snapshotId ?? randomUUID(), integritySha256: '' }; const complete = { ...snapshot, integritySha256: evidenceIntegrity(snapshot) }; validateEvidenceSnapshot(complete); if (this.snapshots.has(complete.snapshotId))
86
+ throw new Error('EVIDENCE_SNAPSHOT_IMMUTABLE'); this.snapshots.set(complete.snapshotId, complete); try {
87
+ await this.persist();
88
+ return complete;
89
+ }
90
+ catch (error) {
91
+ this.snapshots.delete(complete.snapshotId);
92
+ throw error;
93
+ } }
94
+ async appendApproval(snapshotId) { const source = this.snapshots.get(snapshotId); if (!source)
95
+ throw new Error('EVIDENCE_SNAPSHOT_NOT_FOUND'); if (source.decision === 'Approved')
96
+ return source; if (source.decision !== 'Ready for Review')
97
+ throw new Error('EVIDENCE_NOT_APPROVABLE'); const { snapshotId: _old, integritySha256: _integrity, ...payload } = source; return this.append({ ...payload, decision: 'Approved', supersedesSnapshotId: source.snapshotId }); }
98
+ async persist() { const parent = dirname(this.path); await rejectSymlinkPath(parent); await mkdir(parent, { recursive: true, mode: 0o700 }); const temporary = join(parent, `.review-evidence-v1.${process.pid}.${Date.now()}.tmp`); try {
99
+ await writeFile(temporary, `${JSON.stringify({ formatVersion: EVIDENCE_STORE_VERSION, snapshots: [...this.snapshots.values()] }, null, 2)}\n`, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
100
+ await rename(temporary, this.path);
101
+ }
102
+ catch (error) {
103
+ try {
104
+ await access(temporary, constants.F_OK);
105
+ await rename(temporary, `${temporary}.failed`);
106
+ }
107
+ catch { /* preserve failure */ }
108
+ throw error;
109
+ } }
110
+ }
@@ -0,0 +1,98 @@
1
+ const route = (application, path, prepare) => ({ id: application + ':' + path + (prepare ? ':' + prepare : ''), application, path, label: application + ' · ' + path + (prepare ? ' · ' + prepare : ''), ...(prepare ? { prepare } : {}) });
2
+ const invoice = route('invoicing', '/invoices'), overview = route('invoicing', '/'), orders = route('procurement', '/');
3
+ const detail = route('invoicing', '/invoices/INV-2026-1048'), orderDetail = route('procurement', '/orders/PO-2026-402');
4
+ const customers = route('invoicing', '/customers'), customerDialog = route('invoicing', '/customers', 'customer-dialog');
5
+ const create = route('invoicing', '/invoices/new'), confirm = route('invoicing', '/invoices/new', 'invoice-confirm');
6
+ const shared = [invoice, orders];
7
+ export function exampleContextMapping(f) {
8
+ const evidence = [f.path + ' · ' + f.context, 'Verified example route/component imports; selectors refer to the existing rendered markup.'];
9
+ const target = (label, selector, routes, extra = {}) => ({ kind: 'targets', label, selector, routes, evidence, ...extra });
10
+ if (f.ruleId === 'RTL.DOCUMENT.INITIAL')
11
+ return { kind: 'document', label: 'Initial HTML direction · whole document; runtime direction is reported separately', selector: 'html', routes: [f.path.includes('procurement') ? orders : invoice], evidence };
12
+ if (f.path.endsWith('/InvoiceTable.tsx')) {
13
+ if (f.ruleId === 'RTL.ICON.PROGRESSION')
14
+ return target('Invoice row navigation icon', f.context.endsWith('/ArrowBack') ? 'tbody [data-testid="ArrowBackIcon"]' : 'tbody [data-testid="ArrowForwardIcon"]', [invoice, overview], { preferredMode: f.context.endsWith('/ArrowBack') ? 'rtl' : 'ltr' });
15
+ if (f.original === '{i.id}')
16
+ return target('Invoice identifier · containing link', f.id === 'RTL.BIDI.ISOLATION:1c1265d83508cd495927ae75' ? '.review-extra-id' : '.invoice-link', [invoice, overview]);
17
+ if (f.original === '{c.name}')
18
+ return target('Invoice customer name', '.customer-cell strong', [invoice, overview]);
19
+ if (f.original === '{c.email}')
20
+ return target('Invoice customer email', '.customer-cell small', [invoice, overview]);
21
+ if (f.original.includes('money('))
22
+ return target('Invoice amount', '.amount', [invoice, overview]);
23
+ }
24
+ // Only the existing workflow regression fixture imports these two named spans.
25
+ if (f.path.endsWith('/ReviewTokens.tsx'))
26
+ return target('Regression fixture identifier span', f.id === 'RTL.BIDI.ISOLATION:9abfb96bb050e95f51ed573b' ? '.token-one' : '.token-two', [invoice], { limitation: 'Workflow fixture only; not present in the 47-finding checkout.' });
27
+ if (f.path.endsWith('/CreateInvoice.tsx')) {
28
+ if (f.original === '{c.name}')
29
+ return target('Customer menu option', '[role="listbox"] [role="option"]', [route('invoicing', '/invoices/new', 'customer-menu')]);
30
+ if (f.original.includes('customers.find'))
31
+ return target('Confirmation customer name', '.MuiDialogContent-root p:first-child strong:first-of-type', [confirm]);
32
+ if (f.original.includes('money('))
33
+ return target('Invoice total', f.id === 'RTL.BIDI.ISOLATION:f452c219f31ee6379007a4e9' ? '.MuiDialogContent-root p:first-child strong:last-of-type' : '.form-total strong', [f.id === 'RTL.BIDI.ISOLATION:f452c219f31ee6379007a4e9' ? confirm : create]);
34
+ }
35
+ if (f.path.endsWith('/Customers.tsx')) {
36
+ if (f.original === '{c.name}')
37
+ return target('Customer card name', '.customer-card h3', [customers]);
38
+ if (f.original === '{c.address}')
39
+ return target('Customer dialog address', '.MuiDialogContent-root p.hint', [customerDialog]);
40
+ if (f.original === '{c.email}')
41
+ return target('Customer email', f.id === 'RTL.BIDI.ISOLATION:75fcb34b4ca84b10731b3272' ? '.MuiDialogContent-root p:nth-of-type(2)' : '.customer-card p:first-of-type', [f.id === 'RTL.BIDI.ISOLATION:75fcb34b4ca84b10731b3272' ? customerDialog : customers]);
42
+ }
43
+ if (f.path.endsWith('/Dashboard.tsx')) {
44
+ if (f.ruleId === 'RTL.CHART.LABEL_FLOW')
45
+ return target('Revenue chart and its real labels', '.chart-wrap svg', [overview]);
46
+ if (f.ruleId === 'RTL.ICON.LITERAL')
47
+ return target('View all invoices link', '.section-title a', [overview]);
48
+ if (f.ruleId === 'RTL.CSS.PHYSICAL')
49
+ return target('Payment breakdown percentage', '.breakdown-row strong > span', [overview], { css: { property: 'margin-left', value: '10px', inline: true } });
50
+ }
51
+ if (f.path.endsWith('/InvoiceDetails.tsx')) {
52
+ if (f.original === '{c.name}')
53
+ return target('Bill-to customer name', '.detail-grid h3', [detail]);
54
+ if (f.original === '{c.address}' || f.original === '{c.email}')
55
+ return target('Bill-to address/email · containing paragraph', '.detail-grid p.hint', [detail], { limitation: 'Both text expressions share one paragraph; the containing rendered element is highlighted.' });
56
+ if (f.original.includes('money('))
57
+ return target('Invoice total due', '.form-total strong', [detail]);
58
+ }
59
+ if (f.path.endsWith('/Invoices.tsx')) {
60
+ if (f.ruleId === 'RTL.RUNTIME.PAGINATION')
61
+ return target('Invoice pagination', '.pagination nav', [invoice]);
62
+ if (f.ruleId === 'RTL.CSS.PHYSICAL')
63
+ return target('Invoice count alignment', '.toolbar > .hint', [invoice], { css: { property: 'margin-left', value: 'auto', inline: true } });
64
+ }
65
+ if (f.path === 'apps/procurement/src/App.tsx') {
66
+ if (f.context === 'Orders')
67
+ return target(f.original === '{o.id}' ? 'Purchase order identifier' : 'Purchase order amount', f.original === '{o.id}' ? '.invoice-link' : '.amount', [orders]);
68
+ if (f.context === 'Details')
69
+ return target(f.original === '{order.id}' ? 'Purchase order heading' : 'Purchase order total', f.original === '{order.id}' ? '.page-heading h1' : '.form-total strong', [orderDetail]);
70
+ }
71
+ if (f.path === 'libs/design-system/src/index.tsx') {
72
+ if (f.ruleId === 'RTL.FORM.DIRECTION')
73
+ return target('Shared FormField instances', '.MuiFormControl-root', [invoice, orders, create, customers]);
74
+ if (f.ruleId === 'RTL.GEOMETRY.EDGE')
75
+ return target('Shared Modal close control', '.MuiDialogTitle-root button', [customerDialog, confirm], { css: { property: 'right', value: '12px', inline: true } });
76
+ if (f.ruleId === 'RTL.TABLE.ALIGNMENT')
77
+ return target('Shared table ' + (f.id === 'RTL.TABLE.ALIGNMENT:9e76dea095ca377d5e42c677' ? 'header' : 'body') + ' cells', f.id === 'RTL.TABLE.ALIGNMENT:9e76dea095ca377d5e42c677' ? 'thead th' : 'tbody td', [invoice, orders, overview, detail, orderDetail]);
78
+ if (f.ruleId === 'RTL.GEOMETRY.ORDER')
79
+ return target('Shared responsive sidebar · actual off-canvas geometry', 'aside', shared, { preferredViewport: 1, preferredMode: f.original.includes('translateX(100%)') ? 'rtl' : 'ltr', css: { property: 'transform', value: f.original.includes('translateX(100%)') ? 'translateX(100%)' : 'translateX(-100%)', media: '(max-width: 900px)', rtlOnly: f.original.includes('translateX(100%)') }, limitation: 'A collapsed sidebar can be intentionally outside the viewport. Target geometry and active/overridden CSS are reported; use Reveal navigation to inspect the open component.' });
80
+ if (f.ruleId === 'RTL.BRAND.ISLAND')
81
+ return target('Shared brand link', 'aside .brand', shared.map(r => route(r.application, r.path, 'sidebar')));
82
+ if (f.ruleId === 'RTL.ICON.PROGRESSION' || f.ruleId === 'RTL.CSS.PHYSICAL')
83
+ return target('Shared application-switch arrow', '.app-link [data-testid="ArrowForwardIcon"]', shared.map(r => route(r.application, r.path, 'sidebar')), f.ruleId === 'RTL.CSS.PHYSICAL' ? { css: { property: 'margin-left', value: 'auto', inline: true } } : {});
84
+ }
85
+ if (f.path === 'libs/design-system/src/runtime.tsx' && f.ruleId === 'RTL.DOCUMENT.RUNTIME')
86
+ return { kind: 'document', label: 'Shared Provider · document direction/lang and theme context', selector: 'html', routes: shared, evidence };
87
+ if (f.path === 'libs/design-system/src/styles.css') {
88
+ const selector = f.context.replace(/^stylesheet\//, '');
89
+ const declaration = f.original.match(/^([\w-]+):\s*(.*?);?$/);
90
+ if (declaration) {
91
+ const routes = selector === '.chart-labels' || selector === '.kpi-note b' ? [overview] : selector.startsWith('.header') ? shared : shared.map(r => route(r.application, r.path, 'sidebar'));
92
+ return target('Shared stylesheet · ' + selector, selector, routes, { css: { selector, property: declaration[1], value: declaration[2].replace(/;$/, '') } });
93
+ }
94
+ }
95
+ if (f.path === 'libs/shared/src/index.ts' && f.ruleId === 'RTL.RUNTIME.LOCALE')
96
+ return target('Shared money formatter output · locale semantics require review', '.amount', [invoice, orders], { limitation: 'These consumers call the real money() formatter. A target match does not establish a locale defect or authorize changing currency data.' });
97
+ return { kind: 'unresolved', label: 'Unresolved example mapping', selector: '', routes: [], evidence: [f.path + ' · ' + f.context, 'No configured source-to-route binding was found.'], limitation: 'No verified route/target binding for this source expression. Add a verified example mapping; do not substitute an unrelated page.' };
98
+ }
@@ -0,0 +1,27 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { homedir } from 'node:os';
3
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
4
+ import { dirname, join } from 'node:path';
5
+ import { validateReviewIdentity } from './review-session.js';
6
+ export const DEFAULT_MANUAL_CHANGE_STORE_PATH = process.env.RTL_MANUAL_CHANGE_STORE_PATH || join(homedir(), '.rtl-migration-analyzer', 'manual-changes-v1.json');
7
+ const digest = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
8
+ export class ManualChangeStore {
9
+ path;
10
+ changes = [];
11
+ loaded = false;
12
+ constructor(path = DEFAULT_MANUAL_CHANGE_STORE_PATH) {
13
+ this.path = path;
14
+ }
15
+ async load() { try {
16
+ this.changes = JSON.parse(await readFile(this.path, 'utf8'));
17
+ }
18
+ catch (e) {
19
+ if (e.code !== 'ENOENT')
20
+ throw new Error('MANUAL_CHANGE_STORE_UNAVAILABLE');
21
+ this.changes = [];
22
+ } this.loaded = true; }
23
+ list(identity) { validateReviewIdentity(identity); return this.changes.filter(x => x.findingId === identity.findingId && x.sourcePath === identity.sourcePath && x.inputDigest === identity.inputDigest && x.policyDigest === identity.policyDigest); }
24
+ async append(input) { if (!this.loaded)
25
+ throw new Error('MANUAL_CHANGE_STORE_NOT_LOADED'); validateReviewIdentity(input); if (!/^[a-f0-9]{64}$/.test(input.beforeSourceSha256) || !/^[a-f0-9]{64}$/.test(input.afterSourceSha256) || input.beforeSourceSha256 === input.afterSourceSha256)
26
+ throw new Error('MANUAL_CHANGE_SOURCE_NOT_CHANGED'); const value = { ...input, changeId: randomUUID(), timestamp: new Date().toISOString(), sourceChanged: true, integritySha256: '' }; const item = { ...value, integritySha256: digest(value) }; this.changes.push(item); await mkdir(dirname(this.path), { recursive: true, mode: 0o700 }); const tmp = `${this.path}.${process.pid}.tmp`; await writeFile(tmp, `${JSON.stringify(this.changes, null, 2)}\n`, { mode: 0o600, flag: 'wx' }); await rename(tmp, this.path); return item; }
27
+ }
@@ -0,0 +1,19 @@
1
+ export function projectLifecycle(input) {
2
+ const latestAudit = input.audit.slice().sort((a, b) => Date.parse(b.timestamp) - Date.parse(a.timestamp))[0];
3
+ if (latestAudit?.type === 'ROLLED_BACK')
4
+ return 'Rolled Back';
5
+ if (latestAudit?.type === 'APPLY_FAILED' || latestAudit?.type === 'ROLLBACK_FAILED')
6
+ return 'Failed';
7
+ const approvedEvidence = input.evidence.find(e => (e.decision === 'Approved' || e.decision === 'Ready for Review') && !e.scannerAfter.findingPresent);
8
+ if (latestAudit?.type === 'APPLIED')
9
+ return input.currentSourceSha256 && latestAudit.resultingSha256 === input.currentSourceSha256 ? 'Applied' : 'Stale';
10
+ if (approvedEvidence && input.currentSourceSha256 && input.currentSourceSha256 !== approvedEvidence.originalSourceSha256 && input.currentSourceSha256 !== approvedEvidence.candidateSourceSha256)
11
+ return 'Stale';
12
+ if (approvedEvidence && input.review?.status === 'Approved')
13
+ return 'Validated';
14
+ if (input.review?.status === 'Validation Failed')
15
+ return 'Failed';
16
+ if (input.review?.status === 'Candidate Proposed' || input.review?.status === 'Ready for Review' || input.review?.status === 'Approved' || input.decision)
17
+ return 'In Progress';
18
+ return 'Pending';
19
+ }
@@ -0,0 +1,78 @@
1
+ import { createServer } from 'node:net';
2
+ import { join } from 'node:path';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { createHash } from 'node:crypto';
5
+ import { loadPreviewConfiguration } from './preview-configuration.js';
6
+ import { writePreviewRuntimeConfig } from './preview-runtime.js';
7
+ import { ORIGINAL_PREVIEW_ORIGINS } from './contextual-preview.js';
8
+ import { spawnPreviewRuntime, signalOwnedRuntime } from './runtime-process.js';
9
+ const starts = new Map();
10
+ const children = new Map();
11
+ /** Only call after authoritative report/mapping checks. No candidate is created or patched. */
12
+ export async function initializeOriginalPreview(root, application) {
13
+ const key = root + '|' + application;
14
+ const pending = starts.get(key);
15
+ if (pending)
16
+ return pending;
17
+ const operation = start();
18
+ starts.set(key, operation);
19
+ try {
20
+ await operation;
21
+ }
22
+ finally {
23
+ starts.delete(key);
24
+ }
25
+ async function start() {
26
+ const configuration = await loadPreviewConfiguration(root), app = configuration.applications[application];
27
+ const origin = app?.originalOrigin ?? ORIGINAL_PREVIEW_ORIGINS[application];
28
+ if (!origin)
29
+ throw Error('ORIGINAL_APPLICATION_NOT_CONFIGURED');
30
+ const url = new URL(origin);
31
+ if (url.protocol !== 'http:' || url.hostname !== '127.0.0.1')
32
+ throw Error('UNAPPROVED_PREVIEW_ORIGIN');
33
+ // Never stop or adopt a process by port. A running owned Vite observes wrapper updates.
34
+ const owned = children.get(key);
35
+ if (!owned || owned.exitCode !== null || owned.signalCode !== null) {
36
+ await new Promise((resolve, reject) => {
37
+ const probe = createServer();
38
+ probe.once('error', () => reject(Error('ORIGINAL_PREVIEW_PORT_OCCUPIED')));
39
+ probe.listen(Number(url.port), '127.0.0.1', () => probe.close(() => resolve()));
40
+ });
41
+ }
42
+ const source = app?.entry ?? (application === 'invoicing' ? 'apps/invoicing/src/components/InvoiceTable.tsx' : 'apps/procurement/src/App.tsx');
43
+ const sourceSha256 = createHash('sha256').update(await readFile(join(root, source))).digest('hex');
44
+ const config = await writePreviewRuntimeConfig(root, { role: 'original', sessionId: 'original', sourceSha256 }, { application });
45
+ if (!owned || owned.exitCode !== null || owned.signalCode !== null) {
46
+ const child = await spawnPreviewRuntime(root, application, config, Number(url.port));
47
+ children.set(key, child);
48
+ child.on('error', () => { });
49
+ }
50
+ for (let attempt = 0; attempt < 100; attempt++) {
51
+ try {
52
+ const actual = await fetch(origin + '/__rtl_preview_identity', { signal: AbortSignal.timeout(500) }).then(r => r.json());
53
+ if (actual.projectRoot === root && actual.role === 'original' && actual.application === application && actual.sourceSha256 === sourceSha256)
54
+ return;
55
+ }
56
+ catch { /* Wait only for this initialization; descriptors verify the complete identity next. */ }
57
+ if (children.get(key)?.exitCode !== null || children.get(key)?.signalCode !== null)
58
+ break;
59
+ await new Promise(resolve => setTimeout(resolve, 100));
60
+ }
61
+ throw Error('ORIGINAL_PREVIEW_STARTUP_FAILED');
62
+ }
63
+ }
64
+ /** Signals every owned original runtime and waits for exit (SIGKILL after 2 s). Synchronous callers may ignore the promise. */
65
+ export function stopOwnedOriginalPreviews() {
66
+ return Promise.all([...children.values()].map(child => new Promise(resolve => {
67
+ if (child.exitCode !== null || child.signalCode !== null)
68
+ return resolve();
69
+ const timer = setTimeout(() => { signalOwnedRuntime(child, 'SIGKILL'); resolve(); }, 2000);
70
+ child.once('exit', () => { clearTimeout(timer); resolve(); });
71
+ signalOwnedRuntime(child);
72
+ }))).then(() => undefined);
73
+ }
74
+ /** Synchronous last resort for process exit. */
75
+ export function signalOwnedOriginalPreviews(signal = 'SIGKILL') {
76
+ for (const child of children.values())
77
+ signalOwnedRuntime(child, signal);
78
+ }
@@ -0,0 +1,65 @@
1
+ import { lstat } from 'node:fs/promises';
2
+ import { dirname, isAbsolute, normalize, parse, relative, resolve, sep } from 'node:path';
3
+ export class OutputPathError extends Error {
4
+ code;
5
+ constructor(code, message) {
6
+ super(`${code}: ${message}`);
7
+ this.code = code;
8
+ }
9
+ }
10
+ /**
11
+ * Validate and plan a future report destination. This function is read-only:
12
+ * it does not stat, create, truncate, or write the destination.
13
+ *
14
+ * Milestone 2 must revalidate this plan immediately before writing and use a
15
+ * no-follow/atomic write strategy to protect against symlink races.
16
+ */
17
+ export async function planOutputPath(root, requestedPath, format, options = {}) {
18
+ const windowsPath = /^[A-Za-z]:[\\/]/.test(requestedPath) || requestedPath.startsWith('\\\\') || requestedPath.startsWith('//');
19
+ const requestedAbsolute = isAbsolute(requestedPath);
20
+ if (!requestedPath || windowsPath || requestedPath.includes('\\') || /[\0\r\n]/.test(requestedPath)) {
21
+ throw new OutputPathError('ABSOLUTE', 'output path must be a non-empty repository-relative POSIX path');
22
+ }
23
+ const normalized = normalize(requestedPath);
24
+ const rootPath = resolve(root);
25
+ const destination = resolve(isAbsolute(normalized) ? normalized : resolve(rootPath, normalized));
26
+ const rel = relative(rootPath, destination);
27
+ if (!requestedAbsolute && (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)))
28
+ throw new OutputPathError('OUTSIDE_ROOT', 'relative output path escapes the scanner root');
29
+ if (rel === '' || (rel !== '' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)))
30
+ throw new OutputPathError('INPUT_TREE', 'output path may not be inside the scanner root');
31
+ if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
32
+ const protectedRoots = [rootPath, ...(options.protectedRoots ?? [])].map(item => resolve(item));
33
+ if (protectedRoots.some(protectedRoot => { const r = relative(protectedRoot, destination); return r === '' || (r !== '' && !r.startsWith(`..${sep}`) && !isAbsolute(r)); }))
34
+ throw new OutputPathError('INPUT_TREE', 'output path is inside a protected input root');
35
+ }
36
+ if (parse(destination).root !== parse(rootPath).root && !isAbsolute(destination)) {
37
+ throw new OutputPathError('INPUT_TREE', 'output path may not be inside a source or historical-input tree');
38
+ }
39
+ const expected = format === 'json' ? '.json' : '.md';
40
+ if (!destination.endsWith(expected))
41
+ throw new OutputPathError('UNSAFE_NAME', `output path must end with ${expected}`);
42
+ for (let current = dirname(destination);; current = dirname(current)) {
43
+ try {
44
+ if ((await lstat(current)).isSymbolicLink())
45
+ throw new OutputPathError('SYMLINK', 'output directory or ancestor is a symlink');
46
+ }
47
+ catch (error) {
48
+ if (error.code !== 'ENOENT')
49
+ throw error;
50
+ }
51
+ if (current === parse(current).root)
52
+ break;
53
+ }
54
+ try {
55
+ if ((await lstat(destination)).isSymbolicLink())
56
+ throw new OutputPathError('SYMLINK', 'output destination is a symlink');
57
+ if (await lstat(destination))
58
+ throw new OutputPathError('EXISTS', 'output destination already exists');
59
+ }
60
+ catch (error) {
61
+ if (error.code !== 'ENOENT')
62
+ throw error;
63
+ }
64
+ return Object.freeze({ root: rootPath, path: destination, relativePath: rel.split(sep).join('/'), format, revalidateBeforeWrite: true, overwrite: false });
65
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * A cold Vite dev server may reload once shortly after the first load ("optimized dependencies changed"),
3
+ * destroying the page's execution context mid-evaluation. Re-run page work that raced such a reload.
4
+ * Only that specific failure is retried; every other error, and the final attempt, propagates unchanged.
5
+ */
6
+ export async function retryAcrossNavigation(operation, attempts = 3) {
7
+ for (let attempt = 1;; attempt++) {
8
+ try {
9
+ return await operation();
10
+ }
11
+ catch (error) {
12
+ if (attempt >= attempts || !/Execution context was destroyed/.test(error instanceof Error ? error.message : String(error)))
13
+ throw error;
14
+ await new Promise(resolve => setTimeout(resolve, 250));
15
+ }
16
+ }
17
+ }