rtl-analyzer 0.1.0 → 0.3.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 (53) hide show
  1. package/README.md +88 -35
  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 +113 -0
  6. package/dist/contextual-preview.js +74 -0
  7. package/dist/controlled-apply.js +222 -0
  8. package/dist/css-directional.js +60 -0
  9. package/dist/css-icons.js +51 -0
  10. package/dist/css-spacing.js +64 -0
  11. package/dist/dashboard-client.js +57 -40
  12. package/dist/dashboard-contextual-preview.js +119 -0
  13. package/dist/dashboard-data.js +1 -1
  14. package/dist/dashboard-embedded-preview.js +200 -0
  15. package/dist/dashboard-html.js +11 -10
  16. package/dist/dashboard-review-details.js +175 -0
  17. package/dist/dashboard-review-workflow.js +151 -0
  18. package/dist/directional-properties.js +53 -0
  19. package/dist/discovery.js +1 -2
  20. package/dist/eligibility.js +8 -8
  21. package/dist/evidence-store.js +110 -0
  22. package/dist/example-preview-mappings.js +98 -0
  23. package/dist/manual-change-store.js +27 -0
  24. package/dist/migration-lifecycle.js +19 -0
  25. package/dist/original-preview-runtime.js +68 -0
  26. package/dist/output-path.js +65 -0
  27. package/dist/policy-validation.js +1 -1
  28. package/dist/preview-cli.js +22 -0
  29. package/dist/preview-companion.js +621 -0
  30. package/dist/preview-configuration.js +144 -0
  31. package/dist/preview-runtime.js +98 -0
  32. package/dist/project-configuration.js +48 -0
  33. package/dist/project-root.js +12 -0
  34. package/dist/react-inline.js +65 -0
  35. package/dist/report-publisher.js +4 -7
  36. package/dist/review-approval.js +9 -0
  37. package/dist/review-session.js +199 -54
  38. package/dist/review-store.js +175 -0
  39. package/dist/review-workflow.js +554 -0
  40. package/dist/rules.js +14 -13
  41. package/dist/runtime-process.js +35 -0
  42. package/dist/scan-history.js +35 -0
  43. package/dist/scan-manifest-store.js +26 -0
  44. package/dist/scan.js +55 -4
  45. package/dist/serialization.js +1 -0
  46. package/dist/source-context.js +93 -0
  47. package/dist/source-snippets.js +3 -3
  48. package/dist/standalone-cli.js +91 -9
  49. package/dist/tailwind.js +3 -1
  50. package/dist/transformations.js +20 -0
  51. package/dist/validation.js +71 -0
  52. package/dist/workflow-validation.js +46 -0
  53. package/package.json +20 -7
@@ -0,0 +1,175 @@
1
+ /** Read-only views of snapshots captured by the session coordinator. */
2
+ export const reviewDetailsClientSource = String.raw `
3
+ const reviewDetails=(()=>{
4
+ let dialog=null,opener=null,scope='current',tab='Activity',snapshot=null,historyId=null;
5
+ const labels=['Activity','Validation','Changes','Technical'],icons=['activity','check','code','layers'];
6
+ const paths={document:'<rect x="5" y="3" width="14" height="18" rx="2"/><path d="M9 8h6M9 12h6M9 16h4"/>',activity:'<path d="m3 16 5-6 7 4 6-8"/><circle cx="3" cy="16" r="1.5"/><circle cx="8" cy="10" r="1.5"/><circle cx="15" cy="14" r="1.5"/><circle cx="21" cy="6" r="1.5"/>',check:'<circle cx="12" cy="12" r="9"/><path d="m8 12 3 3 5-6"/>',code:'<path d="m7 7-5 5 5 5m10-10 5 5-5 5M14 4l-4 16"/>',layers:'<path d="m12 3 10 5-10 5L2 8Zm-10 9 10 5 10-5M2 16l10 5 10-5"/>',history:'<path d="M3 11a9 9 0 1 1 2 7M3 4v7h7m2-4v5l4 2"/>',close:'<path d="m5 5 14 14M19 5 5 19"/>',info:'<circle cx="12" cy="12" r="9"/><path d="M12 11v6m0-11v1"/>',warning:'<path d="m12 3 10 18H2Zm0 6v5m0 3v1"/>',start:'<circle cx="12" cy="12" r="8"/><circle cx="12" cy="12" r="2"/>',reject:'<circle cx="12" cy="12" r="9"/><path d="m8 8 8 8m0-8-8 8"/>',note:'<path d="M4 3h16v14h-9l-5 4v-4H4Zm4 5h8m-8 4h5"/>',rollback:'<path d="m8 4-6 6 6 6m-6-6h12a6 6 0 0 1 0 12"/>'};
7
+ function glyph(name,cls=''){const icon=document.createElementNS('http://www.w3.org/2000/svg','svg');icon.setAttribute('viewBox','0 0 24 24');icon.setAttribute('class','review-icon '+cls);icon.setAttribute('aria-hidden','true');icon.setAttribute('fill','none');icon.setAttribute('stroke','currentColor');icon.setAttribute('stroke-width','1.7');icon.setAttribute('stroke-linecap','round');icon.setAttribute('stroke-linejoin','round');icon.innerHTML=paths[name]||paths.info;return icon;}
8
+ function stamp(at){const node=el('time',at);const date=new Date(at);if(!Number.isNaN(date.valueOf())){node.dateTime=at;node.textContent=date.toLocaleString(undefined,{month:'short',day:'numeric',hour:'2-digit',minute:'2-digit'});node.title=date.toLocaleString()+' · '+at;}return node;}
9
+ const histories=()=>{const list=Array.isArray(snapshot.history)?snapshot.history:snapshot.history?[snapshot.history]:[];return list.filter((w,i)=>w&&list.findIndex(other=>other?.id===w.id)===i)};
10
+ function close(){if(!dialog)return;dialog.close();dialog.remove();dialog=null;const target=opener?.isConnected?opener:document.querySelector('[data-review-details]');target?.focus({preventScroll:true})}
11
+ function disclosure(title,text,cls=''){const node=el('details','',cls);node.append(el('summary',title),el('pre',text));return node}
12
+ function field(list,label,value){const content=el('dd'),text=el('span',value||'Not recorded');content.append(text);if(value&&['Review','Project root','Candidate session','Resumed from','Superseded by','Analysis hash','Policy hash'].includes(label)){const copy=el('button','Copy');copy.type='button';copy.setAttribute('aria-label','Copy '+label.toLowerCase());copy.onclick=async()=>{try{await navigator.clipboard.writeText(String(value));copy.textContent='Copied'}catch{copy.textContent='Select value';const selection=getSelection(),range=document.createRange();range.selectNodeContents(text);selection.removeAllRanges();selection.addRange(range)}};content.append(copy)}list.append(el('dt',label),content)}
13
+ const time=at=>{const date=new Date(at);return Number.isNaN(date.valueOf())?'Time not recorded':date.toLocaleString(undefined,{dateStyle:'medium',timeStyle:'short'})};
14
+ function render(){
15
+ if(!dialog)return;const body=dialog.querySelector('.review-details-body');body.replaceChildren();
16
+ dialog.querySelectorAll('[data-scope]').forEach(b=>b.setAttribute('aria-pressed',String(b.dataset.scope===scope)));
17
+ dialog.querySelectorAll('[role=tab]').forEach(b=>{b.setAttribute('aria-selected',String(b.dataset.tab===tab));b.tabIndex=b.dataset.tab===tab?0:-1});
18
+ const records=histories(),w=scope==='history'?(records.find(w=>w.id===historyId)||records.find(w=>w.supersededBy===snapshot.current?.id)||records[0]):snapshot.current;
19
+ body.setAttribute('aria-labelledby','review-tab-'+tab.toLowerCase());
20
+ const picker=dialog.querySelector('.review-history-select');picker.hidden=scope!=='history'||!records.length;picker.replaceChildren(...records.map(w=>new Option(time(w.createdAt)+' · '+(w.mode==='apply-first'?'Prepare all, then review':'Review one by one')+' · '+w.state+' · '+w.id.slice(0,8),w.id)));if(w&&scope==='history')picker.value=w.id;
21
+ dialog.querySelector('.review-header-summary').textContent='Current review and previous activity';
22
+ if(!w){body.append(el('p',scope==='history'?'No previous review.':'No active current review. Decisions Pending · validation Not run.'));return}
23
+ const summary=el('div','','review-details-summary'),summaryText=el('div','','review-summary-text'),summaryHeading=el('div','','review-summary-heading');
24
+ const badgeLabel=scope==='history'&&w.state==='Rolled Back'?'Rolled back':scope==='history'&&w.supersededBy?'Superseded':w.state;
25
+ const badge=el('span',badgeLabel,'review-state-badge');badge.dataset.state=w.state;
26
+ summaryHeading.append(el('strong',scope==='history'?'Previous review':'Current review'),badge);
27
+ const accepted=w.entries.filter(e=>e.decision==='Accepted').length,files=[...new Set(w.entries.filter(e=>e.decision==='Accepted').map(e=>e.finding.path))];
28
+ summaryText.append(summaryHeading,el('p',accepted+' accepted '+(accepted===1?'change':'changes')+' · '+(files.length?files.map(path=>path.split('/').pop()).slice(0,2).join(', ')+(files.length>2?' +'+(files.length-2)+' files':''):(w.mode==='one-by-one'?'One by one':'Prepare all, then review'))));
29
+ summary.append(glyph(scope==='history'?'history':'document','review-summary-icon'),summaryText);body.append(summary);
30
+ if(scope==='history'){
31
+ const warning=el('div','','history-warning');
32
+ warning.append(glyph('warning','history-warn-icon'),document.createTextNode('\u00a0Historical results do not validate the current review.'));
33
+ body.append(warning);
34
+ }
35
+ if(tab==='Activity'){
36
+ const events=[{at:w.createdAt,label:'Review started',detail:w.mode==='one-by-one'?'One by one review':'Prepare all, then review',icon:'start',tone:'neutral'}];
37
+ if(w.resumedFrom)events.push({at:w.createdAt,label:'Fresh analysis resumed after rollback',detail:'No inherited decisions or validation',icon:'history',tone:'neutral'});
38
+ for(const e of w.entries)for(const h of e.history)events.push({at:h.at,label:h.decision,detail:e.finding.path+':'+e.finding.range.start.line+(h.notes?' · '+h.notes:''),icon:h.decision==='Accepted'?'check':h.decision==='Rejected'?'reject':'note',tone:h.decision==='Accepted'?'success':h.decision==='Rejected'?'error':'neutral'});
39
+ if(w.validation){const status=w.validationPresentation?.status||w.validation.state;events.push({at:w.validation.at,label:'Validation · '+status,detail:w.validationPresentation?.explanation||'Historical recorded results',icon:status==='Passed'?'check':status==='Limited validation'?'warning':status==='Failed'?'reject':'info',tone:status==='Passed'?'success':status==='Limited validation'?'warning':status==='Failed'?'error':'neutral'});}
40
+ for(const receipt of w.receipts||[])events.push({at:receipt.appliedAt||receipt.timestamp||'',label:'Applied to source',detail:receipt.path,icon:'layers',tone:'applied'});
41
+ if(w.state==='Rolled Back')events.push({at:w.rolledBackAt||'',label:'Rollback completed',detail:'Source restored. New review required.',icon:'rollback',tone:'warning'});
42
+ const list=el('ol','','review-activity');for(const event of events.sort((a,b)=>(a.at||'~').localeCompare(b.at||'~'))){const row=el('li'),icon=el('span','','activity-icon'),text=el('div','','activity-text');row.dataset.tone=event.tone;icon.append(glyph(event.icon));text.append(el('strong',event.label),el('p',event.detail));row.append(icon,text,stamp(event.at));list.append(row)}body.append(list);
43
+ if(w.receipts?.length)body.append(disclosure('Receipts and backups',JSON.stringify(w.receipts,null,2),'workflow-receipts'));
44
+ }else if(tab==='Validation'){
45
+ const presentation=w.validationPresentation,validation=el('div','','dialog-validation'),status=presentation?.status||w.validation?.state||'Not run';validation.dataset.status=status;
46
+ validation.append(el('h3','Technical validation: '+status));
47
+ // Limited validation amber banner
48
+ if(status==='Limited validation'){const banner=el('div','','validation-limited-banner');banner.append(glyph('warning','validation-warn-icon'),document.createTextNode('\u00a0Available checks passed · Limited validation'));validation.append(banner);}
49
+ if(presentation?.explanation)validation.append(el('p',presentation.explanation));
50
+ // Check table with distinguishable groups (Project, Scanner, Runtime)
51
+ const allChecks=presentation?.checks||w.validation?.checks||[];
52
+ const isScanner=c=>c.kind==='scanner'||c.name==='scanner';
53
+ const isRuntime=c=>c.kind==='runtime'||c.name.startsWith('runtime');
54
+ const isProject=c=>c.kind==='project'||(!c.kind&&!isScanner(c)&&!isRuntime(c));
55
+ const projectChecks=allChecks.filter(isProject);
56
+ const scannerChecks=allChecks.filter(isScanner);
57
+ const runtimeChecks=allChecks.filter(isRuntime);
58
+ const groups=[
59
+ {title:'Project checks',checks:projectChecks,isProject:true},
60
+ {title:'Scanner verification',checks:scannerChecks,isProject:false},
61
+ {title:'Runtime verification',checks:runtimeChecks,isProject:false}
62
+ ].filter(g=>g.checks.length>0);
63
+ if(groups.length){
64
+ const table=el('div','','validation-table');
65
+ const headRow=el('div','','validation-head-row');headRow.append(el('span','Check'),el('span','Result'),el('span','Scope'));table.append(headRow);
66
+ for(const group of groups){
67
+ const groupRow=el('div','','validation-group-row');groupRow.append(el('span',group.title,'validation-group-title'));table.append(groupRow);
68
+ for(const check of group.checks){
69
+ const row=el('div','','validation-row '+(group.isProject?'validation-check':'validation-extra-check'));
70
+ row.dataset.kind=check.kind||(group.isProject?'project':'runtime');
71
+ row.dataset.check=check.name;
72
+ row.dataset.status=check.state;
73
+ const stateClass=check.state==='Passed'?'badge-pass':['Failed','Error','Unavailable'].includes(check.state)?'badge-fail':check.state==='Not configured'?'badge-nc':'badge-neutral';
74
+ const resultCell=el('span','','check-result');
75
+ const resultBadge=el('span',check.state,'result-badge '+stateClass);resultCell.append(resultBadge);
76
+ const nameSpan=el('span','','check-name');nameSpan.append(el('strong',check.name));
77
+ row.append(nameSpan,resultCell,el('span',check.scope||'—','check-scope'));
78
+ if(['Failed','Unavailable','Error'].includes(check.state)&&check.detail){
79
+ const err=el('div',check.detail,'check-error-detail');row.append(err);
80
+ }
81
+ table.append(row);
82
+ }
83
+ }
84
+ validation.append(table);
85
+ }
86
+ // Coverage notice
87
+ const coverage=el('aside','','change-coverage');coverage.append(el('strong','Change coverage: '+(presentation?.coverage||'Unknown')),el('p',presentation?.coverageDetail||'No matching source/candidate/test-run coverage evidence. Execution coverage does not prove RTL visual correctness.'));validation.append(coverage);
88
+ // Commands and logs disclosure
89
+ const logLines=allChecks.map(c=>(c.name||'')+(c.command?'\n$ '+c.command:'')+(c.detail?'\n'+c.detail:'')).filter(Boolean).join('\n\n');
90
+ validation.append(disclosure('Commands and logs',logLines||'No execution output recorded.','validation-logs'));
91
+ if(w.applyEligibility)validation.append(el('p','Apply policy: '+w.applyEligibility.reason,'validation-policy'));
92
+ body.append(validation);
93
+ }else if(tab==='Changes'){
94
+ const inventory=el('div','','workflow-inventory');inventory.append(el('p','Change inventory · '+w.entries.filter(e=>e.patch).length+' supported / '+w.entries.length+' findings'));
95
+ for(const file of w.files){const block=el('details');block.append(el('summary',file.path));for(const e of w.entries.filter(e=>e.finding.path===file.path)){const entry=el('section','','change-entry');entry.append(el('h4',e.finding.path+':'+e.finding.range.start.line+':'+e.finding.range.start.column),el('p',e.decision+' · '+(e.applied?(e.decision==='Accepted'?'In accepted review set':'In review preview only · Pending approval'):'Not in review preview')),el('p',e.reason),el('pre',e.patch?'- '+e.finding.original+'\n+ '+e.patch.replacement:'Unchanged: no supported fix'));block.append(entry)}block.append(disclosure('Exact candidate file diff',file.diff,'workflow-file-diff'));inventory.append(block)}body.append(inventory);
96
+ }else{
97
+ if(scope==='history')body.append(el('p','Current analysis '+(snapshot.current?.inputDigest||d.inputDigest)+' · Not validated by this historical review. Historical analysis '+w.inputDigest+' · '+w.state+'. Historical Before preview unavailable: no immutable application runtime was retained. Current source is shown in the preview; decisions, validation, receipts and backups remain historical.','historical-context'));
98
+ const fields=el('dl','','technical-fields');for(const [label,value] of [['Review',w.id],['Lifecycle',w.state],['Project root',w.root],['Candidate session',w.session?.id],['Resumed from',w.resumedFrom],['Superseded by',w.supersededBy],['Analysis hash',w.inputDigest],['Policy hash',w.policyDigest],['Validation recorded',w.validation?time(w.validation.at):'Not run']])field(fields,label,value);body.append(fields);
99
+ body.append(disclosure('Review identities and hashes',JSON.stringify({id:w.id,resumedFrom:w.resumedFrom,root:w.root,inputDigest:w.inputDigest,policyDigest:w.policyDigest,previewConfigDigest:w.previewConfigDigest,session:w.session,files:w.files.map(f=>({path:f.path,originalSha256:f.originalSha256,candidateSha256:f.candidateSha256})),validation:w.validation?{signature:w.validation.signature,hashes:w.validation.hashes}:null},null,2)));
100
+ body.append(disclosure('Receipts and backups',JSON.stringify(w.receipts||[],null,2),'workflow-receipts'));
101
+ }
102
+ }
103
+ function open(button,current,history){
104
+ if(dialog)close();opener=button;snapshot={current,history};scope='current';tab='Activity';historyId=current?.resumedFrom||null;
105
+ dialog=document.createElement('dialog');dialog.className='review-details-dialog';dialog.setAttribute('aria-labelledby','review-details-title');
106
+ // Header: icon + title/subtitle, × at right
107
+ const header=el('header'),titleBlock=el('div','','review-details-title-block'),heading=el('h2','');heading.prepend(glyph('document'));const titleText=document.createElement('span');titleText.textContent='Session details';heading.append(titleText);titleBlock.append(heading,el('p','','review-header-summary'));heading.id='review-details-title';const x=el('button');x.append(glyph('close'));x.setAttribute('aria-label','Close session details');x.type='button';x.onclick=close;header.append(titleBlock,x);
108
+ // Segmented control
109
+ const scopes=el('div','','review-details-scopes');scopes.setAttribute('role','group');scopes.setAttribute('aria-label','Review period');for(const [value,label] of [['current','Current review'],['history','History']]){const b=el('button',label);b.type='button';b.dataset.scope=value;b.onclick=()=>{scope=value;render()};scopes.append(b)}
110
+ // History picker
111
+ const picker=document.createElement('select');picker.className='review-history-select';picker.setAttribute('aria-label','Historical review');picker.onchange=()=>{historyId=picker.value;render()};
112
+ // Tabs
113
+ const tabs=el('div','','review-details-tabs');tabs.setAttribute('role','tablist');tabs.setAttribute('aria-label','Session details sections');for(const [index,label] of labels.entries()){const b=el('button');b.type='button';b.setAttribute('aria-label',label);b.dataset.tab=label;const icon=glyph(icons[index]);b.append(icon,document.createTextNode('\u00a0'+label));b.id='review-tab-'+label.toLowerCase();b.setAttribute('role','tab');b.setAttribute('aria-controls','review-details-panel');b.onclick=()=>{tab=label;render()};b.onkeydown=event=>{if(!['ArrowLeft','ArrowRight','Home','End'].includes(event.key))return;event.preventDefault();tab=event.key==='Home'?labels[0]:event.key==='End'?labels[3]:labels[(labels.indexOf(tab)+(event.key==='ArrowRight'?1:3))%4];render();tabs.querySelector('[aria-selected=true]').focus()};tabs.append(b)}
114
+ // Body + Footer
115
+ const body=el('div','','review-details-body');body.id='review-details-panel';body.setAttribute('role','tabpanel');body.tabIndex=0;
116
+ const footer=el('footer','','review-details-footer');
117
+ const changesButton=el('button','View changes');changesButton.type='button';changesButton.className='review-btn-secondary';
118
+ changesButton.onclick=()=>{tab='Changes';render();tabs.querySelector('[aria-selected=true]').focus();};
119
+ const closeButton=el('button','Close');closeButton.type='button';closeButton.className='review-btn-primary';closeButton.onclick=close;
120
+ footer.append(changesButton,closeButton);
121
+ dialog.append(header,scopes,picker,tabs,body,footer);document.body.append(dialog);
122
+ dialog.addEventListener('cancel',event=>{event.preventDefault();close()});
123
+ dialog.addEventListener('keydown',event=>{if(event.key!=='Tab')return;const nodes=[...dialog.querySelectorAll('button,select,[tabindex="0"],summary')].filter(n=>!n.disabled&&n.getClientRects().length&&!n.closest('[hidden]'));if(event.shiftKey&&document.activeElement===nodes[0]){event.preventDefault();nodes.at(-1).focus()}else if(!event.shiftKey&&document.activeElement===nodes.at(-1)){event.preventDefault();nodes[0].focus()}});
124
+ render();dialog.showModal();x.focus();
125
+ }
126
+ const style=el('style');style.textContent='\n'+
127
+ /* Dialog shell */
128
+ '.review-details-dialog{box-sizing:border-box;width:min(720px,calc(100vw - 32px));max-width:720px;height:fit-content;max-height:min(640px,calc(100dvh - 36px));padding:20px 22px 16px;border:1px solid #587da9;border-radius:13px;background:linear-gradient(135deg,#112038,#0b182a);color:#e7eefb;font:13px/1.45 Inter,system-ui,sans-serif;overflow:hidden;box-shadow:0 20px 70px #0007}\n'+
129
+ '.review-details-dialog[open]{display:flex;flex-direction:column;gap:14px}.review-details-dialog::backdrop{background:#020916b8}.review-icon{display:inline-block;width:19px;height:19px;flex:none;vertical-align:middle}\n'+
130
+ /* Header */
131
+ '.review-details-dialog header{display:flex;align-items:flex-start;justify-content:space-between;gap:10px;flex:none}.review-details-title-block{min-width:0;flex:1}.review-details-dialog h2{display:flex;align-items:center;gap:10px;margin:0;font-size:20px;line-height:1.3;font-weight:700}.review-details-dialog h2 .review-icon{width:24px;height:24px;color:#c18df1;flex:none}.review-header-summary{margin:4px 0 0 34px;color:#acbfd8;font-size:12px}\n'+
132
+ '.review-details-dialog button{padding:7px 14px;border:1px solid #496488;border-radius:7px;background:transparent;color:#dce7f7;font:600 12px Inter,system-ui;cursor:pointer}.review-details-dialog header>button{border-color:transparent;padding:4px;min-width:30px;min-height:30px;flex:none}.review-details-dialog button:hover{background:#21334e}.review-details-dialog :focus-visible{outline:2px solid #d5b2ff;outline-offset:2px}\n'+
133
+ /* Segmented control */
134
+ '.review-details-scopes{display:flex;gap:2px;padding:2px;border:1px solid #617a9e;border-radius:9px;flex-shrink:0;align-self:stretch}.review-details-scopes button{flex:1;border:1px solid transparent;border-radius:7px;padding:7px 12px;font-size:12px;transition:background .15s,border-color .15s}.review-details-scopes [aria-pressed=true]{background:linear-gradient(160deg,#8548ce,#5726a0);border-color:#b98af3;color:#fff;box-shadow:inset 0 1px 2px #ffffff20}.review-details-scopes [aria-pressed=false]{color:#b0c4df}\n'+
135
+ /* Tabs — underline style */
136
+ '.review-details-tabs{display:flex;flex:none;border-bottom:1px solid #364d6c;gap:0}.review-details-tabs button{display:flex;justify-content:center;align-items:center;gap:6px;flex:1;border:0;border-bottom:2px solid transparent;border-radius:0;padding:8px 4px 10px;color:#bbcadf;white-space:nowrap;font:600 12px Inter,system-ui;background:transparent;transition:border-color .15s,color .15s;margin-bottom:-1px}.review-details-tabs button:hover{color:#dce7f7;background:#23334b44}.review-details-tabs [aria-selected=true]{border-bottom-color:#9b6dff;color:#f3eaff}.review-details-tabs .review-icon{width:16px;height:16px}\n'+
137
+ /* Body */
138
+ '.review-details-body{overflow:auto;overscroll-behavior:contain;min-height:0;padding:0 2px;scrollbar-gutter:stable;max-height:calc(100dvh - 280px)}.review-details-body h3{font-size:14px;margin:0 0 8px}.review-details-body h4{font-size:12px;margin:10px 0 5px}.review-details-body p{margin:5px 0;color:#b3c3d9;overflow-wrap:anywhere}\n'+
139
+ /* Summary card */
140
+ '.review-details-summary{display:flex;align-items:center;gap:14px;padding:12px 16px;margin:0 0 10px;border:1px solid #3d5a7f;border-radius:9px;background:linear-gradient(120deg,#172a43,#132238)}.review-summary-icon{width:27px;height:27px;color:#c18df1;flex:none}.review-summary-text{min-width:0;flex:1}.review-summary-heading{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.review-summary-heading strong{font-size:15px}.review-details-summary p{margin:3px 0 0;font-size:12px}\n'+
141
+ /* State badge */
142
+ '.review-state-badge{border:1px solid #8c6abe;border-radius:20px;padding:1px 9px;color:#dec8ff;font-size:11px;white-space:nowrap}.review-state-badge[data-state="Rolled Back"]{border-color:#e7ac37;background:#65451055;color:#ffd16a}.review-state-badge[data-state=Applied]{border-color:#8c6abe;background:#53327d55}\n'+
143
+ /* Footer */
144
+ '.review-details-footer{display:flex;flex:none;justify-content:flex-end;align-items:center;gap:10px;border-top:1px solid #364d6c;padding-top:12px}.review-btn-secondary{min-width:106px;border:1px solid #496488;background:transparent;color:#dce7f7}.review-btn-secondary:hover{background:#1e3252}.review-btn-primary{min-width:82px;background:linear-gradient(160deg,#8548ce,#5726a0);color:#fff;border-color:#b487eb}.review-btn-primary:hover{background:linear-gradient(160deg,#9458de,#6236b0)}\n'+
145
+ /* Pre / details */
146
+ '.review-details-body pre{white-space:pre-wrap;overflow-wrap:anywhere;font-size:11px;max-height:240px;overflow:auto;padding:10px;background:#0a1729;border-radius:6px}.review-details-body details{margin:8px 0;border:1px solid #334c6b;border-radius:7px;padding:8px 10px}.review-details-body summary{cursor:pointer;list-style:none;font-size:12px;color:#c0d4ee}.review-details-body summary::marker,.review-details-body summary::-webkit-details-marker{display:none}.review-details-body details>summary::before{content:"▸ ";font-size:10px;color:#7a9cbf}.review-details-body details[open]>summary::before{content:"▾ "}\n'+
147
+ /* History warning — amber */
148
+ '.history-warning{display:flex;align-items:center;gap:8px;padding:9px 13px;margin:0 0 12px;background:#3d2b0a;border:1px solid #c4963d;border-radius:8px;color:#ffd166;font-size:12px}.history-warn-icon{flex:none;color:#f5c148}\n'+
149
+ /* Activity timeline */
150
+ '.review-activity{list-style:none;padding:2px 8px 0;margin:0}.review-activity li{position:relative;display:grid;grid-template-columns:30px minmax(0,1fr) auto;column-gap:13px;padding:8px 0 16px;isolation:isolate}.review-activity li:not(:last-child):before{content:"";position:absolute;left:14px;top:30px;bottom:-7px;border-left:1px solid #526a8b;z-index:-1}.activity-icon{box-sizing:border-box;display:grid;place-items:center;width:30px;height:30px;border:1px solid #8268ac;border-radius:50%;color:#d0a9f3;background:#25304b;flex:none}.activity-icon .review-icon{width:16px;height:16px}.activity-text{min-width:0}.activity-text strong{font-size:13px}.review-activity .activity-text p{margin:2px 0 0;font-size:12px;line-height:1.45}.review-activity time{padding-top:2px;color:#a9bbd3;font-size:11px;white-space:nowrap;cursor:help}.review-activity [data-tone=success] .activity-icon{border-color:#57d99c;color:#c0f9da;background:#1c5945}.review-activity [data-tone=error] .activity-icon{border-color:#e37d8f;color:#ffb5bf;background:#562a3d}.review-activity [data-tone=warning] .activity-icon{border-color:#e0ad41;color:#ffda80;background:#624910}.review-activity [data-tone=applied] .activity-icon{border-color:#b391e8;color:#dec4ff;background:#3f2b65}\n'+
151
+ /* Validation table — compact rows */
152
+ '.dialog-validation{display:flex;flex-direction:column;gap:4px}.validation-limited-banner{display:flex;align-items:center;gap:8px;padding:9px 13px;background:#3d2b0a;border:1px solid #c4963d;border-radius:8px;color:#ffd166;font-size:13px;font-weight:600;margin-bottom:4px}.validation-warn-icon{flex:none;color:#f5c148}\n'+
153
+ '.validation-table{border:1px solid #2d4668;border-radius:8px;overflow:hidden;margin:6px 0}.validation-head-row{display:grid;grid-template-columns:minmax(120px,2fr) minmax(90px,1fr) minmax(0,2fr);gap:8px;padding:6px 10px;background:#1b304a;font-weight:700;font-size:11px;color:#8fa5c4;text-transform:uppercase;letter-spacing:.04em}\n'+
154
+ '.validation-group-row{display:flex;align-items:center;padding:5px 10px;background:#14243b;border-top:1px solid #233b5c;font-size:10px;font-weight:700;color:#91abcb;text-transform:uppercase;letter-spacing:.04em}.validation-group-row:first-of-type{border-top:none}\n'+
155
+ '.validation-row{display:grid;grid-template-columns:minmax(120px,2fr) minmax(90px,1fr) minmax(0,2fr);gap:8px;align-items:center;padding:7px 10px;border-top:1px solid #1e3151;font-size:12px}\n'+
156
+ '.check-name{overflow-wrap:anywhere;color:#dce7f7}.check-scope{overflow-wrap:anywhere;color:#8fa5c4;font-size:11px}.check-result{display:flex;align-items:center}\n'+
157
+ '.check-error-detail{grid-column:1/-1;padding:5px 8px;margin-top:2px;background:#441a2755;border:1px solid #8e3146;border-radius:5px;color:#ff9fae;font-size:11px;line-height:1.4;white-space:pre-wrap;word-break:break-word}\n'+
158
+ '.result-badge{display:inline-block;padding:2px 8px;border-radius:12px;font-size:11px;font-weight:600;white-space:nowrap}.badge-pass{background:#1c5945;color:#5ee0a7;border:1px solid #57d99c}.badge-fail{background:#562a3d;color:#ff8193;border:1px solid #e37d8f}.badge-nc{background:#2a3a4f;color:#8fa5c4;border:1px solid #4b6384}.badge-neutral{background:#2a3348;color:#b3c3d9;border:1px solid #4a5f7a}\n'+
159
+ /* Change coverage */
160
+ '.change-coverage{padding:9px 12px;background:#1a2d44;border:1px solid #2d4668;border-radius:7px;margin:8px 0}.change-coverage strong{font-size:12px;color:#c8d9f0}.change-coverage p{font-size:11px;margin:3px 0 0}\n'+
161
+ '.validation-logs{margin:6px 0}.validation-policy{font-size:11px;color:#8fa5c4;margin:6px 0;padding:6px 10px;background:#1a2d44;border-radius:6px}\n'+
162
+ /* Technical fields */
163
+ '.technical-fields dd button{margin-left:8px;padding:2px 6px;font-size:10px}.technical-fields{display:grid;grid-template-columns:130px minmax(0,1fr);gap:8px}.technical-fields dt{color:#8fa7c6}.technical-fields dd{margin:0;overflow-wrap:anywhere}.historical-context{font-size:11px;color:#8fa5c4;padding:8px 10px;background:#1a2d44;border-radius:6px;margin-bottom:8px}\n'+
164
+ /* History select */
165
+ '.review-history-select{width:100%;min-width:0;flex:none;background:#172a43;color:#e7eefb;border:1px solid #496488;padding:7px;border-radius:6px;font:12px Inter,system-ui}.review-history-select[hidden]{display:none}\n'+
166
+ /* Workflow helpers */
167
+ '.workflow-notes summary{cursor:pointer;color:#cdb7ff}.workflow-notes textarea{margin-top:7px}.workflow-controls>button,.workflow-notes button{min-height:32px;margin:6px 6px 2px 0;padding:6px 12px;border:1px solid #6d7e9a;border-radius:7px;background:#142944;color:#e7eefb;font:600 11px Inter,system-ui;cursor:pointer}.workflow-controls button:disabled{opacity:.52}.workflow-summary,.workflow-decision{margin:5px 0}.workflow-owned .source-context-status{font-size:10px;color:#aebed3}\n'+
168
+ /* Narrow layout */
169
+ '@media(max-width:480px){.review-details-dialog{width:100%;max-width:100%;border-radius:0;border-left:0;border-right:0;padding:14px 12px 12px;max-height:100dvh}}\n'+
170
+ '@media(max-width:520px){.review-details-dialog[open]{gap:10px}.review-details-dialog h2{font-size:17px}.review-details-tabs button{font-size:11px;gap:4px;padding:7px 2px 10px}.review-details-tabs .review-icon{width:14px;height:14px}.review-details-summary{padding:10px;gap:9px}.review-summary-heading strong{font-size:14px}.review-activity{padding:0 2px}.review-activity li{grid-template-columns:28px minmax(0,1fr);column-gap:10px;padding-bottom:12px}.review-activity time{grid-column:2;padding-top:3px}.review-activity li:not(:last-child):before{left:14px;bottom:-3px}.technical-fields{grid-template-columns:1fr}.technical-fields dd{margin-bottom:8px}.validation-head-row,.validation-row{grid-template-columns:minmax(70px,1fr) minmax(80px,1fr) minmax(0,1.2fr);gap:5px;font-size:11px}.review-details-body{max-height:calc(100dvh - 240px)}}\n';
171
+ document.head.append(style);
172
+ function update(current,history){if(dialog){snapshot={current,history};render()}}
173
+ return{open,close,update};
174
+ })();
175
+ `;
@@ -0,0 +1,151 @@
1
+ import { reviewDetailsClientSource } from './dashboard-review-details.js';
2
+ /** Uses the approved dashboard cards and the existing embedded route renderer. */
3
+ export const workflowClientSource = String.raw `
4
+ const workflowStyle=el('style');workflowStyle.textContent='.workflow-owned .apply-advanced,.workflow-owned .reviewer-context{display:none!important}.workflow-controls{font-size:11px;grid-column:1/-1}body:has(.review-session-toolbar){overflow-x:clip;overflow-y:visible}.workspace:has(.review-session-toolbar){overflow:clip!important}.review-session-toolbar{position:sticky;top:0;z-index:30;display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:6px 8px;margin:0 8px 6px;background:#13243a;border:1px solid #496488;border-radius:9px;box-shadow:0 5px 14px #0004}.session-identity{display:flex;align-items:center;gap:10px;flex:1;min-width:140px}.session-identity strong{font-size:12px}.session-identity span{font-size:10px;color:#adc0d8}.review-session-toolbar button,.session-overflow>button{font:600 11px Inter,system-ui;color:#e7eefb;background:#1b304c;border:1px solid #526d91;border-radius:6px;padding:6px 8px;cursor:pointer}.review-session-toolbar button:disabled{opacity:.5;cursor:default}.review-session-toolbar .session-primary{background:#6330af;border-color:#ac80ee}.session-validation{font-size:11px;color:#b8c6d9}.session-validation[data-status=Passed]{color:#5de0a6}.session-validation[data-status=Failed]{color:#ff8193}.session-validation[data-status="Limited validation"]{color:#ffd166}.session-policy{flex-basis:100%;font-size:10px;color:#b8c6d9;margin:0;max-height:70px;overflow:auto}.session-overflow{position:relative;flex:none}.session-overflow>button{list-style:none;white-space:nowrap}.session-overflow>button::-webkit-details-marker{display:none}.session-overflow>button:after{content:"⌄";margin-left:8px;color:#bdabdc}.session-overflow>button[aria-expanded=true]{border-color:#b58be9;background:#302449}.session-menu{position:fixed;inset:auto;box-sizing:border-box;width:238px;max-width:calc(100vw - 20px);margin:0;padding:6px;border:1px solid #657da2;border-radius:9px;background:#14243a;color:#e7eefb;box-shadow:0 12px 32px #0009;overflow:auto}.session-menu:popover-open{display:flex;flex-direction:column;gap:3px;height:auto;min-height:0;align-items:stretch}.session-menu button{flex:none}.session-menu small{display:block;margin-top:3px;font-weight:400;color:#bac6d7}.session-menu button{display:block;width:100%;text-align:left;white-space:normal;border:1px solid transparent;background:transparent;padding:9px 10px;margin:0;font-size:12px}.session-menu button:hover:not(:disabled),.session-menu button:focus-visible{background:#2b3b57;border-color:#a17cd5}.session-menu button:disabled{opacity:.45}.semantic-review{margin-top:6px;border-top:1px solid #304563;font-size:11px}.semantic-review>summary{padding:6px 0 1px;color:#d3bef2;cursor:pointer}.semantic-review p{margin:6px 0 0;color:#b8c9df;line-height:1.6}.semantic-review[hidden]{display:none}.review-session-toolbar :focus-visible{outline:2px solid #d5b2ff;outline-offset:2px}.workflow-controls textarea{box-sizing:border-box;width:100%;min-height:96px;padding:10px;resize:vertical;white-space:pre-wrap;overflow-x:hidden;overflow-wrap:anywhere;color:#e7eefb;background:#102039;border:1px solid #385579;border-radius:6px}.workflow-controls pre{max-height:260px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere}.workflow-controls .actions{flex-wrap:wrap}.workflow-validation{max-height:160px;overflow:auto}.workflow-controls details{margin-top:8px}.workflow-controls summary{cursor:pointer;color:#cdb7ff}';document.head.append(workflowStyle);
5
+ ${reviewDetailsClientSource}
6
+ const reviewWorkflow=(()=>{
7
+ let workflow=null,history=null,busy=false,busyLabel='',error='',scope=[],reloading=false,overflowOpen=false;
8
+ let overflowUI=null;const noteDrafts=new Map(),noteFeedback=new Map();
9
+ function positionOverflow(){
10
+ if(!overflowUI?.menu.open||!overflowUI.panel.isConnected)return;
11
+ const {toggle,panel}=overflowUI,anchor=toggle.getBoundingClientRect(),gap=7,edge=10;
12
+ panel.style.maxHeight=Math.max(80,innerHeight-edge*2)+'px';
13
+ const box=panel.getBoundingClientRect(),below=innerHeight-anchor.bottom-gap-edge,above=anchor.top-gap-edge;
14
+ panel.style.left=Math.max(edge,Math.min(anchor.right-box.width,innerWidth-box.width-edge))+'px';
15
+ panel.style.top=Math.max(edge,below>=box.height||below>=above?Math.min(anchor.bottom+gap,innerHeight-box.height-edge):anchor.top-gap-box.height)+'px';
16
+ }
17
+ function setOverflow(open,focus=false){
18
+ if(!overflowUI)return;const {menu,toggle,panel}=overflowUI;overflowOpen=open;menu.open=open;toggle.setAttribute('aria-expanded',String(open));
19
+ if(open){if(!panel.matches(':popover-open'))panel.showPopover();positionOverflow();if(focus)([...panel.querySelectorAll('button')].filter(b=>!b.disabled)[0]||toggle).focus({preventScroll:true});}
20
+ else{if(panel.matches(':popover-open'))panel.hidePopover();if(focus)toggle.focus({preventScroll:true});}
21
+ }
22
+ document.addEventListener('pointerdown',event=>{if(overflowUI?.menu.open&&!overflowUI.menu.contains(event.target))setOverflow(false);});
23
+ document.addEventListener('keydown',event=>{if(event.key==='Escape'&&overflowUI?.menu.open){event.preventDefault();event.stopPropagation();setOverflow(false,true);}});
24
+ document.addEventListener('focusin',event=>{if(overflowUI?.menu.open&&!overflowUI.menu.contains(event.target))setOverflow(false);});
25
+ addEventListener('resize',positionOverflow);document.addEventListener('scroll',positionOverflow,true);
26
+ const endpoint='/review/workflows';
27
+ const api=async(path,body)=>{let response;try{response=await fetch(previewOrigin+path,body===undefined?undefined:{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)})}catch{throw Error('COMPANION_UNAVAILABLE')}const result=await response.json();if(!response.ok)throw Error(result.error||'WORKFLOW_REQUEST_FAILED');return result};
28
+ const state=(message,explanation)=>{
29
+ const card=document.querySelector('.code-diff-card');if(!card)return;let node=card.querySelector('.analysis-status');if(!node){node=el('p','','analysis-status');node.setAttribute('role','status');card.append(node)}if(node.textContent!==message)node.textContent=message;
30
+ const body=document.querySelector('.details-card .more-details-body')||document.querySelector('.details-card');let caveat=body?.querySelector('.semantic-review');if(body&&!caveat&&explanation){caveat=el('p','','semantic-review');body.append(caveat)}
31
+ if(caveat&&explanation!==undefined){caveat.hidden=!explanation;if(caveat.textContent!==explanation)caveat.textContent=explanation;}
32
+
33
+ };
34
+ function reloadTransition(next){const anchor=s.finding?{path:s.finding.path,ruleId:s.finding.ruleId,line:s.finding.line,column:s.finding.column}:null,key='rtl-source-selection:'+next.id;if(next.state==='Applied'&&anchor)sessionStorage.setItem(key,JSON.stringify(anchor));let selection=anchor;if(next.state==='Rolled Back'){try{selection=JSON.parse(sessionStorage.getItem(key))||anchor}catch{}}reloading=true;embeddedReview.select(null);sessionStorage.setItem('rtl-source-transition',JSON.stringify({workflowId:next.id,mode:next.mode,state:next.state,selection}));location.reload();}
35
+ async function operate(operation,label='Loading review'){if(busy||reloading)return;busy=true;busyLabel=label;error='';render();try{const result=await operation();if(result?.workflow){const changed=workflow&&workflow.state!==result.workflow.state;if(workflow&&workflow.id!==result.workflow.id)history=(await api(endpoint+'?history=1')).workflows.filter(w=>w.id!==result.workflow.id);workflow=result.workflow;if(changed&&['Applied','Rolled Back'].includes(workflow.state)){reloadTransition(workflow);return}}}catch(e){error=e.message;if(workflow?.id){try{const current=await api(endpoint+'/'+workflow.id);if(current.workflow){const changed=workflow.state!==current.workflow.state;workflow=current.workflow;if(changed&&['Applied','Rolled Back'].includes(workflow.state))reloadTransition(workflow)}}catch{}}}finally{busy=false;if(!reloading)render()}}
36
+ const action=(name,fn,disabled=false)=>{const b=el('button',name);b.disabled=busy||disabled;b.onclick=()=>{const menu=b.closest('.session-overflow');if(menu){setOverflow(false,true);}operate(fn,name)};return b};
37
+ const change=(f,kind,notes)=>api(endpoint+'/'+workflow.id+'/change',{findingId:f.id,action:kind,notes:notes||''});
38
+ const rollback=()=>{if(!window.confirm('Rollback this workflow? Later user edits will block rollback.'))return;return api(endpoint+'/'+workflow.id+'/rollback',{confirmation:'ROLLBACK_CONFIRMED'})};
39
+
40
+ const previewAttempts=new Map();let previewFlight=null;
41
+ const previewKey=(f,c)=>[workflow?.id,d.inputDigest,d.policyDigest,f.id,c?.application,c?.routeId,workflow?.session?.runtime?.status||'not-started',workflow?.entries.filter(e=>e.applied).map(e=>e.finding.id).join(',')].join('|');
42
+ const paintPreview=(f,state,reason='')=>embeddedReview.preparation(f,{state,reason,busy:busy||!!previewFlight});
43
+ function retryPreview(f){if(busy||previewFlight||s.finding?.id!==f.id)return;previewAttempts.delete(previewKey(f,embeddedReview.capability(f)));embeddedReview.refresh(f);}
44
+ async function automaticPreview(){
45
+ const f=s.finding;if(!f||!workflow||sourceContextError||reloading)return;
46
+ const e=workflow.entries.find(e=>e.finding.id===f.id),c=embeddedReview.capability(f);
47
+ if(workflow.state!=='Reviewing'||!e?.patch||['Rejected','Deferred','Flagged'].includes(e.decision)){paintPreview(f,'unsupported',workflow.state!=='Reviewing'?'Historical review; current candidate preparation is unavailable.':!e?.patch?e?.reason||'Finding outside the current review scope.':e.decision+' decision; automatic preparation will not restore this patch.');return;}
48
+ const key=previewKey(f,c),attempt=previewAttempts.get(key),runtimeCurrent=workflow.session?.runtime?.status==='healthy';
49
+ if(c?.resolving){paintPreview(f,'waiting','Resolving the current isolated preview context…');return;}
50
+ if(attempt?.state==='failed'){paintPreview(f,'failed',attempt.reason);return;}
51
+ if(!c?.verified&&!(e.applied&&runtimeCurrent&&c?.candidateAvailable&&c?.bindingVerified)){paintPreview(f,c?.blocked?'unsupported':c?.failed?'failed':'waiting',c?.reason||'Verifying the original source, route and rendered target…');return;}
52
+ if(e.applied&&runtimeCurrent&&c.candidateReady){paintPreview(f,'ready');return;}
53
+ if(e.applied&&runtimeCurrent&&c.candidateAvailable){
54
+ if(c.candidateFailed){const failed={state:'failed',reason:c.candidateReason||'Candidate source/target verification failed.'};previewAttempts.set(key,failed);paintPreview(f,'failed',failed.reason);}
55
+ else paintPreview(f,'preparing','Checking the isolated candidate source and rendered target…');
56
+ return;
57
+ }
58
+ if(attempt?.state==='prepared'&&runtimeCurrent){const failed={state:'failed',reason:c.candidateReason||'Prepared candidate runtime is unavailable. Retry preview.'};previewAttempts.set(key,failed);paintPreview(f,'failed',failed.reason);return;}
59
+ if(busy||previewFlight){paintPreview(f,'preparing','Waiting for the current isolated preview preparation…');return;}
60
+ const owner=workflow.id,operation={state:'preparing',reason:''};previewAttempts.set(key,operation);previewFlight=operation;busy=true;render();paintPreview(f,'preparing','Preparing the isolated candidate and starting its verified application route…');
61
+ try{
62
+ const result=await api(endpoint+'/'+owner+'/prepare-preview',{findingId:f.id,application:c.application,routeId:c.routeId,inputDigest:d.inputDigest,policyDigest:d.policyDigest});
63
+ if(workflow?.id===owner){workflow=result.workflow;operation.state='prepared';previewAttempts.set(previewKey(f,c),operation);}
64
+ }catch(failure){
65
+ operation.state='failed';operation.reason=failure.message;
66
+ // A runtime failure may follow a successful isolated patch. Reconcile that exact workflow before retry.
67
+ if(workflow?.id===owner){try{const current=await api(endpoint+'/'+owner);if(workflow?.id===owner)workflow=current.workflow;}catch{}previewAttempts.set(previewKey(f,c),operation);}
68
+ }finally{previewFlight=null;busy=false;if(!reloading)render();}
69
+ }
70
+ window.addEventListener('rtl-context-preview-updated',event=>{if(workflow?.id===event.detail.workflowId&&s.finding?.id===event.detail.findingId)automaticPreview();});
71
+ function sessionToolbar(){
72
+ const source=document.querySelector('.code-scroll'),code=source?.parentElement,pane=code?.parentElement,meta=code?.querySelector('.meta');if(!pane||!code||!source)return;if(meta)pane.insertBefore(meta,code);const previous=pane.querySelector('.review-session-toolbar'),menuOpen=previous?.querySelector('.session-overflow')?.open??overflowOpen,focused=previous?.contains(document.activeElement)?document.activeElement:null,focusKey=focused?.dataset.sessionAction,focusLabel=focused?.textContent,focusPrimary=focused?.classList.contains('session-primary');previous?.remove();
73
+ const bar=el('section','','review-session-toolbar');bar.setAttribute('aria-label','Review session');bar.setAttribute('aria-busy',String(busy));pane.insertBefore(bar,code);
74
+ const historical=sourceContextError||workflow?.state!=='Reviewing',current=historical?null:workflow,selected=workflow?.entries.filter(e=>e.decision==='Accepted').length||0;
75
+ const identity=el('div','','session-identity');identity.title=workflow?(workflow.mode==='one-by-one'?'One by one review':'Prepare all, then review'):'Review session';identity.append(el('strong','Current review · '+(workflow?.mode==='apply-first'?'Prepare all, then review':'One by one')),el('span',selected+' accepted'+(historical?' · '+(workflow?.state||'Loading'):''),'workflow-summary'));bar.append(identity);
76
+ const status=current?.validationPresentation?.status||'Not run',summary=el('span','Validation: '+status,'workflow-validation session-validation');summary.dataset.status=status;summary.title=current?.validationPresentation?.explanation||'Historical validation cannot validate this review.';bar.append(summary);
77
+ const detailButton=el('button','Session details');detailButton.dataset.reviewDetails='true';detailButton.onclick=()=>reviewDetails.open(detailButton,current,historical?[workflow,...(Array.isArray(history)?history:history?[history]:[])].filter(Boolean):history);bar.append(detailButton);
78
+ const eligible=!sourceContextError&&workflow?.applyEligibility?.eligible;
79
+ const applyLabel=selected===1?'Apply 1 accepted change to source':'Apply '+selected+' accepted changes to source';
80
+ const validateLabel='Validate changes';
81
+ const primary=eligible?action(applyLabel,()=>{if(!window.confirm('Apply only explicitly accepted, validated changes to the original source? Recoverable backups will be retained.'))return;return api(endpoint+'/'+workflow.id+'/apply',{confirmation:'APPLY_CONFIRMED'})}):action(validateLabel,()=>api(endpoint+'/'+workflow.id+'/validate',{}),!!historical||!selected);
82
+ primary.className='session-primary';if(busy)primary.textContent=previewFlight?'Preparing preview…':busyLabel.startsWith('Validate')?'Validating changes…':busyLabel.startsWith('Apply')?(selected===1?'Applying accepted change…':'Applying accepted changes…'):busyLabel+'…';bar.append(primary);
83
+ const menu=el('div','','session-overflow'),toggle=el('button','Review actions'),panel=el('div','','session-menu');toggle.setAttribute('aria-label','Review actions');toggle.setAttribute('aria-haspopup','menu');toggle.setAttribute('aria-controls','review-session-menu');toggle.dataset.sessionAction='overflow';panel.id='review-session-menu';panel.setAttribute('popover','manual');panel.setAttribute('role','menu');panel.setAttribute('aria-label','Review actions');menu.append(toggle,panel);bar.append(menu);overflowUI={menu,toggle,panel};
84
+ const rollbackButton=action('Rollback applied changes',rollback,!['Applied','Applying'].includes(workflow?.state)||!workflow?.receipts?.length),restartButton=action('Start new review',()=>api(endpoint,{inputDigest:d.inputDigest,policyDigest:d.policyDigest,mode:workflow.mode,scope:workflow.scope,restart:true}),!workflow||!!sourceContextError||workflow.state==='Applying');
85
+ rollbackButton.setAttribute('aria-label','Rollback applied changes');if(!['Applied','Applying'].includes(workflow?.state)||!workflow?.receipts?.length)rollbackButton.append(el('small','Available after Apply'));
86
+ for(const [key,button] of [['rollback',rollbackButton],['restart',restartButton]]){button.dataset.sessionAction=key;button.setAttribute('role','menuitem');panel.append(button);}
87
+ toggle.onclick=event=>{event.preventDefault();setOverflow(!menu.open);};
88
+ toggle.onkeydown=event=>{if(['ArrowDown','ArrowUp'].includes(event.key)){event.preventDefault();setOverflow(true,true);if(event.key==='ArrowUp')[...panel.querySelectorAll('button')].filter(b=>!b.disabled).at(-1)?.focus();}};
89
+ panel.onkeydown=event=>{const buttons=[...panel.querySelectorAll('button')].filter(b=>!b.disabled),index=buttons.indexOf(document.activeElement);if(['ArrowDown','ArrowUp','Home','End'].includes(event.key)){event.preventDefault();buttons[event.key==='Home'?0:event.key==='End'?buttons.length-1:(index+(event.key==='ArrowUp'?-1:1)+buttons.length)%buttons.length]?.focus();}if(event.key==='Tab'){setOverflow(false,true);}};
90
+ setOverflow(!!menuOpen);
91
+ if(error||sourceContextError){const warning=el('p',error||sourceContextError,'session-policy');warning.setAttribute('role','alert');bar.append(warning);}
92
+ primary.title=workflow?.applyEligibility?.reason||'Validate accepted changes before Apply.';
93
+ if(current?.validationPresentation?.status==='Failed'||current?.validationPresentation?.status==='Unavailable'){bar.append(el('p',workflow.applyEligibility?.reason||current.validationPresentation.explanation,'session-policy'));}
94
+ const focusTarget=focusPrimary?primary:[...bar.querySelectorAll('button,summary')].find(n=>focusKey?n.dataset.sessionAction===focusKey:n.textContent===focusLabel);if(focused)(focusTarget&&!focusTarget.disabled?focusTarget:toggle).focus({preventScroll:true});
95
+ }
96
+ function render(){
97
+ const f=s.finding;if(!localStorage.getItem('rtl-review-workflow'))return;if(!f){sessionToolbar();reviewDetails.update(workflow?.state==='Reviewing'?workflow:null,workflow?.state!=='Reviewing'?[workflow,...(history||[])].filter(Boolean):history);return;}
98
+ normalizeComponentReview();normalizeDecision();sessionToolbar();
99
+ const card=document.querySelector('.decision-card'),component=document.querySelector('.component-review');if(!card)return;
100
+ card.classList.add('workflow-owned');card.querySelectorAll('.workflow-controls').forEach(n=>n.remove());
101
+ const actions=card.querySelector('.decision-actions');if(!actions)return;actions.replaceChildren();
102
+ const controls=el('div','','workflow-controls');card.append(controls);
103
+ if(sourceContextError){state((workflow?.state==='Rolled Back'||pendingSourceTransition?.state==='Rolled Back'?'Rollback succeeded. Rescan failed: ':'Source context blocked: ')+sourceContextError+'. Displayed report is a stale snapshot; current analysis is unavailable.');document.querySelector('.after-card pre').textContent='Fresh suggestion unavailable until rescan succeeds.';controls.append(el('p','Source context blocked: '+sourceContextError,'source-context-status'),action('Retry rescan',()=>{sessionStorage.setItem('rtl-source-transition',JSON.stringify(pendingSourceTransition||{mode:workflow?.mode||localStorage.getItem('rtl-review-workflow')}));reloading=true;location.reload()}));if(workflow){}return;}
104
+ if(error){state('Blocked: '+error);controls.append(action('Retry connection',()=>restore(true)));}
105
+ if(!workflow){if(!error)state(busy?'Analyzing scan and codemod inventory…':'Start a review workflow to analyze this report.');return;}
106
+ const historical=workflow.state!=='Reviewing',e=historical?null:workflow.entries.find(e=>e.finding.id===f.id),locked=historical;
107
+ reviewDetails.update(historical?null:workflow,historical?[workflow,...(history||[])]:history);
108
+ const selected=workflow.entries.filter(e=>e.decision==='Accepted').length;
109
+
110
+ const feedbackKey='rtl-rollback-feedback:'+workflow.id;
111
+ if(workflow.resumedFrom&&!historical&&!workflow.validation&&workflow.entries.every(e=>e.decision==='Pending'&&!e.history.length)&&!sessionStorage.getItem(feedbackKey)){const feedback=el('p','Rollback succeeded · Automatic rescan complete · Fresh review ready. ','source-context-status');const dismiss=el('button','Dismiss');dismiss.setAttribute('aria-label','Dismiss rollback notification');dismiss.onclick=()=>{sessionStorage.setItem(feedbackKey,'dismissed');render()};feedback.append(dismiss);controls.append(feedback);}
112
+
113
+ if(historical){['Approve fix','Reject fix','Defer','Needs review'].forEach(label=>actions.append(action(label,()=>{},true)));controls.append(el('p',workflow.state==='Rolled Back'?'Source restored · Start a fresh review.':workflow.state==='Applying'?'Source apply incomplete · Use Rollback to recover. History: Session details.':'Source applied · Current source shown. History and recovery: Session details.','source-context-status'));document.querySelector('.after-card pre').textContent='Current source · No current candidate. '+((f.eligibilityBlockers||[]).join('; ')||'Review this finding separately.');}if(sourceContextError)controls.append(el('p','Source context blocked: '+sourceContextError,'source-context-status'));
114
+ if(e){
115
+ document.querySelector('.before-card pre').textContent=e.finding.original;
116
+ document.querySelector('.after-card pre').textContent=e.patch?e.patch.replacement:'No supported automatic fix. '+e.reason;
117
+ if(!error)state(e.applied?(e.decision==='Accepted'?'Accepted · In accepted review set':'Preview ready · Pending approval'):e.decision+' · Not in review preview',e.reason);
118
+ const noteKey=workflow.id+':'+f.id,draft=noteDrafts.get(noteKey),notes=el('textarea');notes.maxLength=4000;notes.setAttribute('aria-label','Review note');notes.value=draft?.value??e.notes;notes.disabled=busy;
119
+ const noteBox=el('details','','workflow-notes'),noteSummary=el('summary',e.notes?'Edit review note':'Add review note');noteBox.open=draft?.open||false;noteBox.append(noteSummary,notes);
120
+ notes.oninput=()=>{noteDrafts.set(noteKey,{value:notes.value,open:true});noteFeedback.delete(noteKey);feedback.textContent='Unsaved draft retained for this finding.'};
121
+ noteBox.ontoggle=()=>{const current=noteDrafts.get(noteKey);if(noteBox.isConnected)noteDrafts.set(noteKey,{value:current?.value??notes.value,open:noteBox.open})};
122
+ const feedback=el('p',noteFeedback.get(noteKey)|| (draft&&draft.value!==e.notes?'Unsaved draft retained for this finding.':''));feedback.setAttribute('role','status');
123
+ noteBox.append(action('Save note',async()=>{const result=await change(f,'notes',notes.value);noteDrafts.delete(noteKey);noteFeedback.set(noteKey,'Note saved.');return result;}));
124
+ const cancel=el('button','Cancel');cancel.disabled=busy;cancel.onclick=()=>{noteDrafts.delete(noteKey);noteFeedback.set(noteKey,'Unsaved edits discarded. Saved note retained.');render()};noteBox.append(cancel);controls.append(noteBox,feedback);
125
+ actions.append(action('Approve fix',()=>change(f,'Accepted',e.notes),locked||!e.patch||!e.applied));
126
+ actions.append(action('Reject fix',()=>change(f,'Rejected',e.notes),locked));
127
+ actions.append(action('Defer',()=>change(f,'Deferred',e.notes),locked));
128
+ actions.append(action('Needs review',()=>change(f,'Flagged',e.notes),locked));
129
+ [...actions.children].forEach((button,index)=>button.setAttribute('aria-pressed',String(['Accepted','Rejected','Deferred','Flagged'][index]===e.decision)));card.querySelector('.decision-heading span:last-child').textContent=e.decision;
130
+ embeddedReview.configure(f,{onRetryPreview:()=>retryPreview(f),...(e.patch?{patch:e.patch,onApply:()=>operate(async()=>{const result=await change(f,'apply');previewAttempts.clear();return result;})}:{}),workflow});
131
+ const previewButton=[...card.querySelectorAll('button')].find(b=>['Apply & Preview','Prepare candidate','Open candidate preview','Retry candidate preview'].includes(b.textContent));if(previewButton)previewButton.disabled=busy||locked;
132
+ }else{if(!error)state(historical?'Current source · No current candidate · Validation Not run. History: Session details.':'Finding outside selected workflow scope.');embeddedReview.configure(f,{workflow});}
133
+ const validation=el('p','Current review · '+(e?.decision||'Pending')+' · '+(e?.applied?(e.decision==='Accepted'?'Accepted for validation':'Review preview only'):'Not in review preview'),'current-review-status workflow-decision');controls.append(validation);
134
+ // These legacy one-patch operations remain available to API regressions; this workflow owns its distinct lifecycle.
135
+ card.querySelectorAll('.reviewer-context,.apply-advanced').forEach(n=>n.hidden=true);
136
+ }
137
+ async function restore(create=false,mode=localStorage.getItem('rtl-review-workflow')){
138
+ if(!mode)return;const result=await api(pendingSourceTransition?.workflowId?endpoint+'/'+pendingSourceTransition.workflowId:endpoint+'?'+new URLSearchParams({inputDigest:dashboardSnapshot.inputDigest,policyDigest:dashboardSnapshot.policyDigest,mode}));
139
+ if(result.workflow){workflow=result.workflow;history=(await api(endpoint+'?history=1')).workflows.filter(w=>w.id!==workflow.id);scope=workflow.scope;if(!sourceContextError&&workflow.state==='Rolled Back'){history=[workflow,...history.filter(w=>w.id!==workflow.id)];const next=await api(endpoint+'/'+workflow.id+'/resume',{});workflow=next.workflow;pendingSourceTransition=null;return next;}if(!sourceContextError)pendingSourceTransition=null;return result;}
140
+ if(create){const next=await api(endpoint,{inputDigest:d.inputDigest,policyDigest:d.policyDigest,mode,scope});workflow=next.workflow;return next;}
141
+ if(!sourceContextError)showWorkflowScreen();
142
+ }
143
+ // Companion health/recovery also rebuilds detail directly. Restore workflow and Before after every rebuild.
144
+ const workflowDetail=detail;detail=f=>{reviewDetails.close();embeddedReview.select(null);workflowDetail(f);render()};
145
+ window.addEventListener('rtl-review-workflow-entered',event=>{embeddedReview.select(null);workflow=null;history=null;scope=event.detail.scope;operate(()=>restore(true,event.detail.mode))});
146
+ window.addEventListener('rtl-context-runtime-request',event=>{if(workflow?.id===event.detail.workflowId)operate(()=>api(endpoint+'/'+workflow.id+'/runtime',{application:event.detail.application}))});
147
+ // Reload restores persisted state without initiating batch application again.
148
+ setTimeout(()=>{if(localStorage.getItem('rtl-review-workflow'))operate(()=>restore(false))},0);
149
+ return{render};
150
+ })();
151
+ `;
@@ -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
  }