agents-relay 2.0.242 → 2.0.244

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -127,6 +127,8 @@ Jobs separate durable lifecycle from derived runtime status. Durable lifecycle i
127
127
 
128
128
  The **Job Execution Lifecycle (JEL)** is Create → Plan → Execute → Final Review → Merge → Completed. All work/recovery Tasks must reach a terminal state (SUCCEEDED, FAILED, or CANCELLED) before Final Review is eligible; terminal failure is evidence for the reviewer, not automatic acceptance. The independent Final Reviewer records findings. A PASS goes to the merge gate; CHANGES_REQUIRED persists findings and starts a minimal Planner N+1 repair round, then another Final Review. No automatic Plan N+1 is created after successful work. Planner and Workers use the discovered `ponytail` Skill to avoid unnecessary tasks without omitting required verification. For operator discussion, call this lifecycle **JEL**.
129
129
 
130
+ The Dashboard Job detail includes a **View JEL chart** link. It opens a read-only Mermaid popup that shows each persisted Plan, execution round, Final Review (including CHANGES_REQUIRED → Plan N+1), merge stage, and completion status. Every node displays wall-clock elapsed time derived from persisted timestamps (including queued time); missing timing data is labeled **unknown**, not estimated. The JEL popup highlights failed attempts in red, repeated worker attempts (Retry) in purple, and Troubleshooter tasks in amber, as dashed read-only diagnostic branches off their Execute round. Historical failure is shown only when a persisted `recoveryForAttempt` record supports it. The chart never changes Job state. Shortcut-runner jobs display their direct execution path instead of fictitious planning, review, or merge stages.
131
+
130
132
  Lifecycle transition authority lives in the directly renderable canonical flowchart sources linked in [Workflow graph navigation](#workflow-graph-navigation). Git history owns prior graph versions; the working tree contains only the current graph set.
131
133
 
132
134
  The canonical Mermaid Graph Engine is the authoritative durable workflow decision path. Job/Task lifecycle transitions plus Review, Planner, Blocker/Unblock, and Troubleshooter orchestration branches are defined by the canonical workflow graphs and executed through the shared graph runtime. TypeScript supplies facts and primitive action/effect implementations; it must not duplicate those workflow branches as a second procedural state machine.
@@ -1,5 +1,6 @@
1
1
  import { dashboardStyles } from './dashboard-style.js';
2
2
  import { DEFAULT_DASHBOARD_JOB_STATUSES } from './dashboard-data.js';
3
+ import { jobJelDiagram } from './dashboard-jel.js';
3
4
  import { createRequire } from 'node:module';
4
5
  import { execFileSync } from 'node:child_process';
5
6
  import { fileURLToPath } from 'node:url';
@@ -36,7 +37,6 @@ ${dashboardStyles}
36
37
  <button id="usage-tab" type="button" role="tab" aria-selected="false" aria-controls="usage-view">Usage</button>
37
38
  <button id="rules-tab" type="button" role="tab" aria-selected="false" aria-controls="rules-view">Router Rules</button>
38
39
  <button id="qa-tab" type="button" role="tab" aria-selected="false" aria-controls="qa-view">Troubleshooter Q&A</button>
39
- <button id="shortcuts-tab" type="button" role="tab" aria-selected="false" aria-controls="shortcuts-view">Shortcuts</button>
40
40
  <button id="graphs-tab" type="button" role="tab" aria-selected="false" aria-controls="graphs-view">Workflow</button>
41
41
  </nav>
42
42
  </header>
@@ -47,7 +47,7 @@ ${dashboardStyles}
47
47
  </section>
48
48
  <div class="workspace" id="jobs-workspace">
49
49
  <section class="panel" aria-labelledby="workspace-heading">
50
- <div class="panel-head"><button id="mobile-jobs-back" class="icon-button mobile-only" type="button" aria-label="Back to Jobs" title="Back to Jobs"><svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M19 12H5m7-7-7 7 7 7"/></svg></button><h2 id="workspace-heading"><span id="selected-job-title" class="subtle"></span></h2><div class="panel-actions"><button id="job-content-open" class="icon-button job-status-button" type="button" aria-label="Job details" title="Job details" data-state="IDLE"><svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="3" class="status-center"/></svg></button><button id="selected-job-refresh" class="icon-button" type="button" aria-label="Refresh selected job" title="Refresh selected job"><svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M20 11a8 8 0 1 0 1 5"/><path d="M20 4v7h-7"/></svg></button><span id="connection" class="status-pill neutral" aria-live="polite" aria-label="Connecting"></span></div></div>
50
+ <div class="panel-head"><button id="mobile-jobs-back" class="icon-button mobile-only" type="button" aria-label="Back to Jobs" title="Back to Jobs"><svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M19 12H5m7-7-7 7 7 7"/></svg></button><h2 id="workspace-heading"><span id="selected-job-title" class="subtle"></span></h2><div class="panel-actions"><button id="job-content-open" class="icon-button job-status-button" type="button" aria-label="Job details" title="Job details" data-state="IDLE"><svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="3" class="status-center"/></svg></button><button id="selected-job-refresh" class="icon-button" type="button" aria-label="Refresh selected job" title="Refresh selected job"><svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M20 11a8 8 0 1 0 1 5"/><path d="M20 4v7h-7"/></svg></button></div></div>
51
51
  <div class="panel-body">
52
52
  <div id="job-detail"><div class="skeleton"></div></div>
53
53
  <h3 class="section-title">Task hierarchy</h3>
@@ -83,6 +83,7 @@ ${dashboardStyles}
83
83
  </div>
84
84
  </div>
85
85
  </section>
86
+ <dialog id="jel-dialog" class="jel-dialog" aria-label="Job Execution Lifecycle chart"><div class="jel-dialog-header"><strong id="jel-dialog-title">Job Execution Lifecycle</strong><button type="button" id="jel-dialog-close" class="refresh-button" aria-label="Close JEL chart">Close</button></div><div class="jel-legend" aria-label="JEL diagnostics"><span class="jel-legend-failed">Failed</span><span class="jel-legend-retry">Retry</span><span class="jel-legend-troubleshooter">Troubleshooter</span></div><div id="jel-chart" class="jel-chart" aria-live="polite"></div><p id="jel-status" class="subtle">Graph derived from the selected job snapshot.</p></dialog>
86
87
  <dialog id="graph-dialog" class="graph-dialog" aria-label="Workflow graph viewer"><div class="graph-dialog-header"><strong id="graph-dialog-title">Workflow graph</strong><div class="graph-navigation"><button type="button" id="graph-zoom-out" class="refresh-button" aria-label="Zoom out">−</button><span id="graph-zoom-level" aria-live="polite">100%</span><button type="button" id="graph-zoom-in" class="refresh-button" aria-label="Zoom in">+</button><button type="button" id="graph-zoom-reset" class="refresh-button">Fit</button><button type="button" id="graph-dialog-close" class="refresh-button">Close</button></div></div><div id="graph-dialog-viewport" class="graph-dialog-viewport"></div></dialog>
87
88
  <section id="rules-view" role="tabpanel" aria-labelledby="rules-tab" hidden><div class="panel"><div class="panel-head"><h2>Router Rules</h2><span id="rules-meta" class="subtle"></span></div><div class="panel-body"><div class="router-rules-workspace"><div class="router-rules-pane rules-editor"><h3>Rules Editor</h3><p class="rules-help">Execution Router rules with an explicit <code>[choices]</code> section (provider: model [reasoning] entries, additive to profile defaults) and a <code>[routing-instruction]</code> section forwarded verbatim to Laya. Relay deduplicates, applies hard gates, and sends one merged choice list; impossible routes remain excluded by code and Codex stays the deterministic fallback.</p><textarea id="rules-text" class="rules-textarea" spellcheck="true" aria-label="Execution router rules" placeholder="[choices]\nopenai: sol medium, luna high\nzai: glm-5.3-flash high\n\n[routing-instruction]\nPrefer zai until its quota resets; otherwise use the openai default."></textarea><div class="rules-footer"><span id="rules-status" class="subtle" aria-live="polite"></span><div><button id="rules-test" class="rules-save" type="button">Test Router</button> <button id="rules-save" class="rules-save" type="button">Save rules</button></div></div></div><div class="router-rules-pane"><div class="panel-head"><h3>Audit Log</h3><button id="audit-refresh" type="button">Refresh</button></div><div id="audit-log" class="audit-log" aria-live="polite"><p class="empty">Loading latest routing decisions…</p></div></div></div><div class="router-test-panel"><h3>Test Router Result</h3><div id="router-test-results" class="router-test-results" aria-live="polite"><p class="empty">Select a Job and Task, then run Test Router.</p></div></div></div></div></section>
88
89
  <section id="qa-view" role="tabpanel" aria-labelledby="qa-tab" hidden>
@@ -93,18 +94,6 @@ ${dashboardStyles}
93
94
  <div class="rules-footer"><span id="qa-status" class="subtle" aria-live="polite"></span><div><button id="qa-reload" class="rules-save" type="button">Reload</button> <button id="qa-save" class="rules-save" type="button">Save Q&A</button></div></div>
94
95
  </div></div></div>
95
96
  </section>
96
- <section id="shortcuts-view" role="tabpanel" aria-labelledby="shortcuts-tab" hidden>
97
- <div class="panel">
98
- <div class="panel-head"><h2>ChatGPT Shortcuts</h2><span class="subtle">One per line · %1 = current repo/pr</span></div>
99
- <div class="panel-body">
100
- <div class="rules-editor">
101
- <p class="rules-help">Format: &lt;name&gt;: &lt;prompt&gt;. Use %1 where the current Job reference should appear.</p>
102
- <textarea id="shortcuts-text" class="rules-textarea" spellcheck="true" aria-label="ChatGPT shortcuts"></textarea>
103
- <div class="rules-footer"><span id="shortcuts-status" class="subtle" aria-live="polite"></span><button id="shortcuts-save" class="rules-save" type="button">Save shortcuts</button></div>
104
- </div>
105
- </div>
106
- </div>
107
- </section>
108
97
  </main>
109
98
  <script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>
110
99
  <script>
@@ -126,7 +115,6 @@ const jobsTab=document.querySelector('#jobs-tab');
126
115
  const usageTab=document.querySelector('#usage-tab');
127
116
  const graphsTab=document.querySelector('#graphs-tab');
128
117
  const rulesTab=document.querySelector('#rules-tab');
129
- const shortcutsTab=document.querySelector('#shortcuts-tab');
130
118
  const qaTab=document.querySelector('#qa-tab');
131
119
  const qaView=document.querySelector('#qa-view');
132
120
  const qaText=document.querySelector('#qa-text');
@@ -138,7 +126,6 @@ const jobsView=document.querySelector('#jobs-view');
138
126
  const usageView=document.querySelector('#usage-view');
139
127
  const graphsView=document.querySelector('#graphs-view');
140
128
  const rulesView=document.querySelector('#rules-view');
141
- const shortcutsView=document.querySelector('#shortcuts-view');
142
129
  const jobsWorkspace=document.querySelector('#jobs-workspace');
143
130
  const jobList=document.querySelector('#job-list');
144
131
  const jobsRefresh=document.querySelector('#jobs-refresh');
@@ -156,7 +143,6 @@ const taskDetailRoot=document.querySelector('#task-detail');
156
143
  const eventFeed=document.querySelector('#event-feed');
157
144
  const eventsAllTasks=document.querySelector('#events-all-tasks');
158
145
  const eventsScope=document.querySelector('#events-scope');
159
- const connection=document.querySelector('#connection');
160
146
  const selectedJobTitle=document.querySelector('#selected-job-title');
161
147
  const usageRoot=document.querySelector('#usage-root');
162
148
  const usageMeta=document.querySelector('#usage-meta');
@@ -170,9 +156,6 @@ const rulesText=document.querySelector('#rules-text');
170
156
  const rulesMeta=document.querySelector('#rules-meta');
171
157
  const rulesStatus=document.querySelector('#rules-status');
172
158
  const rulesSave=document.querySelector('#rules-save');const rulesTest=document.querySelector('#rules-test');const routerTestResults=document.querySelector('#router-test-results');const auditLog=document.querySelector('#audit-log');const auditRefresh=document.querySelector('#audit-refresh');
173
- const shortcutsText=document.querySelector('#shortcuts-text');
174
- const shortcutsStatus=document.querySelector('#shortcuts-status');
175
- const shortcutsSave=document.querySelector('#shortcuts-save');
176
159
  const rateLimitWarning=document.querySelector('#rate-limit-warning');
177
160
  const runtimeSummary=document.querySelector('#runtime-summary');
178
161
  let jobs=[];
@@ -232,18 +215,49 @@ function syncFilters(){
232
215
  if(jobSearch.value!==searchQuery)jobSearch.value=searchQuery;
233
216
  }
234
217
  function repoName(repository){if(typeof repository!=='string'||!repository)return 'unknown-repo';const parts=repository.split('/').filter(Boolean);return parts.at(-1)||repository;}
235
- const CHAT_SHORTCUTS_KEY='agents-relay:chatgpt-shortcuts';
236
- const DEFAULT_CHAT_SHORTCUTS=[
237
- 'Why blocked?: %1: why is it blocked? Find the root cause and move it forward.',
238
- 'Move forward: %1: check the current state and move it forward.',
239
- 'What is wrong?: %1: check the current state and explain what is wrong.'
240
- ].join('\\n');
241
- function chatShortcutText(){return localStorage.getItem(CHAT_SHORTCUTS_KEY)||DEFAULT_CHAT_SHORTCUTS;}
242
- function parseChatShortcuts(source){return String(source||'').split(/\\r?\\n/).map(line=>line.trim()).filter(Boolean).map(line=>{const split=line.indexOf(':');return split>0?{name:line.slice(0,split).trim(),prompt:line.slice(split+1).trim()}:null;}).filter(item=>item&&item.name&&item.prompt);}
243
- function jobChatRef(job){const pr=Number(job?.prNumber||0);return repoName(job?.repository)+"/job:"+value(job?.id)+(pr>0?"/pr#"+pr:"")+": "+value(job?.title||job?.id);}
244
- function chatShortcutUrl(prompt){return 'https://chatgpt.com/?prompt='+encodeURIComponent(prompt);}
245
- const CHAT_SHORTCUT_TARGET='agents-relay-shortcut';
246
- function chatShortcutField(job){const box=element('div','detail-group');box.append(element('p','detail-label',text('ChatGPT shortcut')));const select=document.createElement('select');select.className='job-filter job-chat-shortcut-select';select.setAttribute('aria-label','ChatGPT shortcut');select.append(new Option('',''));for(const item of parseChatShortcuts(chatShortcutText()))select.append(new Option(item.name,item.prompt));select.value='';select.addEventListener('change',()=>{if(!select.value)return;const prompt=select.value.replaceAll('%1',jobChatRef(job));window.open(chatShortcutUrl(prompt),CHAT_SHORTCUT_TARGET,'noopener');select.value='';});box.append(select);return box;}
218
+ const buildJelDiagram=${jobJelDiagram.toString()};
219
+ const jelDialog=document.querySelector('#jel-dialog');
220
+ const jelChart=document.querySelector('#jel-chart');
221
+ const jelStatus=document.querySelector('#jel-status');
222
+ let jelRenderSequence=0;
223
+ async function openJelChart(job){
224
+ const renderId=++jelRenderSequence;
225
+ jelDialog.querySelector('#jel-dialog-title').textContent='JEL · '+value(job.repository)+'/'+value(job.id);
226
+ jelChart.replaceChildren(element('p','subtle',text('Rendering job lifecycle…')));
227
+ jelStatus.textContent='Wall-clock elapsed from persisted timestamps (includes queued time); unknown means timing data is unavailable. Pending stages are not complete.';
228
+ jelDialog.showModal();
229
+ const source=buildJelDiagram(job);
230
+ try{
231
+ if(!window.mermaid)throw new Error('Mermaid unavailable');
232
+ if(!window.__relayMermaidReady){window.mermaid.initialize({startOnLoad:false,securityLevel:'strict',flowchart:{htmlLabels:false}});window.__relayMermaidReady=true;}
233
+ const rendered=await window.mermaid.render('relay-jel-'+renderId,source);
234
+ if(renderId!==jelRenderSequence||!jelDialog.open)return;
235
+ const svg=sanitizeGraphSvg(rendered.svg);
236
+ const definitions=graphNodeDefinitions(source);
237
+ for(const node of svg.querySelectorAll('g.node')){const entry=Array.from(definitions.entries()).find(([key])=>node.id.includes('-flowchart-'+key+'-'));if(entry)addNodeLabel(node,entry[1]);}
238
+ applyGraphPalette(svg);
239
+ applyJelHighlights(svg);
240
+ jelChart.replaceChildren(svg);
241
+ }catch(error){
242
+ if(renderId!==jelRenderSequence||!jelDialog.open)return;
243
+ jelChart.replaceChildren(element('pre','jel-source',text(source)));
244
+ jelStatus.textContent='Graph preview unavailable; showing the JEL source.';
245
+ }
246
+ }
247
+ jelDialog.querySelector('#jel-dialog-close').addEventListener('click',()=>jelDialog.close());
248
+ jelDialog.addEventListener('close',()=>{jelRenderSequence++;});
249
+ function applyJelHighlights(svg){
250
+ const palette={failed:['#fee2e2','#b91c1c','#991b1b'],retry:['#ede9fe','#7c3aed','#5b21b6'],troubleshooter:['#fef3c7','#b45309','#92400e']};
251
+ for(const node of svg.querySelectorAll('g.node')){
252
+ const kind=node.id.includes('-flowchart-failed_')?'failed':node.id.includes('-flowchart-retry_')?'retry':node.id.includes('-flowchart-troubleshooter_')?'troubleshooter':null;
253
+ if(!kind)continue;
254
+ node.classList.add('jel-'+kind);
255
+ const [fill,stroke,color]=palette[kind];
256
+ for(const shape of node.querySelectorAll('rect,polygon,circle,ellipse')){shape.setAttribute('fill',fill);shape.setAttribute('stroke',stroke);shape.setAttribute('stroke-width','2');}
257
+ for(const label of node.querySelectorAll('text,tspan'))label.setAttribute('fill',color);
258
+ }
259
+ }
260
+ function jelField(job){const box=element('div','detail-group');box.append(element('p','detail-label',text('Job Execution Lifecycle')));const line=element('p','detail-value');const link=element('a','',text('View JEL chart'));link.href='#jel-dialog';link.addEventListener('click',event=>{event.preventDefault();void openJelChart(job);});line.append(link);box.append(line);return box;}
247
261
  function shortcutProgress(job){if(job.executionMode!=='shortcut')return null;const root=(job.tasks||[]).find(task=>task.agentGraph);const checkpoint=root?.result?.data?.shortcut;const nodes=Object.keys(checkpoint?.nodes||{});const pending=Object.keys(checkpoint?.inFlight||{});const completed=nodes.filter(id=>checkpoint.nodes[id]?.status==='COMPLETED').length;const current=pending.length?pending.join(', '):'—';return completed+' completed · '+(pending.length?'running: '+current:'no active node');}
248
262
  function renderJobList(){jobList.replaceChildren();const visible=filteredJobs();if(!jobs.length){jobList.append(element('li','empty',text('No durable jobs discovered.')));return;}if(!visible.length){jobList.append(element('li','empty',text('No jobs match the selected filters.')));return;}for(const job of visible){const row=element('div','job-row'+(isCompleteUnmerged(job)?' complete-unmerged':''));row.setAttribute('aria-current',String(jobSelectionKey(job)===selectedJob));row.addEventListener('click',()=>selectJob(job));const content=element('div','job-content');const select=document.createElement('button');select.type='button';select.className='job-button';select.setAttribute('aria-current',String(jobSelectionKey(job)===selectedJob));select.title=job.title||job.id;select.addEventListener('click',event=>{event.stopPropagation();selectJob(job);});select.append(element('span','job-title',text(repoName(job.repository)+'/'+value(job.id)+(Number(job.prNumber||0)>0?'/PR#'+value(job.prNumber):'')+': '+value(job.title||job.id))));const states=element('span','job-status-line');states.append(element('span','badge '+value(job.state),text(value(job.state))));if(job.executionMode==='shortcut')states.append(element('span','badge shortcut-mode',text('SHORTCUT')));states.append(element('span','badge '+value(job.runtimeStatus||'IDLE'),text(value(job.runtimeStatus||'IDLE'))));if(job.publicationFailure)states.append(element('span','badge FAILED',text('PUBLISH FAILED: '+value(job.publicationFailure.stage))));else if(job.publication?.version)states.append(element('span','badge SUCCEEDED',text('v'+job.publication.version)));else if(Number(job.prNumber||0)>0&&job.githubState==='MERGED')states.append(element('span','badge MERGED',text('PR Merged')));else if(job.state==='COMPLETED'&&job.githubState==='CLOSED')states.append(element('span','badge SUCCEEDED',text('PR Archived')));if(job.state==='ACTIVE'&&job.reviewEnabled!==false)states.append(element('span','badge flag-review',text('REVIEW REQUIRED')));if(job.localMerge?.status==='failed')states.append(element('span','badge FAILED',text('MERGE FAILED: '+value(job.localMerge.error||'Unknown error'))));else if(isCompleteUnmerged(job))states.append(element('span','badge MERGE_PENDING',text('MERGE PENDING')));const primary=element('div','job-primary');primary.append(states);const lastLine=element('div','job-last-line');lastLine.append(element('span','subtle',text(compactCounts(counts(job.tasks)))),element('span','subtle',text(relativeTime(job.updatedAt))));content.append(select,primary,lastLine);row.append(content);jobList.append(element('li','',row));}}
249
263
  function taskTagDisplay(job,task){const display=task.tag&&job?.tag?.values?.[task.tag];return typeof display==='string'&&display?display:null;}
@@ -261,7 +275,7 @@ function taskStateField(task){const box=element('div','detail-group');box.append
261
275
  function manualOverrideField(task){const rows=Array.isArray(task.manualStateOverrides)?task.manualStateOverrides:[];const last=rows.at(-1);return field('Manual override',last?last.from+' → '+last.to+' · '+relativeTime(last.at):'—');}
262
276
  function iconSvg(name){const paths={close:'M5 5l14 14M19 5 5 19',detail:'M7 3h7l4 4v14H7zM14 3v5h4M10 12h5m-5 4h5'};const ns='http://www.w3.org/2000/svg';const svg=document.createElementNS(ns,'svg');svg.setAttribute('viewBox','0 0 24 24');svg.setAttribute('aria-hidden','true');const path=document.createElementNS(ns,'path');path.setAttribute('d',paths[name]);svg.append(path);return svg;}
263
277
  function showDetailsDialog(title,sections){const dialog=element('dialog','details-dialog');dialog.setAttribute('aria-label',title);const head=element('div','details-dialog-head');const name=element('strong','',text(title));const close=element('button','icon-button');close.append(iconSvg('close'));close.type='button';close.setAttribute('aria-label','Close details');close.title='Close details';close.addEventListener('click',()=>dialog.close());head.append(name,close);dialog.append(head);for(const [label,value] of sections){if(value===undefined||value===null||value==='')continue;dialog.append(element('h3','',text(label)));const content=element('pre');content.textContent=typeof value==='string'?value:JSON.stringify(value,null,2);dialog.append(content);}dialog.addEventListener('close',()=>dialog.remove());document.body.append(dialog);dialog.showModal();}function openJobDetails(){const job=selected();if(!job)return;showDetailsDialog('Job '+job.id+' · '+value(job.title),[['Objective',job.objective],['Description',job.description],['State',job.state],['Plans',job.plans?.map(p=>({id:p.id,status:p.status,assessment:p.assessment,error:p.error,generatedTaskIds:p.generatedTaskIds}))],['Review',job.review],['Outcome',job.result],['Publication',job.publication],['Failure',job.error]]);}function openTaskDetails(task){const result=task.result?.data??task.result;showDetailsDialog('Task '+task.id+' · '+value(task.title),[['Input / task objective',task.input],['State',task.state],['Conclusion',result],['Result summary',task.result?.summary],['Planner assessment',task.plannerResult?.assessment],['Resolution',task.resolution],['Resolution classification',task.resolutionClassification],['Failure',task.failureReason||task.error],['Dependencies',task.dependencies]]);}document.querySelector('#job-content-open').addEventListener('click',openJobDetails);function renderTaskDetail(task){taskDetailRoot.replaceChildren();if(!task){taskDetailRoot.append(element('p','empty',text('Select a task to inspect execution details.')));return;}const routing=task.routing||{};const groups=element('div','detail-groups');groups.append(field('Title',task.title||'—'),field('Task ID',task.id),field('Kind',task.kind||'work'),taskStateField(task),...(task.state==='FAILED'&&task.resolution?.state?[field('Resolution state',task.resolution.state),field('Resolution path',task.resolution.path||'—'),field('Resolution target',task.resolution.targetTaskId||'—')]:[]),manualOverrideField(task),field('Planning decision',task.planningDecisionId||'—'),field('Planning source',task.planningSource||'—'),field('Planning round',task.planningRound===undefined?'—':String(task.planningRound)),field('Project / agent',value(task.projectName)+' / '+value(task.agentName)),field('Parent task',task.parentTaskId||'root'),...(task.resolutionClassification?[field('Resolution classification',task.resolutionClassification.kind),field('Resolution target',task.resolutionClassification.targetTaskId),field('Resolution evidence',task.resolutionClassification.evidence),field('Resolution reason',task.resolutionClassification.reason)]:[]),field('Adapter',task.adapter),field('Provider / model',value(routing.provider)+' / '+value(routing.model)),field('Reasoning / profile',value(routing.reasoning||routing.profile)),field('Attempt',attemptBudget(task)),field('Dependencies',Array.isArray(task.dependencies)&&task.dependencies.length?task.dependencies.join(', '):'none'),taskCommentField(task),chatField(task));const job=selected();if(task.reviewHeadSha&&job)groups.append(commitField('HEAD commit',job,task.reviewHeadSha));const graph=agentGraphField(task);if(graph)groups.append(graph);if(task.plannerResult)groups.append(field('Objective status',task.plannerResult.objective_status),markdownField('Assessment',task.plannerResult.assessment));if(task.error)groups.append(field('Error',task.error));const result=task.result?.data??task.result;if(result){groups.append(field('Conclusion',result.verdict||result.outcome?.verdict||task.result?.summary||'Available'));}taskDetailRoot.append(groups);const details=element('button','icon-button');details.append(iconSvg('detail'));details.type='button';details.setAttribute('aria-label','Task details and conclusion');details.title='Task details and conclusion';details.addEventListener('click',()=>openTaskDetails(task));taskDetailRoot.append(details);}
264
- function reviewStatus(job){const review=job?.review;if(!review)return 'Not started';if(review.outcome==='approved'&&review.headSha===job.headSha)return 'MERGE READY · approved';const stale=Array.isArray(job?.tasks)&&job.tasks.some(task=>['reviewer','job-acceptance-reviewer'].includes(task.agentName)&&task.reviewHeadSha&&job.headSha&&task.reviewHeadSha!==job.headSha);if(stale)return 'STALE · awaiting review';return String(review.outcome||'pending').replace('_',' ').toUpperCase();}function renderSelectedJob(){jobDetail.replaceChildren();const job=selected();if(!job){selectedJobTitle.textContent='';jobContentButton.disabled=true;jobContentButton.dataset.state='IDLE';jobDetail.append(element('div','empty',text('No durable jobs discovered.')));buildTree([]);renderTaskDetail(null);return;}selectedJobTitle.textContent=value(job.title||job.id);jobContentButton.disabled=false;jobContentButton.dataset.state=JOB_STATES.includes(job.state)?job.state:'IDLE';jobContentButton.setAttribute('aria-label','Job details · '+value(job.state));jobContentButton.title='Job details · '+value(job.state);if(jobSelectionKey(job)!==selectedJob){selectedJob=jobSelectionKey(job);selectedTaskId=null;eventTaskId=null;clearEvents();rememberSelection();}const summary=element('div','job-summary');summary.append(field('PR state',job.executionMode==='shortcut'?'Not applicable':job.githubState||'UNKNOWN'),jobStateField(job),field('Runtime status',job.runtimeStatus||'IDLE'),field('Execution mode',job.executionMode==='shortcut'?'Shortcut Runner (external trigger)':'Managed'),...(job.executionMode==='shortcut'?[field('Shortcut nodes',shortcutProgress(job))]:[]),field('Review',job.executionMode==='shortcut'?'Not required':reviewStatus(job)),field('Creator thread',job.creatorThreadId||'—'),threadField('Implementation thread',job.implementationThreadId),threadField('Reviewer thread',job.reviewerThreadId),commitField('Review head SHA',job,job.review?.headSha||job.headSha||''),prField(job),field('Repository',job.repository||'—'),field('Last activity',relativeTime(job.updatedAt)),field('Task states',compactCounts(job.tasks)),chatShortcutField(job));jobDetail.append(summary);const selectedTask=(job.tasks||[]).find(task=>task.id===selectedTaskId)||null;if(selectedTaskId&&!selectedTask){selectedTaskId=null;eventTaskId=null;clearEvents();rememberSelection();}buildTree(job.tasks||[]);renderTaskDetail(selectedTask);renderEventScope();}function renderAll(){jobs.sort(compareJobs);syncFilters();renderJobList();renderSelectedJob();syncMobileJobsView();}
278
+ function reviewStatus(job){const review=job?.review;if(!review)return 'Not started';if(review.outcome==='approved'&&review.headSha===job.headSha)return 'MERGE READY · approved';const stale=Array.isArray(job?.tasks)&&job.tasks.some(task=>['reviewer','job-acceptance-reviewer'].includes(task.agentName)&&task.reviewHeadSha&&job.headSha&&task.reviewHeadSha!==job.headSha);if(stale)return 'STALE · awaiting review';return String(review.outcome||'pending').replace('_',' ').toUpperCase();}function renderSelectedJob(){jobDetail.replaceChildren();const job=selected();if(!job){selectedJobTitle.textContent='';jobContentButton.disabled=true;jobContentButton.dataset.state='IDLE';jobDetail.append(element('div','empty',text('No durable jobs discovered.')));buildTree([]);renderTaskDetail(null);return;}selectedJobTitle.textContent=value(job.title||job.id);jobContentButton.disabled=false;jobContentButton.dataset.state=JOB_STATES.includes(job.state)?job.state:'IDLE';jobContentButton.setAttribute('aria-label','Job details · '+value(job.state));jobContentButton.title='Job details · '+value(job.state);if(jobSelectionKey(job)!==selectedJob){selectedJob=jobSelectionKey(job);selectedTaskId=null;eventTaskId=null;clearEvents();rememberSelection();}const summary=element('div','job-summary');summary.append(field('PR state',job.executionMode==='shortcut'?'Not applicable':job.githubState||'UNKNOWN'),jobStateField(job),field('Runtime status',job.runtimeStatus||'IDLE'),field('Execution mode',job.executionMode==='shortcut'?'Shortcut Runner (external trigger)':'Managed'),...(job.executionMode==='shortcut'?[field('Shortcut nodes',shortcutProgress(job))]:[]),field('Review',job.executionMode==='shortcut'?'Not required':reviewStatus(job)),field('Creator thread',job.creatorThreadId||'—'),threadField('Implementation thread',job.implementationThreadId),threadField('Reviewer thread',job.reviewerThreadId),commitField('Review head SHA',job,job.review?.headSha||job.headSha||''),prField(job),field('Repository',job.repository||'—'),field('Last activity',relativeTime(job.updatedAt)),field('Task states',compactCounts(job.tasks)),jelField(job));jobDetail.append(summary);const selectedTask=(job.tasks||[]).find(task=>task.id===selectedTaskId)||null;if(selectedTaskId&&!selectedTask){selectedTaskId=null;eventTaskId=null;clearEvents();rememberSelection();}buildTree(job.tasks||[]);renderTaskDetail(selectedTask);renderEventScope();}function renderAll(){jobs.sort(compareJobs);syncFilters();renderJobList();renderSelectedJob();syncMobileJobsView();}
265
279
  function isCompleteUnmerged(job){return job.runtimeStatus==='MERGE_PENDING';}
266
280
  function compareJobs(a,b){const lifecycleGroup=job=>job.state==='COMPLETED'||job.state==='CANCELLED'?1:0;const timestamp=job=>{const updated=Date.parse(job.updatedAt||'');if(Number.isFinite(updated))return updated;const created=Date.parse(job.createdAt||'');return Number.isFinite(created)?created:0;};return lifecycleGroup(a)-lifecycleGroup(b)||timestamp(b)-timestamp(a)||String(a.repository||'').localeCompare(String(b.repository||''))||String(a.id||'').localeCompare(String(b.id||''));}
267
281
  async function loadJSON(url){const response=await fetch(url);if(!response.ok)throw new Error(response.status+' '+response.statusText);return response.json();}
@@ -279,7 +293,7 @@ async function refreshStatus(){try{renderRateLimitStatus(await loadJSON('/api/st
279
293
  function rememberJobFilters(){sessionStorage.setItem('agents-relay:repo-filter',selectedRepo);sessionStorage.setItem('agents-relay:status-filter',selectedStatus);sessionStorage.setItem('agents-relay:job-search',searchQuery);}
280
294
  function jobsQuery(force=false){const params=new URLSearchParams();if(searchQuery.trim())params.set('q',searchQuery.trim());if(selectedStatus)params.set('status',selectedStatus);if(selectedRepo)params.set('repo',selectedRepo);if(force)params.set('refresh','1');return params.toString();}
281
295
  let jobsRequestSequence=0;
282
- async function refresh(force=true){const requestSequence=++jobsRequestSequence;jobsRefresh.disabled=true;jobsFeedback.textContent='';try{const params=jobsQuery(force);const discovered=await loadJSON('/api/jobs'+(params?'?'+params:''));if(requestSequence!==jobsRequestSequence)return;const result=Array.isArray(discovered)?{jobs:discovered,repositories:[...new Set(discovered.map(job=>job.repository).filter(Boolean))].sort()}:discovered;jobs=dedupeJobs(Array.isArray(result.jobs)?result.jobs:[]).sort(compareJobs).slice(0,20);jobRepositories=result.repositories||[];void drawRuntimeSummary();jobs.sort(compareJobs);if(selectedJob&&!jobForSelection(selectedJob)){selectedJob=null;selectedTaskId=null;}if(!selectedJob){const match=location.hash.match(/^#\\/jobs\\/(.+)$/);const fromHash=match?decodeURIComponent(match[1]):null;const fromRoute=jobForSelection(fromHash);selectedJob=jobSelectionKey(fromRoute||jobs[0]);}rememberSelection();rememberJobFilters();renderAll();void loadEventHistory();jobsFeedback.textContent='';connection.textContent='';connection.setAttribute('aria-label','Live durable state connected');connection.className='status-pill ok';}catch(error){if(requestSequence!==jobsRequestSequence)return;jobsFeedback.textContent='Refresh failed: '+error.message;connection.textContent='';connection.setAttribute('aria-label','Durable state unavailable');connection.className='status-pill bad';jobList.replaceChildren(element('li','error-state',text('Could not load jobs: '+error.message)));}finally{if(requestSequence===jobsRequestSequence){jobsRefresh.disabled=false;syncFilters();}}}
296
+ async function refresh(force=true){const requestSequence=++jobsRequestSequence;jobsRefresh.disabled=true;jobsFeedback.textContent='';try{const params=jobsQuery(force);const discovered=await loadJSON('/api/jobs'+(params?'?'+params:''));if(requestSequence!==jobsRequestSequence)return;const result=Array.isArray(discovered)?{jobs:discovered,repositories:[...new Set(discovered.map(job=>job.repository).filter(Boolean))].sort()}:discovered;jobs=dedupeJobs(Array.isArray(result.jobs)?result.jobs:[]).sort(compareJobs).slice(0,20);jobRepositories=result.repositories||[];void drawRuntimeSummary();jobs.sort(compareJobs);if(selectedJob&&!jobForSelection(selectedJob)){selectedJob=null;selectedTaskId=null;}if(!selectedJob){const match=location.hash.match(/^#\\/jobs\\/(.+)$/);const fromHash=match?decodeURIComponent(match[1]):null;const fromRoute=jobForSelection(fromHash);selectedJob=jobSelectionKey(fromRoute||jobs[0]);}rememberSelection();rememberJobFilters();renderAll();void loadEventHistory();jobsFeedback.textContent='';}catch(error){if(requestSequence!==jobsRequestSequence)return;jobsFeedback.textContent='Refresh failed: '+error.message;jobList.replaceChildren(element('li','error-state',text('Could not load jobs: '+error.message)));}finally{if(requestSequence===jobsRequestSequence){jobsRefresh.disabled=false;syncFilters();}}}
283
297
  function renderEventScope(){const task=eventTaskId&&selected()?.tasks?.find(candidate=>candidate.id===eventTaskId);eventsAllTasks.disabled=!task;eventsAllTasks.setAttribute('aria-pressed',String(!task));eventsScope.textContent=task?'Task '+task.id+' · newest first · 60 max':'Job-wide · newest first · 60 max';}
284
298
  function eventLabel(type){return ({'task.process.launched':'Process launched','task.started':'Worker started','task.process.exited':'Sync process exited','task.process.async_exited':'Async process exited','task.completed':'Worker completed','task.failed':'Worker failed','task.blocked':'Worker blocked','review.started':'Review started','review.approved':'Review approved','review.changes_required':'Review changes required','review.blocked':'Review blocked'})[type]||type||'Event';}
285
299
  function eventSeverity(event,level){const type=String(event?.type||'').toLowerCase(),eventLevel=String(event?.level||level||'').toLowerCase(),outcome=String(event?.outcome||event?.status||'').toLowerCase();if(eventLevel==='error'||outcome==='failed'||type.endsWith('.failed')||type==='task.failed')return 'error';if(eventLevel==='warn'||outcome==='blocked'||type.endsWith('.blocked')||type==='task.blocked'||type==='review.blocked')return 'warn';return 'normal';}
@@ -332,11 +346,9 @@ async function drawAudit(){auditRefresh.disabled=true;try{renderAudit(await load
332
346
  async function drawRules(){rulesStatus.textContent='';try{const rules=await loadJSON('/api/execution-router-rules');rulesText.value=typeof rules.text==='string'?rules.text:'';rulesMeta.textContent=rules.hash&&rules.hash!=='none'?'Loaded · '+rules.hash.slice(0,12):'No custom rules saved';}catch(error){rulesMeta.textContent='Unavailable';rulesStatus.textContent='Could not load rules: '+error.message;}void drawAudit();}
333
347
  async function testRouter(){rulesTest.disabled=true;routerTestResults.replaceChildren(element('p','subtle',text('Calling router with current status…')));try{if(!selectedJob||!selectedTaskId)throw new Error('Select a Job and Task first');const response=await fetch('/api/router-test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({jobId:selected()?.id,taskId:selectedTaskId})});if(!response.ok)throw new Error(response.status+' '+await response.text());const result=await response.json();const routeSelection=result.selected||{};const payload={selected:routeSelection,proposed_fields:result.proposedFields||{},probabilities:result.probabilities||{},fallback:Boolean(result.fallback),effective_choices:result.effectiveChoices||[],routing_instruction:result.routingInstruction||'',merged_choices:result.mergedChoices||[],hard_gates:result.gates||[],laya_input:result.decisionInput||null};routerTestResults.replaceChildren(element('strong','',text((routeSelection.worker||'—')+' · '+(routeSelection.model||'—'))));routerTestResults.append(element('div','subtle',text('route: '+(routeSelection.route||'—'))),element('pre','',text(yamlDump(payload))));}catch(error){routerTestResults.replaceChildren(element('p','error-state',text('Router test failed: '+error.message)));}finally{rulesTest.disabled=false;}}
334
348
  async function saveRules(){rulesSave.disabled=true;rulesStatus.textContent='Saving…';try{const response=await fetch('/api/execution-router-rules',{method:'PUT',headers:{'content-type':'text/plain; charset=utf-8'},body:rulesText.value});if(!response.ok)throw new Error(response.status+' '+await response.text());const rules=await response.json();rulesMeta.textContent='Saved · '+rules.hash.slice(0,12);rulesStatus.textContent='Saved. New routing decisions will load these rules.';}catch(error){rulesStatus.textContent='Save failed: '+error.message;}finally{rulesSave.disabled=false;}}
335
- async function drawShortcuts(){shortcutsStatus.textContent='';shortcutsText.value=chatShortcutText();}
336
- function saveShortcuts(){const value=shortcutsText.value.trim();if(value)localStorage.setItem(CHAT_SHORTCUTS_KEY,value);else localStorage.removeItem(CHAT_SHORTCUTS_KEY);shortcutsText.value=chatShortcutText();shortcutsStatus.textContent='Saved.';}
337
349
  async function drawQa(){qaStatus.textContent='Loading…';try{const result=await loadJSON('/api/troubleshooter-qa');qaText.value=result.text;qaRevision=result.hash;qaStatus.textContent='Loaded';}catch(error){qaStatus.textContent='Load failed: '+error.message;}}
338
350
  async function saveQa(){qaSave.disabled=true;qaStatus.textContent='Saving…';try{const response=await fetch('/api/troubleshooter-qa',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify({text:qaText.value,hash:qaRevision})});if(!response.ok)throw new Error(response.status+' '+await response.text());const saved=await response.json();qaRevision=saved.hash;qaStatus.textContent='Saved to Markdown file';}catch(error){qaStatus.textContent='Save failed: '+error.message;}finally{qaSave.disabled=false;}}
339
- function showView(view){const isJobs=view==='jobs';const isUsage=view==='usage';const isGraphs=view==='graphs';const isRules=view==='rules';const isShortcuts=view==='shortcuts';const isQa=view==='qa';qaView.hidden=!isQa;qaTab.setAttribute('aria-selected',String(isQa));jobsView.hidden=!isJobs;jobsWorkspace.hidden=!isJobs;usageView.hidden=!isUsage;graphsView.hidden=!isGraphs;rulesView.hidden=!isRules;shortcutsView.hidden=!isShortcuts;jobsTab.setAttribute('aria-selected',String(isJobs));usageTab.setAttribute('aria-selected',String(isUsage));graphsTab.setAttribute('aria-selected',String(isGraphs));rulesTab.setAttribute('aria-selected',String(isRules));shortcutsTab.setAttribute('aria-selected',String(isShortcuts));if(isUsage)void drawUsage();else if(isGraphs)void drawGraphs();else if(isRules)void drawRules();else if(isQa)void drawQa();else if(!isJobs)void drawShortcuts();}
351
+ function showView(view){const isJobs=view==='jobs';const isUsage=view==='usage';const isGraphs=view==='graphs';const isRules=view==='rules';const isQa=view==='qa';qaView.hidden=!isQa;qaTab.setAttribute('aria-selected',String(isQa));jobsView.hidden=!isJobs;jobsWorkspace.hidden=!isJobs;usageView.hidden=!isUsage;graphsView.hidden=!isGraphs;rulesView.hidden=!isRules;jobsTab.setAttribute('aria-selected',String(isJobs));usageTab.setAttribute('aria-selected',String(isUsage));graphsTab.setAttribute('aria-selected',String(isGraphs));rulesTab.setAttribute('aria-selected',String(isRules));if(isUsage)void drawUsage();else if(isGraphs)void drawGraphs();else if(isRules)void drawRules();else if(isQa)void drawQa();}
340
352
  jobsTab.addEventListener('click',()=>{location.hash=selectedJob?'#/jobs/'+encodeURIComponent(selectedJob):'#/jobs';showView('jobs');});
341
353
  jobsRefresh.addEventListener('click',()=>void refresh(true));
342
354
  eventsAllTasks.addEventListener('click',()=>{eventTaskId=null;clearEvents();renderEventScope();void loadEventHistory();});
@@ -354,32 +366,28 @@ document.querySelector('#graph-entry').addEventListener('click',()=>navigateGrap
354
366
  const graphDialog=document.querySelector('#graph-dialog');const graphViewport=document.querySelector('#graph-dialog-viewport');let graphZoom=1;const graphCanvasHome=graphCanvas.parentNode;function setGraphZoom(value){graphZoom=Math.min(4,Math.max(.35,value));const svg=graphCanvas.querySelector('svg');if(svg){svg.style.width=(Number(svg.getAttribute('width'))||Math.max(900,svg.viewBox.baseVal.width))*graphZoom+'px';svg.style.maxWidth='none';}document.querySelector('#graph-zoom-level').textContent=Math.round(graphZoom*100)+'%';}document.querySelector('#graph-maximize').addEventListener('click',()=>{graphDialog.showModal();graphViewport.append(graphCanvas);document.querySelector('#graph-dialog-title').textContent=graphTitle.textContent;setGraphZoom(1);});function closeGraphViewer(){graphCanvasHome.insertBefore(graphCanvas,graphCanvasHome.querySelector('.graph-source-details'));setGraphZoom(1);}graphDialog.addEventListener('close',closeGraphViewer);document.querySelector('#graph-dialog-close').addEventListener('click',()=>graphDialog.close());document.querySelector('#graph-zoom-in').addEventListener('click',()=>setGraphZoom(graphZoom*1.25));document.querySelector('#graph-zoom-out').addEventListener('click',()=>setGraphZoom(graphZoom/1.25));document.querySelector('#graph-zoom-reset').addEventListener('click',()=>setGraphZoom(1));graphViewport.addEventListener('wheel',event=>{if(!event.ctrlKey&&!event.metaKey)return;event.preventDefault();setGraphZoom(graphZoom*(event.deltaY<0?1.15:1/1.15));},{passive:false});let drag=null;graphViewport.addEventListener('pointerdown',event=>{if(event.target.closest('.drillable'))return;drag={x:event.clientX,y:event.clientY,left:graphViewport.scrollLeft,top:graphViewport.scrollTop};graphViewport.setPointerCapture(event.pointerId);});graphViewport.addEventListener('pointermove',event=>{if(!drag)return;graphViewport.scrollLeft=drag.left-(event.clientX-drag.x);graphViewport.scrollTop=drag.top-(event.clientY-drag.y);});graphViewport.addEventListener('pointerup',()=>drag=null);graphViewport.addEventListener('pointercancel',()=>drag=null);
355
367
  document.querySelector('#graph-back').addEventListener('click',()=>history.back());
356
368
  document.querySelector('#graph-forward').addEventListener('click',()=>history.forward());
357
- window.addEventListener('popstate',()=>{if(graphFromHash()){renderGraphNavigation();showView('graphs');}else if(location.hash==='#/usage')showView('usage');else if(location.hash==='#/execution-router-rules')showView('rules');else if(location.hash==='#/shortcuts')showView('shortcuts');else if(location.hash==='#/troubleshooter-qa')showView('qa');else showView('jobs');});
358
- window.addEventListener('hashchange',()=>{if(graphFromHash()){renderGraphNavigation();showView('graphs');}else if(location.hash==='#/usage')showView('usage');else if(location.hash==='#/execution-router-rules')showView('rules');else if(location.hash==='#/shortcuts')showView('shortcuts');else if(location.hash==='#/troubleshooter-qa')showView('qa');else showView('jobs');});
369
+ window.addEventListener('popstate',()=>{if(graphFromHash()){renderGraphNavigation();showView('graphs');}else if(location.hash==='#/usage')showView('usage');else if(location.hash==='#/execution-router-rules')showView('rules');else if(location.hash==='#/troubleshooter-qa')showView('qa');else showView('jobs');});
370
+ window.addEventListener('hashchange',()=>{if(graphFromHash()){renderGraphNavigation();showView('graphs');}else if(location.hash==='#/usage')showView('usage');else if(location.hash==='#/execution-router-rules')showView('rules');else if(location.hash==='#/troubleshooter-qa')showView('qa');else showView('jobs');});
359
371
  rulesTab.addEventListener('click',()=>{location.hash='#/execution-router-rules';showView('rules');});
360
372
  qaTab.addEventListener('click',()=>{location.hash='#/troubleshooter-qa';showView('qa');});
361
373
  qaSave.addEventListener('click',()=>void saveQa());
362
374
  document.querySelector('#qa-reload').addEventListener('click',()=>{if(!qaText.value||confirm('Discard unsaved Q&A edits and reload?'))void drawQa();});
363
- shortcutsTab.addEventListener('click',()=>{location.hash='#/shortcuts';showView('shortcuts');});
364
375
  rulesSave.addEventListener('click',()=>void saveRules());
365
376
  rulesTest.addEventListener('click',()=>void testRouter());
366
377
  auditRefresh.addEventListener('click',()=>void drawAudit());
367
- shortcutsSave.addEventListener('click',saveShortcuts);
368
- window.addEventListener('keydown',event=>{if(event.key==='Tab'&&event.altKey){event.preventDefault();const views=['jobs','usage','graphs','rules','qa','shortcuts'];const current=location.hash==='#/usage'?'usage':graphFromHash()?'graphs':location.hash==='#/execution-router-rules'?'rules':location.hash==='#/shortcuts'?'shortcuts':location.hash==='#/troubleshooter-qa'?'qa':'jobs';const next=views[(views.indexOf(current)+1)%views.length];location.hash=next==='usage'?'#/usage':next==='graphs'?'#/graphs':next==='rules'?'#/execution-router-rules':next==='shortcuts'?'#/shortcuts':next==='qa'?'#/troubleshooter-qa':(selectedJob?'#/jobs/'+encodeURIComponent(selectedJob):'#/jobs');showView(next);}});
378
+ window.addEventListener('keydown',event=>{if(event.key==='Tab'&&event.altKey){event.preventDefault();const views=['jobs','usage','graphs','rules','qa'];const current=location.hash==='#/usage'?'usage':graphFromHash()?'graphs':location.hash==='#/execution-router-rules'?'rules':location.hash==='#/troubleshooter-qa'?'qa':'jobs';const next=views[(views.indexOf(current)+1)%views.length];location.hash=next==='usage'?'#/usage':next==='graphs'?'#/graphs':next==='rules'?'#/execution-router-rules':next==='qa'?'#/troubleshooter-qa':(selectedJob?'#/jobs/'+encodeURIComponent(selectedJob):'#/jobs');showView(next);}});
369
379
  function parseMessage(message){try{return JSON.parse(message.data);}catch{return null;}}
370
380
  function isFreshEnough(incoming,current){const a=Date.parse(incoming||''),b=Date.parse(current||'');return !Number.isFinite(b)||!Number.isFinite(a)||a>=b;}
371
381
  function applyStatePatch(patch){if(!patch?.jobId)return false;const job=jobs.find(candidate=>candidate.id===patch.jobId);if(!job)return false;if(patch.jobState&&isFreshEnough(patch.jobUpdatedAt,job.updatedAt)){job['state']=patch.jobState;if(patch.jobUpdatedAt)job.updatedAt=patch.jobUpdatedAt;}if(patch.taskId&&patch.taskState){const task=(job.tasks||[]).find(candidate=>candidate.id===patch.taskId);if(task&&isFreshEnough(patch.taskUpdatedAt,task.updatedAt)){task['state']=patch.taskState;if(patch.taskUpdatedAt)task.updatedAt=patch.taskUpdatedAt;}}return true;}
372
382
  async function refreshJobSnapshot(jobId){const known=jobs.find(job=>job.id===jobId);if(!known)return;try{const params=new URLSearchParams({id:known.id,repo:known.repository,pr:String(known.prNumber||0)});const latest=await loadJSON('/api/job?'+params);upsertFreshJob(latest);renderAll();}catch{/* The current stream and next manual refresh remain available. */}}
373
383
  function upsertFreshJob(incoming){if(!incoming)return;const index=jobs.findIndex(job=>jobSelectionKey(job)===jobSelectionKey(incoming));if(index<0){jobs.push(incoming);return;}if(isFreshEnough(incoming.updatedAt,jobs[index].updatedAt))jobs[index]={...incoming,prNumber:Number(incoming.prNumber||0)>0?incoming.prNumber:jobs[index].prNumber};}
374
384
  const stream=new EventSource('/events');
375
- stream.onopen=()=>{connection.textContent='';connection.setAttribute('aria-label','Event stream connected');connection.className='status-pill ok';};
376
- stream.onerror=()=>{connection.textContent='';connection.setAttribute('aria-label','Event stream reconnecting');connection.className='status-pill warn';};
377
385
  stream.onmessage=message=>{const payload=parseMessage(message);if(payload?.job){upsertFreshJob(payload.job);renderAll();void drawRuntimeSummary();}};
378
386
  stream.addEventListener('relay',message=>{const payload=parseMessage(message);if(payload?.job)upsertFreshJob(payload.job);else if(payload?.statePatch)applyStatePatch(payload.statePatch);if(payload?.statePatch)void refreshJobSnapshot(payload.statePatch.jobId);if(payload?.event)addEvent(payload.event);renderAll();void drawRuntimeSummary();});
379
- if(location.hash==='#/usage')showView('usage');else if(graphFromHash())showView('graphs');else if(location.hash==='#/execution-router-rules')showView('rules');else if(location.hash==='#/shortcuts')showView('shortcuts');else if(location.hash==='#/troubleshooter-qa')showView('qa');else showView('jobs');void refresh(false);
387
+ if(location.hash==='#/usage')showView('usage');else if(graphFromHash())showView('graphs');else if(location.hash==='#/execution-router-rules')showView('rules');else if(location.hash==='#/troubleshooter-qa')showView('qa');else showView('jobs');void refresh(false);
380
388
  setInterval(()=>{if(location.hash==='#/usage')void drawUsage();},30000);
381
389
  setInterval(()=>void refreshVersion(),30000);
382
- async function refreshSelected(){const job=selected();if(!job){await refresh();return;}selectedJobRefresh.disabled=true;try{const params=new URLSearchParams({id:job.id,repo:job.repository,pr:String(job.prNumber)});const updated=await loadJSON('/api/job?'+params.toString());const index=jobs.findIndex(candidate=>jobSelectionKey(candidate)===jobSelectionKey(job));if(index>=0)jobs[index]=updated;else jobs.push(updated);selectedJob=jobSelectionKey(updated);rememberSelection();renderAll();connection.textContent='';connection.setAttribute('aria-label','Live durable state connected');connection.className='status-pill ok';}catch(error){connection.textContent='';connection.setAttribute('aria-label','Durable state unavailable');connection.className='status-pill bad';}finally{selectedJobRefresh.disabled=false;}}
390
+ async function refreshSelected(){const job=selected();if(!job){await refresh();return;}selectedJobRefresh.disabled=true;try{const params=new URLSearchParams({id:job.id,repo:job.repository,pr:String(job.prNumber)});const updated=await loadJSON('/api/job?'+params.toString());const index=jobs.findIndex(candidate=>jobSelectionKey(candidate)===jobSelectionKey(job));if(index>=0)jobs[index]=updated;else jobs.push(updated);selectedJob=jobSelectionKey(updated);rememberSelection();renderAll();}catch(error){jobsFeedback.textContent='Selected job refresh failed: '+error.message;}finally{selectedJobRefresh.disabled=false;}}
383
391
  </script>
384
392
  </body>
385
393
  </html>`;
@@ -0,0 +1,142 @@
1
+ /** Keep this function self-contained: dashboard-html embeds its JS source in the browser. */
2
+ export function jobJelDiagram(job) {
3
+ const lines = ['flowchart LR'];
4
+ const safe = (value) => String(value ?? 'Unknown').replace(/[^A-Za-z0-9 _./-]/g, '').slice(0, 240);
5
+ const now = Date.now();
6
+ const instant = (value) => {
7
+ if (typeof value !== 'string' || !value)
8
+ return null;
9
+ const parsed = Date.parse(value);
10
+ return Number.isFinite(parsed) && parsed <= now ? parsed : null;
11
+ };
12
+ const elapsed = (start, end) => {
13
+ const from = instant(start);
14
+ const to = end === 'NOW' ? now : instant(end);
15
+ if (from === null || to === null || to < from)
16
+ return 'unknown';
17
+ const seconds = Math.floor((to - from) / 1000);
18
+ if (seconds < 60)
19
+ return seconds + 's';
20
+ const minutes = Math.floor(seconds / 60);
21
+ if (minutes < 60)
22
+ return minutes + 'm ' + seconds % 60 + 's';
23
+ const hours = Math.floor(minutes / 60);
24
+ if (hours < 24)
25
+ return hours + 'h ' + minutes % 60 + 'm';
26
+ return Math.floor(hours / 24) + 'd ' + hours % 24 + 'h';
27
+ };
28
+ const terminalTask = (task) => ['SUCCEEDED', 'FAILED', 'CANCELLED'].includes(task.state || '');
29
+ const workElapsed = (work) => {
30
+ const starts = work.map(task => instant(task.createdAt)).filter((time) => time !== null);
31
+ if (starts.length !== work.length || !starts.length)
32
+ return 'unknown';
33
+ const ends = work.map(task => instant(task.updatedAt)).filter((time) => time !== null);
34
+ return elapsed(new Date(Math.min(...starts)).toISOString(), work.every(terminalTask) && ends.length === work.length ? new Date(Math.max(...ends)).toISOString() : 'NOW');
35
+ };
36
+ const node = (id, label, time) => lines.push(' ' + id + '["' + safe(label + ' / elapsed ' + time) + '"]');
37
+ const edge = (from, to, reason = '') => lines.push(' ' + from + ' -->' + (reason ? '|' + safe(reason) + '|' : '') + ' ' + to);
38
+ const tasks = Array.isArray(job.tasks) ? job.tasks : [];
39
+ const isReviewer = (task) => task.agentName === 'job-acceptance-reviewer';
40
+ const isTroubleshooter = (task) => task.agentName === 'troubleshooter';
41
+ const state = (value, fallback) => typeof value === 'string' && value ? safe(value).toUpperCase() : fallback;
42
+ const workLabel = (work) => {
43
+ const succeeded = work.filter(task => task.state === 'SUCCEEDED').length;
44
+ const failed = work.filter(task => task.state === 'FAILED').length;
45
+ const active = work.filter(task => !['SUCCEEDED', 'FAILED', 'CANCELLED'].includes(task.state || '')).length;
46
+ return work.length + ' tasks / ' + succeeded + ' succeeded / ' + failed + ' failed / ' + active + ' active';
47
+ };
48
+ // These dashed observation branches are not workflow transitions: persisted
49
+ // Task facts are projected without inferring a new scheduling decision.
50
+ const diagnostics = (executionId, suffix, work, troubleshoot) => {
51
+ const failed = new Set();
52
+ const add = (kind, label, time) => {
53
+ const id = kind + '_' + suffix + '_' + String(lines.filter(line => line.startsWith(' ' + kind + '_' + suffix + '_')).length);
54
+ node(id, label, time);
55
+ lines.push(' ' + executionId + ' -.-> ' + id);
56
+ lines.push(' class ' + id + ' jel' + kind[0].toUpperCase() + kind.slice(1));
57
+ };
58
+ for (const task of work) {
59
+ if (task.state === 'FAILED') {
60
+ const key = (task.id || 'unknown') + ':' + String(task.attempt ?? '?');
61
+ failed.add(key);
62
+ add('failed', 'Failed ' + (task.id || 'unknown') + ' / attempt ' + (task.attempt || 'unknown'), elapsed(task.createdAt, task.updatedAt));
63
+ }
64
+ if (typeof task.attempt === 'number' && Number.isInteger(task.attempt) && task.attempt > 1) {
65
+ const history = Array.isArray(task.executionHistory) ? task.executionHistory : [];
66
+ const current = history.slice().reverse().find(record => record.attempt === task.attempt);
67
+ add('retry', 'Retry ' + (task.id || 'unknown') + ' / ' + (task.attempt - 1) + ' retries / attempt ' + task.attempt, elapsed(current?.startedAt, terminalTask(task) ? task.updatedAt : 'NOW'));
68
+ }
69
+ }
70
+ for (const task of troubleshoot) {
71
+ const parent = work.find(candidate => candidate.id === task.parentTaskId);
72
+ if (parent && Number.isInteger(task.recoveryForAttempt) && (task.recoveryForAttempt ?? 0) > 0) {
73
+ const key = (parent.id || 'unknown') + ':' + task.recoveryForAttempt;
74
+ if (!failed.has(key)) {
75
+ failed.add(key);
76
+ // Recovery-for-attempt is durable evidence of a failed attempt, but
77
+ // not of its terminal timestamp: display unknown, never fabricate.
78
+ add('failed', 'Failed ' + (parent.id || 'unknown') + ' / attempt ' + task.recoveryForAttempt, 'unknown');
79
+ }
80
+ }
81
+ add('troubleshooter', 'Troubleshooter ' + (task.id || 'unknown') + ' / ' + state(task.state, 'UNKNOWN'), workElapsed([task]));
82
+ }
83
+ };
84
+ const finish = () => {
85
+ // The browser applies the same palette *after* SVG sanitization; Mermaid
86
+ // styling alone is not trusted to survive the safe SVG renderer.
87
+ lines.push(' classDef jelFailed fill:#fee2e2,stroke:#b91c1c,color:#991b1b,stroke-width:2px');
88
+ lines.push(' classDef jelRetry fill:#ede9fe,stroke:#7c3aed,color:#5b21b6,stroke-width:2px');
89
+ lines.push(' classDef jelTroubleshooter fill:#fef3c7,stroke:#b45309,color:#92400e,stroke-width:2px');
90
+ return lines.join('\n');
91
+ };
92
+ const plans = Array.isArray(job.plans) ? job.plans : [];
93
+ const jobEnd = ['COMPLETED', 'CANCELLED'].includes(job.state || '') ? job.updatedAt : 'NOW';
94
+ const firstStart = plans[0]?.createdAt || (job.tasks || []).map(task => task.createdAt).filter(Boolean).sort()[0];
95
+ node('created', 'Create / recorded', elapsed(job.createdAt, firstStart || jobEnd));
96
+ if (job.executionMode === 'shortcut') {
97
+ const work = tasks.filter(task => !isReviewer(task) && !isTroubleshooter(task));
98
+ node('execute', 'Shortcut execute / ' + workLabel(work), workElapsed(work));
99
+ diagnostics('execute', 'shortcut', work, tasks.filter(isTroubleshooter));
100
+ node('finished', 'Job / ' + state(job.state, 'UNKNOWN'), elapsed(job.createdAt, jobEnd));
101
+ edge('created', 'execute');
102
+ edge('execute', 'finished');
103
+ return finish();
104
+ }
105
+ const rounds = plans.length ? plans : [{ id: '', round: 1, status: 'NOT STARTED', generatedTaskIds: [] }];
106
+ let previous = 'created';
107
+ for (let i = 0; i < rounds.length; i++) {
108
+ const plan = rounds[i];
109
+ const number = Number.isInteger(plan.round) && (plan.round ?? 0) > 0 ? plan.round : i + 1;
110
+ const suffix = String(i + 1);
111
+ const planId = 'plan_' + suffix;
112
+ const executeId = 'execute_' + suffix;
113
+ const reviewId = 'review_' + suffix;
114
+ const assigned = new Set(Array.isArray(plan.generatedTaskIds) ? plan.generatedTaskIds : []);
115
+ const work = (plans.length ? tasks.filter(task => !isReviewer(task) && !isTroubleshooter(task) && (task.planningDecisionId === plan.id || assigned.has(task.id || ''))) : tasks.filter(task => !isReviewer(task) && !isTroubleshooter(task)));
116
+ node(planId, 'Plan ' + number + ' / ' + state(plan.status, 'NOT STARTED'), elapsed(plan.createdAt, plan.status === 'PLANNING' ? 'NOW' : plan.updatedAt));
117
+ node(executeId, 'Execute ' + number + ' / ' + workLabel(work), workElapsed(work));
118
+ const workIds = new Set(work.map(task => task.id));
119
+ const troubleshoot = tasks.filter(task => isTroubleshooter(task) &&
120
+ (workIds.has(task.parentTaskId || '') || task.planningDecisionId === plan.id || !plans.length));
121
+ diagnostics(executeId, suffix, work, troubleshoot);
122
+ const nextPlan = plans[i + 1];
123
+ const review = job.reviewEnabled === false ? 'NOT REQUIRED' : nextPlan?.trigger?.source === 'review' ? 'CHANGES REQUIRED' : i === rounds.length - 1 ? state(job.review?.outcome, 'NOT STARTED') : 'NOT RECORDED';
124
+ // Review Tasks are not guaranteed to carry the Plan ID. Use their persisted
125
+ // timestamps within the current round, never guess a Review duration.
126
+ const reviewTasks = tasks.filter(task => isReviewer(task) && instant(task.createdAt) !== null && instant(plan.createdAt) !== null &&
127
+ instant(task.createdAt) >= instant(plan.createdAt) && (!nextPlan?.createdAt || (instant(nextPlan.createdAt) !== null && instant(task.createdAt) < instant(nextPlan.createdAt))));
128
+ node(reviewId, 'Final Review ' + number + ' / ' + review, workElapsed(reviewTasks));
129
+ edge(previous, planId, i > 0 && plan.trigger?.source === 'review' ? 'changes required' : '');
130
+ edge(planId, executeId);
131
+ edge(executeId, reviewId);
132
+ previous = reviewId;
133
+ }
134
+ const merge = job.localMerge?.status === 'failed' ? 'FAILED' : job.localMerge?.status === 'succeeded' || job.githubState === 'MERGED' || job.publication?.version ? 'DONE' : job.state === 'COMPLETED' ? 'NOT RECORDED' : 'PENDING';
135
+ const mergeStart = job.review?.outcome === 'approved' ? job.review.updatedAt : undefined;
136
+ const mergeEnd = merge === 'DONE' ? job.localMerge?.updatedAt || job.mergedAt : merge === 'PENDING' && mergeStart ? 'NOW' : undefined;
137
+ node('merge', 'Merge / ' + merge, elapsed(mergeStart, mergeEnd));
138
+ node('finished', 'Job / ' + state(job.state, 'UNKNOWN'), elapsed(job.createdAt, jobEnd));
139
+ edge(previous, 'merge');
140
+ edge('merge', 'finished');
141
+ return finish();
142
+ }
@@ -75,11 +75,11 @@ export const dashboardStyles = ` <style>
75
75
  .job-primary { display:flex; align-items:center; justify-content:space-between; gap:.45rem; min-width:0; }
76
76
  .job-status-line { display:flex; align-items:center; gap:.3rem; min-width:0; white-space:nowrap; }
77
77
  .job-status-line .badge { flex:0 0 auto; }
78
- .status-pill,.badge { display:inline-flex; align-items:center; border-radius:999px; padding:.06rem .42rem; min-height:1.35rem; font-size:.68rem; font-weight:800; }
79
- .status-pill.ok,.badge.ACTIVE,.badge.RUNNING,.badge.SUCCEEDED,.badge.COMPLETED,.badge.MERGED { background:#e5f3e9; color:var(--ok); }
80
- .status-pill.warn,.badge.BLOCKED,.badge.DRAFT,.badge.QUEUED,.badge.WAITING,.badge.AWAITING_DECISION,.badge.OPEN { background:#fff1d2; color:var(--warn); }
81
- .status-pill.bad,.badge.FAILED { background:#ffe8e8; color:var(--bad); }
82
- .status-pill.neutral,.badge.IDLE,.badge.CANCELLED { background:#edf0f4; color:var(--muted); }
78
+ .badge { display:inline-flex; align-items:center; border-radius:999px; padding:.06rem .42rem; min-height:1.35rem; font-size:.68rem; font-weight:800; }
79
+ .badge.ACTIVE,.badge.RUNNING,.badge.SUCCEEDED,.badge.COMPLETED,.badge.MERGED { background:#e5f3e9; color:var(--ok); }
80
+ .badge.BLOCKED,.badge.DRAFT,.badge.QUEUED,.badge.WAITING,.badge.AWAITING_DECISION,.badge.OPEN { background:#fff1d2; color:var(--warn); }
81
+ .badge.FAILED { background:#ffe8e8; color:var(--bad); }
82
+ .badge.IDLE,.badge.CANCELLED { background:#edf0f4; color:var(--muted); }
83
83
  .badge.DRAFT { background:#eef2ff; color:#3f51b5; }
84
84
  .badge.shortcut-mode { background:var(--accent2); color:var(--accent); border:1px solid var(--accent); }
85
85
  .badge.MERGE_PENDING { background:#ffe3a3; color:#7a4a00; }
@@ -131,6 +131,17 @@ export const dashboardStyles = ` <style>
131
131
  .graph-navigation { display:flex; flex-wrap:wrap; align-items:center; gap:.5rem; margin-bottom:.7rem; }
132
132
  .graph-canvas .node.drillable { cursor:pointer; }
133
133
  .graph-canvas .node.drillable text, .graph-canvas .node.drillable tspan { fill:#2367b1; }
134
+ .jel-dialog { width:min(1050px,96vw); max-height:90vh; padding:.8rem; border:1px solid var(--border); border-radius:.55rem; background:var(--surface); color:var(--text); }
135
+ .jel-dialog::backdrop { background:#17202b99; }
136
+ .jel-dialog-header { display:flex; justify-content:space-between; align-items:center; gap:1rem; padding:.2rem .3rem .6rem; }
137
+ .jel-legend { display:flex; align-items:center; flex-wrap:wrap; gap:.5rem; padding:.1rem .3rem .6rem; font-size:.76rem; font-weight:700; }
138
+ .jel-legend span { padding:.16rem .5rem; border-radius:.35rem; border:1px solid; }
139
+ .jel-legend-failed { background:#fee2e2; border-color:#b91c1c!important; color:#991b1b; }
140
+ .jel-legend-retry { background:#ede9fe; border-color:#7c3aed!important; color:#5b21b6; }
141
+ .jel-legend-troubleshooter { background:#fef3c7; border-color:#b45309!important; color:#92400e; }
142
+ .jel-chart { min-height:14rem; max-height:72vh; overflow:auto; padding:.8rem; border:1px solid var(--border); border-radius:.4rem; background:var(--surface2); }
143
+ .jel-chart svg { display:block; min-width:100%; max-width:none; height:auto; }
144
+ .jel-source { overflow:auto; white-space:pre; font:12px/1.5 ui-monospace,monospace; }
134
145
  .graph-dialog { width:96vw; height:94vh; max-width:none; max-height:none; padding:.7rem; border:1px solid var(--border); border-radius:.5rem; background:var(--surface); color:var(--text); }
135
146
  .graph-dialog::backdrop { background:#17202b99; }
136
147
  .graph-dialog-header { display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:.7rem; padding:.3rem .5rem; }
@@ -181,7 +192,6 @@ export const dashboardStyles = ` <style>
181
192
  #jobs-view #jobs-refresh { width:2.25rem; height:2.25rem; }
182
193
  #jobs-workspace > .panel:first-child > .panel-head { display:grid; grid-template-columns:auto minmax(0,1fr) auto; gap:.3rem; align-items:center; }
183
194
  #jobs-workspace > .panel:first-child > .panel-head .panel-actions { flex-wrap:nowrap; gap:.05rem; }
184
- #jobs-workspace > .panel:first-child > .panel-head #connection { display:none; }
185
195
  #jobs-view .panel-body { max-height:none; }
186
196
  #jobs-workspace { gap:.65rem; }
187
197
  #jobs-workspace .panel-body { max-height:none; }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agents-relay",
3
- "version": "2.0.242",
3
+ "version": "2.0.244",
4
4
  "description": "Durable async agent jobs coordinated through GitHub pull requests",
5
5
  "repository": {
6
6
  "type": "git",