sidequestor 0.2.9.dev1__py3-none-any.whl → 0.2.11.dev0__py3-none-any.whl
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.
- sidequestor/__init__.py +1 -1
- sidequestor/runtime/dashboard-quest-visualizer.js +18 -3
- sidequestor/runtime/dashboard.html +17 -15
- sidequestor/runtime/yaas-triage/checkers/cron-due.py +5 -4
- sidequestor/runtime/yaas-triage/checkers/schedule.py +16 -6
- sidequestor/runtime/yaas-triage/dashboard_visualizer.py +3 -2
- sidequestor/runtime/yaas-triage/dispatch/slack-read-health.py +74 -3
- sidequestor/runtime/yaas-triage/ledger/approval-helper.py +11 -1
- sidequestor/runtime/yaas-triage/ops/dashboard-server.py +53 -4
- sidequestor/runtime/yaas-triage/skills/yaas-onboarding/SKILL.md +22 -1
- sidequestor/runtime/yaas-triage/skills/yaas-quest-creation/SKILL.md +6 -5
- sidequestor/runtime/yaas-triage/skills/yaas-quest-dispatch/SKILL.md +39 -2
- sidequestor/runtime/yaas-triage/skills/yaas-reactions/SKILL.md +57 -5
- sidequestor/runtime/yaas-triage/surfaces/log-event.py +17 -1
- sidequestor/runtime/yaas-triage/surfaces/slack-send.py +119 -18
- sidequestor/runtime/yaas-triage/tick.py +45 -3
- sidequestor/runtime/yaas-triage/timeline_time.py +62 -0
- {sidequestor-0.2.9.dev1.dist-info → sidequestor-0.2.11.dev0.dist-info}/METADATA +59 -6
- {sidequestor-0.2.9.dev1.dist-info → sidequestor-0.2.11.dev0.dist-info}/RECORD +23 -22
- {sidequestor-0.2.9.dev1.dist-info → sidequestor-0.2.11.dev0.dist-info}/WHEEL +0 -0
- {sidequestor-0.2.9.dev1.dist-info → sidequestor-0.2.11.dev0.dist-info}/entry_points.txt +0 -0
- {sidequestor-0.2.9.dev1.dist-info → sidequestor-0.2.11.dev0.dist-info}/licenses/LICENSE +0 -0
- {sidequestor-0.2.9.dev1.dist-info → sidequestor-0.2.11.dev0.dist-info}/top_level.txt +0 -0
sidequestor/__init__.py
CHANGED
|
@@ -4,6 +4,21 @@
|
|
|
4
4
|
const LIMIT=180,LANES=['Triggers','Resources','Actions'];
|
|
5
5
|
const scalar=v=>typeof v==='string'||typeof v==='number'?String(v):'';
|
|
6
6
|
function instant(v){if(v===null||v===undefined||v===''||typeof v==='boolean')return null;const n=Number(v),t=Number.isFinite(n)?n*(Math.abs(n)<1e12?1000:1):Date.parse(typeof v==='string'&&/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/.test(v)?v.replace(' ','T')+'Z':v);return Number.isFinite(t)&&Number.isFinite(new Date(t).getTime())?t:null}
|
|
7
|
+
// Opt-in source-message time; never infer it from thread IDs or polling watermarks.
|
|
8
|
+
const SOURCE_TIME_EVENTS=new Set(['info_received','info_logged','message_received','email_received']);
|
|
9
|
+
function sourceEventTime(e){
|
|
10
|
+
if(!SOURCE_TIME_EVENTS.has(e.event))return null;
|
|
11
|
+
const v=e.source_event_ts,recorded=instant(e.ts||e.timestamp);if(recorded===null||typeof v==='boolean'||v===null||v===undefined||v==='')return null;
|
|
12
|
+
let t=null;
|
|
13
|
+
if(typeof v==='number'||typeof v==='string'&&/^\d+(?:\.\d+)?$/.test(v)){const n=Number(v);if(Number.isFinite(n)&&n>0)t=n*1000}
|
|
14
|
+
else if(typeof v==='string'){
|
|
15
|
+
const m=v.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/);
|
|
16
|
+
if(m){const [,y,month,d,h,min,sec='0']=m,calendar=new Date(Date.UTC(Number(y),Number(month)-1,Number(d)));if(calendar.getUTCFullYear()===Number(y)&&calendar.getUTCMonth()===Number(month)-1&&calendar.getUTCDate()===Number(d)&&Number(h)<24&&Number(min)<60&&Number(sec)<60)t=Date.parse(v)}
|
|
17
|
+
}
|
|
18
|
+
const coarse=typeof(e.ts||e.timestamp)==='string'&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:Z|[+-]\d{2}:\d{2})$/.test(e.ts||e.timestamp);
|
|
19
|
+
return t!==null&&Number.isFinite(t)&&t>0&&Number.isFinite(new Date(t).getTime())&&(coarse?t<recorded+1000:t<=recorded)?t:null;
|
|
20
|
+
}
|
|
21
|
+
function eventTime(e){return sourceEventTime(e)??instant(e.ts||e.timestamp)}
|
|
7
22
|
function lane(e){return /trigger|watch|check|received|due/.test(scalar(e.event))?'Triggers':/read|resource|file|fetch|inspect/.test(scalar(e.event))?'Resources':'Actions'}
|
|
8
23
|
function resources(e){const out=[];for(const key of ['channel_id','thread_ts','repo','issue','pr','doc_id','file','path','file_id','source_file_id','target_file_id','message_id','thread_id','item_id'])if(scalar(e[key]))out.push({key,value:scalar(e[key])});return out}
|
|
9
24
|
function safeLink(value){try{const u=new URL(value);return !u.username&&!u.password&&['https:','http:','slack:'].includes(u.protocol)?u.href:null}catch{return null}}
|
|
@@ -82,7 +97,7 @@ function entities(raw,context={},depth=0){
|
|
|
82
97
|
return [...found.values()].slice(0,80).map(d=>({...d,kind:'Resource',category:categoryOf(d.type)==='other'?'resource':categoryOf(d.type)}));
|
|
83
98
|
}
|
|
84
99
|
|
|
85
|
-
function normalize(data){const context={slack_channels:{}},slackOrigins=new Set,jiraOrigins=new Set,ambiguousChannels=new Set;for(const raw of [...(Array.isArray(data.events)?data.events:[]),...(Array.isArray(data.watches)?data.watches:[])]){if(!raw||typeof raw!=='object')continue;for(const key of ['permalink','slack_url','message_url','link_url','url','ticket_url']){try{const u=new URL(raw[key]);if(!safeLink(u.href))continue;if(/^https?:$/.test(u.protocol)&&/^[a-z0-9-]+\.slack\.com$/.test(u.hostname)){slackOrigins.add(u.origin);const c=u.pathname.match(/^\/archives\/([A-Z0-9]+)/)?.[1];if(c){if(context.slack_channels[c]&&context.slack_channels[c]!==u.origin)ambiguousChannels.add(c);context.slack_channels[c]=u.origin}};if(/^https?:$/.test(u.protocol)&&/\/browse\/[A-Z][A-Z0-9]+-\d+/.test(u.pathname)&&(u.hostname.endsWith('.atlassian.net')||providerOf(raw)==='jira'||key==='ticket_url'))jiraOrigins.add(u.origin)}catch{}}}for(const c of ambiguousChannels)delete context.slack_channels[c];if(jiraOrigins.size===1)context.jira_origin=[...jiraOrigins][0];const events=(Array.isArray(data.events)?data.events:[]).filter(e=>e&&typeof e==='object').map((e,i)=>({id:scalar(e.event_id||e.id)||`entry-${i}`,explicitId:scalar(e.event_id||e.id),time:
|
|
100
|
+
function normalize(data){const context={slack_channels:{}},slackOrigins=new Set,jiraOrigins=new Set,ambiguousChannels=new Set;for(const raw of [...(Array.isArray(data.events)?data.events:[]),...(Array.isArray(data.watches)?data.watches:[])]){if(!raw||typeof raw!=='object')continue;for(const key of ['permalink','slack_url','message_url','link_url','url','ticket_url']){try{const u=new URL(raw[key]);if(!safeLink(u.href))continue;if(/^https?:$/.test(u.protocol)&&/^[a-z0-9-]+\.slack\.com$/.test(u.hostname)){slackOrigins.add(u.origin);const c=u.pathname.match(/^\/archives\/([A-Z0-9]+)/)?.[1];if(c){if(context.slack_channels[c]&&context.slack_channels[c]!==u.origin)ambiguousChannels.add(c);context.slack_channels[c]=u.origin}};if(/^https?:$/.test(u.protocol)&&/\/browse\/[A-Z][A-Z0-9]+-\d+/.test(u.pathname)&&(u.hostname.endsWith('.atlassian.net')||providerOf(raw)==='jira'||key==='ticket_url'))jiraOrigins.add(u.origin)}catch{}}}for(const c of ambiguousChannels)delete context.slack_channels[c];if(jiraOrigins.size===1)context.jira_origin=[...jiraOrigins][0];const events=(Array.isArray(data.events)?data.events:[]).filter(e=>e&&typeof e==='object').map((e,i)=>({id:scalar(e.event_id||e.id)||`entry-${i}`,explicitId:scalar(e.event_id||e.id),time:eventTime(e),label:scalar(e.event).replaceAll('_',' ')||'Recorded event',event:scalar(e.event)||'note',lane:lane(e),note:scalar(e.note||e.reason||e.summary||e.brief||e.finding||e.detail),watch:scalar(e.watch_id),approval:scalar(e.approval_id),dispatch:scalar(e.dispatch_id),associatedDispatch:scalar(e.associated_dispatch_id),parents:[e.parent_event_id,e.source_event_id,e.caused_by,...(Array.isArray(e.parent_event_ids)?e.parent_event_ids:[])].map(scalar).filter(Boolean),resources:resources(e),url:safeLink(e.link_url||e.slack_url||e.permalink),source:scalar(e.evidence_source)||'quest timeline',activity:e.succeeded===false||['failed','error','blocked'].includes(scalar(e.status||e.outcome).toLowerCase())?'attention':activity(scalar(e.event)),raw:e})).sort((a,b)=>(a.time??Infinity)-(b.time??Infinity));
|
|
86
101
|
const frequencies=new Map;for(const e of events)if(e.explicitId)frequencies.set(e.explicitId,(frequencies.get(e.explicitId)||0)+1);for(let i=0;i<events.length;i++)if(frequencies.get(events[i].explicitId)>1)events[i].id=`duplicate-${i}`;
|
|
87
102
|
const byId=new Map(events.filter(e=>e.explicitId&&frequencies.get(e.explicitId)===1).map(e=>[e.explicitId,e]));const edges=[];for(const e of events)for(const parent of e.parents)if(byId.has(parent))edges.push({from:byId.get(parent).id,to:e.id,type:'recorded cause'});
|
|
88
103
|
return{context,watchTypes:data.watch_types||{},createdAt:instant(data.created_at),historicalWatches:Array.isArray(data.historical_watches)?data.historical_watches:[],title:scalar(data.title)||scalar(data.id),events,edges,watches:(Array.isArray(data.watches)?data.watches:[]).filter(w=>w&&typeof w==='object'),truncated:!!data.truncated,eventLimit:data.event_limit||5000,coverage:data.coverage||{}};}
|
|
@@ -155,7 +170,7 @@ function label(n){return privateView?n.alias:n.label}
|
|
|
155
170
|
function configurationTargets(n,time){const configs=n.configurations||[],distinct=new Set(configs.map(c=>[...c.targets].sort().join('\0'))).size,asOf=Date.now();const dated=configs.map(c=>({...c,time:c.observed??(c.current&&distinct===1?c.created:c.current?asOf:null)})).filter(c=>c.time!==null&&c.time<=time).sort((a,b)=>b.time-a.time);return new Set(dated[0]?.targets||configs.find(c=>c.current&&c.created===null&&distinct===1)?.targets||[])}
|
|
156
171
|
function viewBox(){pan.x=Math.max(-600,Math.min(600,pan.x));pan.y=Math.max(-g.height/2,Math.min(g.height/2,pan.y));if(ui)ui.svg.setAttribute('viewBox',`${600-600/zoom+pan.x} ${g.height/2-g.height/(2*zoom)+pan.y} ${1200/zoom} ${g.height/zoom}`)}
|
|
157
172
|
function tooltip(n,pin=false){if(pin)pinned=n.id;const box=ui.tipContent;box.replaceChildren();ui.tooltip.hidden=false;ui.tipClose.hidden=!(pin||pinned===n.id);box.append(node('div','qv-tip-kind',(n.kind==='Watch'?CATEGORIES[n.category][0]+' watch':n.type||n.kind)),node('h3','',label(n)));const events=n.eventIds.map(id=>g.eventById.get(id)).filter(Boolean),cut=timeAt(g.times,position,mode);const visible=events.filter(e=>e.time!==null&&e.time<=cut);box.append(node('p','',`${visible.length} recorded events by this moment · ${n.hits} in this history`));
|
|
158
|
-
if(!privateView){if(n.url){const a=node('a','qv-resource-link','Open '+(n.type||n.kind)+' ↗');a.href=n.url;a.target='_blank';a.rel='noopener noreferrer';box.append(a)}else if(n.type==='Slack thread'&&safeLink(n.detail.channel_url)){const a=node('a','qv-resource-link','Open containing Slack channel ↗');a.href=safeLink(n.detail.channel_url);a.target='_blank';a.rel='noopener noreferrer';box.append(a)}for(const [key,value]of Object.entries(n.detail)){if(typeof value!=='string'||!value||['channel_url','recorded_url'].includes(key))continue;box.append(node('div','qv-tip-key',({next_fire_ts:'Scheduled for',cron:'Cron expression',tz:'Time zone'})[key]||key.replaceAll('_',' ')),node('p','',value))}for(const w of n.kind==='Watch'?[n.watch].filter(Boolean):n.watches||[]){const since=watchInstant(w.created_ts)||watchInstant(w.observed_at);box.append(node('div','qv-tip-key',(w.historical?'Historical watch snapshot · ':'Current watch configuration · ')+scalar(w.type).replaceAll('_',' ')),node('p','',scalar(w.reason)||'Configured watch point'),node('small','',since===null?'Start date not retained; current configuration is shown as context.':(w.created_ts?'Creation recorded: ':'Snapshot retained: ')+stamp(since)));if(w.projection_truncated)box.append(node('p','','Some criteria or descriptions were shortened by display limits.'));if(w.watch_evidence||w.historical)box.append(node('p','',w.watch_evidence||'Retained historical snapshot; exact start and retirement may be unknown.'))}if(n.kind==='Watch'){const state=watchState(n,cut??Date.now());box.append(node('div','qv-tip-key','Monitoring evidence'),node('p','',stateText(state)));if(n.retiredAt!==undefined)box.append(node('p','','Retirement recorded: '+stamp(n.retiredAt)));if(!n.supported&&!n.detail.grouped)box.append(node('p','','Unrecognized watch type; retained criteria are shown without assuming its behaviour.'));const linked=g.links.filter(l=>l.from===n.id&&l.type==='configuration').map(l=>g.nodes.find(x=>x.id===l.to)).filter(Boolean);for(const target of linked){const b=button('View '+target.type,()=>{stop();tooltip(target,true)});box.append(b)}}for(const last of visible.slice(-3).reverse())box.append(node('div','qv-tip-key',stamp(last.time)+' · '+last.label),node('p','',last.note||last.label),node('small','',last.source+(last.raw.projection_truncated?' · Details shortened by display limits.':'')+(last.subjectAssociation?' · Subject matched by review/health ID, not a causal link.':'')));}
|
|
173
|
+
if(!privateView){if(n.url){const a=node('a','qv-resource-link','Open '+(n.type||n.kind)+' ↗');a.href=n.url;a.target='_blank';a.rel='noopener noreferrer';box.append(a)}else if(n.type==='Slack thread'&&safeLink(n.detail.channel_url)){const a=node('a','qv-resource-link','Open containing Slack channel ↗');a.href=safeLink(n.detail.channel_url);a.target='_blank';a.rel='noopener noreferrer';box.append(a)}for(const [key,value]of Object.entries(n.detail)){if(typeof value!=='string'||!value||['channel_url','recorded_url'].includes(key))continue;box.append(node('div','qv-tip-key',({next_fire_ts:'Scheduled for',cron:'Cron expression',tz:'Time zone'})[key]||key.replaceAll('_',' ')),node('p','',value))}for(const w of n.kind==='Watch'?[n.watch].filter(Boolean):n.watches||[]){const since=watchInstant(w.created_ts)||watchInstant(w.observed_at);box.append(node('div','qv-tip-key',(w.historical?'Historical watch snapshot · ':'Current watch configuration · ')+scalar(w.type).replaceAll('_',' ')),node('p','',scalar(w.reason)||'Configured watch point'),node('small','',since===null?'Start date not retained; current configuration is shown as context.':(w.created_ts?'Creation recorded: ':'Snapshot retained: ')+stamp(since)));if(w.projection_truncated)box.append(node('p','','Some criteria or descriptions were shortened by display limits.'));if(w.watch_evidence||w.historical)box.append(node('p','',w.watch_evidence||'Retained historical snapshot; exact start and retirement may be unknown.'))}if(n.kind==='Watch'){const state=watchState(n,cut??Date.now());box.append(node('div','qv-tip-key','Monitoring evidence'),node('p','',stateText(state)));if(n.retiredAt!==undefined)box.append(node('p','','Retirement recorded: '+stamp(n.retiredAt)));if(!n.supported&&!n.detail.grouped)box.append(node('p','','Unrecognized watch type; retained criteria are shown without assuming its behaviour.'));const linked=g.links.filter(l=>l.from===n.id&&l.type==='configuration').map(l=>g.nodes.find(x=>x.id===l.to)).filter(Boolean);for(const target of linked){const b=button('View '+target.type,()=>{stop();tooltip(target,true)});box.append(b)}}for(const last of visible.slice(-3).reverse())box.append(node('div','qv-tip-key',stamp(last.time)+' · '+last.label),node('p','',last.note||last.label),node('small','',last.source+(sourceEventTime(last.raw)!==null?' · Recorded '+stamp(instant(last.raw.ts||last.raw.timestamp)):'')+(last.raw.projection_truncated?' · Details shortened by display limits.':'')+(last.subjectAssociation?' · Subject matched by review/health ID, not a causal link.':'')));}
|
|
159
174
|
else box.append(node('p','','Private names, identifiers, notes and resource links are hidden.'));
|
|
160
175
|
if(n.detail.grouped)box.append(node('p','',`${n.detail.grouped} additional entities grouped for a responsive view.`));
|
|
161
176
|
|
|
@@ -187,5 +202,5 @@ function update(){if(!ui||!g)return;const t=timeAt(g.times,position,mode),snap=s
|
|
|
187
202
|
ui.slider.value=String(Math.round(position*10000));ui.slider.setAttribute('aria-valuetext',stamp(t));ui.clock.textContent=stamp(t);ui.clock.dateTime=new Date(t).toISOString();ui.count.textContent=`${snap.completed.toLocaleString()} / ${g.events.length.toLocaleString()} records`;if(snap.latest){ui.latest.replaceChildren(node('strong','',snap.latest.label),node('span','',privateView?'Recorded quest activity':snap.latest.note.slice(0,200)||snap.latest.source))}else ui.latest.textContent='Before the first recorded event';if(pinned){const key=pinned+':'+snap.completed+':'+privateView;if(ui.tipStamp!==key){ui.tipStamp=key;const n=g.nodes.find(n=>n.id===pinned);if(n)tooltip(n,true)}}}
|
|
188
203
|
function tick(now){frame=null;if(!play||!dialog.open||document.hidden){stop();return}if(lastFrame!==null)position=Math.min(1,position+(Math.min(100,now-lastFrame)/1000)*rate/Math.min(60,Math.max(14,g.times.length*1.4)));lastFrame=now;update();if(position>=1)stop();else frame=requestAnimationFrame(tick)}
|
|
189
204
|
async function open(id){const generation=++loadGeneration;ensure();stop();ui=null;g=null;model=null;dialog.replaceChildren(node('div','qv-loading','Collecting the story from timelines and trigger logs…'));if(!dialog.open)dialog.showModal();try{const response=await fetch(`/api/quest/${encodeURIComponent(id)}/visualization`,{cache:'no-store'});if(!response.ok)throw Error(response.status===404?'Quest replay is disabled or unavailable.':'Could not load quest evidence.');const data=await response.json();if(generation!==loadGeneration||!dialog.open)return;model=normalize(data);g=graph(model);position=1;pinned=null;zoom=1;pan={x:0,y:0};assemble()}catch(error){if(generation!==loadGeneration||!dialog.open)return;dialog.replaceChildren(button('Close',()=>dialog.close()),node('p','qv-loading',error.message))}}
|
|
190
|
-
return{normalize,project,graph,snapshot,timeAt,progressAt,instant,safeLink,entities,activity,watchCategory,watchState,configurationTargets,WATCH_TYPES,CATEGORIES,open,LIMIT};
|
|
205
|
+
return{normalize,project,graph,snapshot,timeAt,progressAt,instant,sourceEventTime,eventTime,safeLink,entities,activity,watchCategory,watchState,configurationTargets,WATCH_TYPES,CATEGORIES,open,LIMIT};
|
|
191
206
|
});
|
|
@@ -116,10 +116,10 @@ button:focus-visible,textarea:focus-visible,input:focus-visible,select:focus-vis
|
|
|
116
116
|
<section class="briefings" id="briefings"><aside class="brief-index"><header class="brief-index-head"><div class="eyebrow">Field notes</div><h2>Briefings</h2><p>Morning, evening, weekly, and monthly perspective.</p></header><div class="brief-picker"><button class="button brief-picker-trigger" id="brief-picker-trigger" type="button" aria-haspopup="listbox" aria-expanded="false"><span class="brief-kind" id="brief-picker-kind">Brief</span><span class="brief-picker-title" id="brief-picker-title">Select a briefing</span><svg aria-hidden="true" viewBox="0 0 12 8"><path d="m1 1 5 5 5-5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg></button><div class="brief-picker-list" id="brief-picker-list" role="listbox" aria-label="Briefing archive" hidden></div></div><div class="brief-list" id="brief-list"><div class="brief-empty">Open Briefings to load the archive.</div></div></aside><article class="brief-reader" id="brief-reader"><div class="brief-empty">Select a briefing to read it.</div></article></section>
|
|
117
117
|
<section class="audit" id="audit"><section class="audit-panel"><h2>Approval history</h2><div class="audit-list" id="approval-history"></div></section><section class="audit-panel"><h2>Dispatch history</h2><div class="audit-list" id="run-history"></div></section></section>
|
|
118
118
|
</main>
|
|
119
|
-
<dialog id="quest-dialog"><form class="dialog-body" id="quest-form"><div class="eyebrow">In your own words</div><h2>Create a quest</h2><p class="muted">Describe the mission and who it involves. Sidequestor creates an explicitly marked bootstrap quest, then resolves exact watches on the next triage tick without guessing.</p><input id="quest-title" maxlength="120" placeholder="Optional short title…"><textarea id="quest-prompt" maxlength="4000" required placeholder="Who should I listen to, who should I talk to, and what should I do about it?"></textarea><p class="muted field-hint">
|
|
119
|
+
<dialog id="quest-dialog"><form class="dialog-body" id="quest-form"><div class="eyebrow">In your own words</div><h2>Create a quest</h2><p class="muted">Describe the mission and who it involves. Sidequestor creates an explicitly marked bootstrap quest, then resolves exact watches on the next triage tick without guessing.</p><input id="quest-title" maxlength="120" placeholder="Optional short title…"><textarea id="quest-prompt" maxlength="4000" required placeholder="Who should I listen to, who should I talk to, and what should I do about it?"></textarea><p class="muted field-hint">Sidequestor verifies the watches or completes the one-shot task. Missing details appear in manual review so you can answer them here.</p><select id="quest-priority"><option value="normal">Normal priority</option><option value="high">High priority</option><option value="low">Low priority</option></select><div class="quest-guide-cmd"><button type="button" class="button" id="open-creation-terminal" title="Open your chosen app to create a quest together">Create in Codex instead</button></div><div class="inline-status" id="quest-status" role="status"></div><div class="dialog-actions"><button type="button" class="button" id="cancel-quest">Cancel</button><button class="button primary">Create quest</button></div></form></dialog>
|
|
120
120
|
<dialog id="settings-dialog" aria-labelledby="settings-title"><div class="dialog-body"><header class="settings-head"><h2 id="settings-title">Sidequestor settings</h2><button type="button" class="icon-button" id="close-settings" aria-label="Close settings">×</button></header><p class="muted settings-instructions">Edit <code class="settings-path" id="settings-path">.env</code> in your workspace. Add or change <code>KEY=value</code>; remove a line to restore its runtime default. Quote values containing spaces. Keep credentials in Keychain or a secret manager. Credential values are hidden here.</p><p class="muted settings-instructions">Most changes apply on the next poll or dispatch. Run <code>sq stop</code>, then <code>sq start</code> after changing loop intervals or exported process settings. If a process environment value takes precedence, update or unset that exported variable too. Existing terminal sessions may need reopening. Review agent model and permission changes before saving.</p><input type="search" id="settings-filter" aria-label="Filter settings" placeholder="Filter settings by name or description…"><div id="settings-status" role="status" class="muted"></div><div class="settings-scroll" id="settings-content"></div><div class="dialog-actions"><button class="button" id="refresh-settings" type="button">Refresh</button><button class="button primary" id="settings-edit" type="button">Edit in Codex</button></div></div></dialog>
|
|
121
121
|
<dialog id="review-dialog"><div class="dialog-body" id="review-dialog-shell"></div></dialog>
|
|
122
|
-
<dialog id="help-dialog" aria-labelledby="help-title"><div class="help-shell"><header class="help-mast"><div class="help-guide-mark" aria-hidden="true"><svg viewBox="0 0 32 32" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M6 25V7l5 3 5-3 5 3 5-3v18l-5-3-5 3-5-3-5 3Z"/><path d="m11 10 5 3 5-3M16 13v12"/><circle cx="21" cy="16" r="2" fill="currentColor" stroke="none"/></svg></div><div class="help-mast-copy"><div class="help-kicker">Player handbook</div><h2 id="help-title">Sidequestor Field Guide</h2><p>Two short chapters for keeping your quests moving.</p></div><button class="help-close" id="close-help" type="button" aria-label="Close field guide">X</button></header><div class="help-tabs" role="tablist" aria-label="Field guide chapters"><button class="help-tab" id="help-tab-quests" type="button" role="tab" aria-selected="true" aria-controls="help-panel-quests" tabindex="0" data-help-tab="quests"><span class="help-tab-number">01</span>Quests</button><button class="help-tab" id="help-tab-reactions" type="button" role="tab" aria-selected="false" aria-controls="help-panel-reactions" tabindex="-1" data-help-tab="reactions"><span class="help-tab-number">02</span>Slack reactions</button></div><div class="help-pages"><section class="help-page" id="help-panel-quests" role="tabpanel" aria-labelledby="help-tab-quests" data-help-panel="quests"><div class="help-lead"><div><h3>Your folder, running as a service</h3><p>Sidequestor is for people who want to expose a local working directory as a service that stays awake. It can keep doing work, help colleagues, notice new replies, and continue a mission while you are away.</p></div><aside class="help-callout"><strong>The golden rule</strong><p>Want to work interactively with a quest or anything in its folder? Go straight to your Terminal. That is your workshop.</p></aside></div><div class="help-section-label">The quest loop</div><div class="help-steps"><article class="help-step"><b>1</b><h4>Create</h4><p>Describe the mission, people involved, and what “done” should look like.</p></article><article class="help-step"><b>2</b><h4>Watch</h4><p>Tripwires listen for Slack, email, schedule, or repo activity.</p></article><article class="help-step"><b>3</b><h4>Act</h4><p>The local agent does the next step, records what happened, and can add new channels, tickets, and emails to watch.</p></article><article class="help-step"><b>4</b><h4>Continue</h4><p>The quest remembers its state and waits for the next useful signal.</p></article></div><div class="help-section-label">Choose your screen</div><div class="help-places"><article class="help-place terminal"><h4>Terminal = the workshop</h4><p>Create or edit files, inspect quest state, and work directly with your local agent here.</p></article><article class="help-place dashboard"><h4>Dashboard = the map</h4><p>Scan activity, open a quest’s story, and review work in an easy-to-read view. Quests themselves are created in the Terminal. The files remain the source of truth.</p></article></div></section><section class="help-page" id="help-panel-reactions" role="tabpanel" aria-labelledby="help-tab-reactions" data-help-panel="reactions" hidden><div class="help-lead"><div><h3>Cast a tiny spell from Slack</h3><p>Add a configured reaction to any Slack message. Sidequestor sees it on a later tick, picks up the thread context, and performs that one-off action for you.</p></div><aside class="help-callout"><strong>No quest required</strong><p>Reaction jobs use a fast path for ad hoc work. A quest is only needed when the job turns into ongoing follow-up.</p></aside></div><div class="help-spells"><article class="help-spell"><span class="help-spell-icon" aria-hidden="true">⚡</span><div><h4><code data-reaction-role="process">loading…</code></h4><p>Handle this. Do the work and reply in the Slack thread.</p></div></article><article class="help-spell"><span class="help-spell-icon" aria-hidden="true">✎</span><div><h4><code data-reaction-role="draft">loading…</code></h4><p>Draft this. Research and prepare a reply, but leave sending to you.</p></div></article><article class="help-spell"><span class="help-spell-icon" aria-hidden="true">▣</span><div><h4><code data-reaction-role="save">loading…</code></h4><p>Remember this. Save useful context quietly, with no reply.</p></div></article><article class="help-spell"><span class="help-spell-icon" aria-hidden="true">✉</span><div><h4><code data-reaction-role="adopt">loading…</code></h4><p>Adopt this.
|
|
122
|
+
<dialog id="help-dialog" aria-labelledby="help-title"><div class="help-shell"><header class="help-mast"><div class="help-guide-mark" aria-hidden="true"><svg viewBox="0 0 32 32" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M6 25V7l5 3 5-3 5 3 5-3v18l-5-3-5 3-5-3-5 3Z"/><path d="m11 10 5 3 5-3M16 13v12"/><circle cx="21" cy="16" r="2" fill="currentColor" stroke="none"/></svg></div><div class="help-mast-copy"><div class="help-kicker">Player handbook</div><h2 id="help-title">Sidequestor Field Guide</h2><p>Two short chapters for keeping your quests moving.</p></div><button class="help-close" id="close-help" type="button" aria-label="Close field guide">X</button></header><div class="help-tabs" role="tablist" aria-label="Field guide chapters"><button class="help-tab" id="help-tab-quests" type="button" role="tab" aria-selected="true" aria-controls="help-panel-quests" tabindex="0" data-help-tab="quests"><span class="help-tab-number">01</span>Quests</button><button class="help-tab" id="help-tab-reactions" type="button" role="tab" aria-selected="false" aria-controls="help-panel-reactions" tabindex="-1" data-help-tab="reactions"><span class="help-tab-number">02</span>Slack reactions</button></div><div class="help-pages"><section class="help-page" id="help-panel-quests" role="tabpanel" aria-labelledby="help-tab-quests" data-help-panel="quests"><div class="help-lead"><div><h3>Your folder, running as a service</h3><p>Sidequestor is for people who want to expose a local working directory as a service that stays awake. It can keep doing work, help colleagues, notice new replies, and continue a mission while you are away.</p></div><aside class="help-callout"><strong>The golden rule</strong><p>Want to work interactively with a quest or anything in its folder? Go straight to your Terminal. That is your workshop.</p></aside></div><div class="help-section-label">The quest loop</div><div class="help-steps"><article class="help-step"><b>1</b><h4>Create</h4><p>Describe the mission, people involved, and what “done” should look like.</p></article><article class="help-step"><b>2</b><h4>Watch</h4><p>Tripwires listen for Slack, email, schedule, or repo activity.</p></article><article class="help-step"><b>3</b><h4>Act</h4><p>The local agent does the next step, records what happened, and can add new channels, tickets, and emails to watch.</p></article><article class="help-step"><b>4</b><h4>Continue</h4><p>The quest remembers its state and waits for the next useful signal.</p></article></div><div class="help-section-label">Choose your screen</div><div class="help-places"><article class="help-place terminal"><h4>Terminal = the workshop</h4><p>Create or edit files, inspect quest state, and work directly with your local agent here.</p></article><article class="help-place dashboard"><h4>Dashboard = the map</h4><p>Scan activity, open a quest’s story, and review work in an easy-to-read view. Quests themselves are created in the Terminal. The files remain the source of truth.</p></article></div></section><section class="help-page" id="help-panel-reactions" role="tabpanel" aria-labelledby="help-tab-reactions" data-help-panel="reactions" hidden><div class="help-lead"><div><h3>Cast a tiny spell from Slack</h3><p>Add a configured reaction to any Slack message. Sidequestor sees it on a later tick, picks up the thread context, and performs that one-off action for you.</p></div><aside class="help-callout"><strong>No quest required</strong><p>Reaction jobs use a fast path for ad hoc work. A quest is only needed when the job turns into ongoing follow-up.</p></aside></div><div class="help-spells"><article class="help-spell"><span class="help-spell-icon" aria-hidden="true">⚡</span><div><h4><code data-reaction-role="process">loading…</code></h4><p>Handle this. Do the work and reply in the Slack thread.</p></div></article><article class="help-spell"><span class="help-spell-icon" aria-hidden="true">✎</span><div><h4><code data-reaction-role="draft">loading…</code></h4><p>Draft this. Research and prepare a reply, but leave sending to you.</p></div></article><article class="help-spell"><span class="help-spell-icon" aria-hidden="true">▣</span><div><h4><code data-reaction-role="save">loading…</code></h4><p>Remember this. Save useful context quietly, with no reply.</p></div></article><article class="help-spell"><span class="help-spell-icon" aria-hidden="true">✉</span><div><h4><code data-reaction-role="adopt">loading…</code></h4><p>Adopt this. File the message under the right quest, then reply in the thread when a response is needed.</p></div></article><article class="help-spell"><span class="help-spell-icon" aria-hidden="true">🪄</span><div><h4><code data-reaction-role="expand">loading…</code></h4><p>Expand in place. Flesh out your own message, edit it in its original location, and carry out its explicit requests or track ongoing work in a quest.</p></div></article></div><div class="help-section-label">Visible progress</div><div class="help-lifecycle" aria-label="Reaction progress: your trigger, then working, then finished or blocked"><div class="help-life-state"><i aria-hidden="true">☝</i><strong>Your trigger</strong><span>Please do this</span></div><div class="help-life-arrow" aria-hidden="true">›</div><div class="help-life-state loading"><i aria-hidden="true">⏳</i><strong><code data-reaction-role="loading">loading…</code></strong><span>Picked up and working</span></div><div class="help-life-arrow" aria-hidden="true">›</div><div class="help-life-state done"><i aria-hidden="true">✓</i><strong><code data-reaction-role="done">loading…</code></strong><span>Finished or no action needed</span></div><div class="help-life-arrow help-life-or" aria-hidden="true">or</div><div class="help-life-state blocked"><i aria-hidden="true">🕒</i><strong><code data-reaction-role="blocked">loading…</code></strong><span>Could not finish; check the dashboard</span></div></div><p class="help-footnote" id="reaction-config-note"><strong>Only one status reaction stays on the message.</strong><span id="reaction-config-status"> Multiple triggers on the same message run independently. Working stays visible while any action is queued or working; once none is working, blocked takes precedence over done. The save reaction is silent and skips status changes. Emoji names come from your Sidequestor configuration.</span></p></section></div></div></dialog>
|
|
123
123
|
<div class="toast" id="toast" role="status"></div>
|
|
124
124
|
<script nonce="__DASHBOARD_NONCE__" src="/dashboard-assets/dashboard-quest-visualizer.js"></script>
|
|
125
125
|
<script>
|
|
@@ -146,8 +146,8 @@ function mdInline(v,repo=''){
|
|
|
146
146
|
}
|
|
147
147
|
function markdown(md,repo=''){const inline=value=>mdInline(value,repo);let h='',list='';const close=()=>{if(list){h+=`</${list}>`;list=''}};for(const line of String(md||'').split('\n')){if(/^#\s/.test(line)){close();h+=`<h1>${inline(line.slice(2))}</h1>`}else if(/^##\s/.test(line)){close();h+=`<h2>${inline(line.slice(3))}</h2>`}else if(/^#{3,}\s/.test(line)){close();h+=`<h3>${inline(line.replace(/^#{3,}\s/,''))}</h3>`}else if(/^[-*]\s/.test(line)){if(list!=='ul'){close();list='ul';h+='<ul>'}h+=`<li>${inline(line.slice(2))}</li>`}else if(/^\d+\.\s/.test(line)){if(list!=='ol'){close();list='ol';h+='<ol>'}h+=`<li>${inline(line.replace(/^\d+\.\s/,''))}</li>`}else if(!line.trim())close();else{close();h+=`<p>${inline(line)}</p>`}}close();return h||'<p>No context recorded.</p>'}
|
|
148
148
|
function targetText(card){const t=card.target||{};if(t.action==='health_repair')return 'Worker issue · '+({headless:'Agent repair proposed',interactive:'Setup or sign-in needed',uncertain:'Cause needs investigation'}[t.repair_mode]||'Cause needs investigation');if(t.action==='sidequestor_upgrade')return `Sidequestor ${t.version||''} · Independent upgrade after approval`;if(t.to)return[t.to,t.subject].filter(Boolean).join(' · ');if(t.channel_id)return t.thread_ts?`${t.channel_id} · in thread`:t.channel_id;if(t.repo)return[t.repo,t.issue?'issue #'+t.issue:t.path,t.branch].filter(Boolean).join(' · ');return t.path||t.email_thread_id||'No target recorded'}
|
|
149
|
-
function reviewDestination(card){const t=card.target||{};if(['health_repair','sidequestor_upgrade'].includes(t.action))return{label:t.action==='health_repair'?'Repair mode':'Upgrade',value:targetText(card)};if(t.to)return{label:'To',value:[t.to,t.subject].filter(Boolean).join(' · ')};if(t.surface==='gmail'&&t.message_id){const audience=t.recipients||{};return{label:t.action==='reply_all'?'Gmail reply-all':'Gmail reply',value:[`message ${t.message_id}`,...(audience.to||[]).map(x=>`to ${x}`),...(audience.cc||[]).map(x=>`cc ${x}`),...(t.remove||[]).map(x=>`remove ${x}`),...(t.attachments||[]).map(a=>`attach ${a.path} (${a.size} bytes)`)].join(' · ')}}if(t.action==='file_upload')return{label:'Slack file upload',value:[`${t.filename} (${t.size} bytes)`,t.file,t.thread_ts?`${t.channel_id} · thread ${t.thread_ts}`:t.channel_id].join(' · ')};if(t.channel_id)return{label:'Slack destination',value:t.thread_ts?`${t.channel_id} · thread ${t.thread_ts}`:t.channel_id};if(t.email_thread_id)return{label:'Email thread',value:t.email_thread_id};if(t.doc_id)return{label:'Google Doc',value:t.doc_id};if(t.repo)return{label:'Repository target',value:[t.repo,t.issue?'issue #'+t.issue:t.path,t.branch].filter(Boolean).join(' · ')};if(t.path)return{label:card.action_type==='file_edit'?'File to change':'Target path',value:t.path};if(t.peer)return{label:'Recipient',value:t.peer};return{label:card.action_type==='file_edit'?'File to change':'Destination',value:'Not recorded in this request',missing:true}}
|
|
150
|
-
function reviewMessageCopy(card){if(card.target?.action==='health_repair')return{label:'What happened and how to recover',hint:'Follow the steps below first. Approval queues an agent check; it does not mean the issue is fixed.'};if(card.target?.action==='sidequestor_upgrade')return{label:'Upgrade plan',hint:'Approval hands this fixed lifecycle to an independent background job.'};if(card.target?.report_kind==='package_bug')return{label:'Bug report email to send',hint:'The agent sends this exact report only after approval; reporting does not resolve the health issue.'};
|
|
149
|
+
function reviewDestination(card){const t=card.target||{};if(t.action==='quest_setup')return{label:'Quest setup',value:card.quest_title||card.quest_id||'This quest'};if(['health_repair','sidequestor_upgrade'].includes(t.action))return{label:t.action==='health_repair'?'Repair mode':'Upgrade',value:targetText(card)};if(t.to)return{label:'To',value:[t.to,t.subject].filter(Boolean).join(' · ')};if(t.surface==='gmail'&&t.message_id){const audience=t.recipients||{};return{label:t.action==='reply_all'?'Gmail reply-all':'Gmail reply',value:[`message ${t.message_id}`,...(audience.to||[]).map(x=>`to ${x}`),...(audience.cc||[]).map(x=>`cc ${x}`),...(t.remove||[]).map(x=>`remove ${x}`),...(t.attachments||[]).map(a=>`attach ${a.path} (${a.size} bytes)`)].join(' · ')}}if(t.action==='file_upload')return{label:'Slack file upload',value:[`${t.filename} (${t.size} bytes)`,t.file,t.thread_ts?`${t.channel_id} · thread ${t.thread_ts}`:t.channel_id].join(' · ')};if(t.channel_id)return{label:'Slack destination',value:[t.channel_name||t.audience,t.thread_ts?`${t.channel_id} · thread ${t.thread_ts}`:t.channel_id].filter(Boolean).join(' · ')};if(t.email_thread_id)return{label:'Email thread',value:t.email_thread_id};if(t.doc_id)return{label:'Google Doc',value:t.doc_id};if(t.repo)return{label:'Repository target',value:[t.repo,t.issue?'issue #'+t.issue:t.path,t.branch].filter(Boolean).join(' · ')};if(t.path)return{label:card.action_type==='file_edit'?'File to change':'Target path',value:t.path};if(t.peer)return{label:'Recipient',value:t.peer};return{label:card.action_type==='file_edit'?'File to change':'Destination',value:'Not recorded in this request',missing:true}}
|
|
150
|
+
function reviewMessageCopy(card){if(card.target?.action==='quest_setup')return{label:'Setup plan to approve',hint:'Answer the questions using Request change, then approve the resolved plan to start monitoring. Close issue stops setup.'};if(card.target?.action==='health_repair')return{label:'What happened and how to recover',hint:'Follow the steps below first. Approval queues an agent check; it does not mean the issue is fixed.'};if(card.target?.action==='sidequestor_upgrade')return{label:'Upgrade plan',hint:'Approval hands this fixed lifecycle to an independent background job.'};if(card.target?.report_kind==='package_bug')return{label:'Bug report email to send',hint:'The agent sends this exact report only after approval; reporting does not resolve the health issue.'};if(['slack_message','slack_reply'].includes(card.action_type))return{label:'Message to send',hint:'Approval permits this message; Slack must also be connected. If execution reports missing sign-in, run setup with this workspace explicitly selected and follow the Slack connection steps. If delivery is uncertain, inspect Slack before retrying.'};const message=card.action_type==='email_reply';if(message)return{label:'Message to send',hint:'The agent will send this draft to the destination above after approval.'};if(card.action_type==='file_edit')return{label:'Action for the agent',hint:'Approval asks the agent to carry out this file action.'};return{label:'Proposed external action',hint:'Approval asks the agent to carry out this action.'}}
|
|
151
151
|
function reviewAlert(title,body,at,kind,repo=''){return`<div class="review-alert ${kind}" role="note"><div class="review-alert-head"><strong>${esc(title)}</strong>${at?`<time datetime="${esc(at)}">${esc(watchTime(at))}</time>`:''}</div><div class="rich-copy">${markdown(body,repo)}</div></div>`}
|
|
152
152
|
function pill(text,kind='neutral'){return`<span class="pill ${esc(kind)}">${esc(text)}</span>`}
|
|
153
153
|
const watchLabels={approval:'Approval',email:'Email search',github_issue:'GitHub issues',github_pr:'GitHub pull requests',jira:'Jira search',notion_page:'Notion page',notion_data_source:'Notion data source',notion_comments:'Notion comments',schedule:'Schedule',slack_channel:'Slack channel',slack_dm:'Slack direct message',slack_mention:'Slack mentions',slack_thread:'Slack thread'};
|
|
@@ -175,7 +175,7 @@ function refreshRelativeAges(){$$('[data-relative-ts]').forEach(el=>{const text=
|
|
|
175
175
|
function matchingWatchLink(w){const reason=String(w.reason||'').trim();if(!reason)return null;const matches=(state.detail?.open_items?.threads||[]).filter(x=>x.type===w.type&&String(x.reason||'').trim()===reason&&safeUrl(x.link_url||x.slack_url||''));return matches.length===1?matches[0]:null}
|
|
176
176
|
function watchLink(w){const direct=[w.link_url,w.slack_url,w.permalink,w.url].map(safeUrl).find(Boolean);if(direct)return{url:direct,kind:w.link_kind||''};const related=matchingWatchLink(w);if(related)return{url:safeUrl(related.link_url||related.slack_url),kind:related.link_kind||''};const type=String(w.type||'').toLowerCase(),repo=w.repo||w.github_repo;if(repo&&repo.includes('/')&&(type==='github_issue'||type==='github_pr')){const suffix=type==='github_issue'?'issues':'pulls',url=safeUrl(`https://github.com/${repo}/${suffix}`);if(url)return{url,kind:'github'}}return null}
|
|
177
177
|
function notionCoverage(w){const c=w.notion_coverage;if(!c)return'';const last=c.last_complete_scan?watchTime(c.last_complete_scan):'never',status=c.status||'unknown',parts=[`Scan: ${status}`,`Last complete: ${last}`];if(c.entities_scanned!==undefined)parts.push(`${c.entities_scanned}/${c.max_entities??'—'} entities`);if(c.pending_tasks!==undefined)parts.push(`${c.pending_tasks} tasks remaining`);if(c.subpage_depth!==undefined)parts.push(`Subpage depth: ${c.subpage_depth}`);if(c.request_limit!==undefined)parts.push(`Budget: ${c.request_limit} requests / ${c.time_limit_seconds}s per tick`);if(c.include_subpage_content!==undefined)parts.push(`Subpage content: ${c.include_subpage_content?'on':'off'}`);if(c.include_subpage_comments!==undefined)parts.push(`Subpage comments: ${c.include_subpage_comments?'on':'off'}`);if(c.reason)parts.push(c.reason);return`<div class="watch-target">${parts.map(esc).join(' · ')}</div>`}
|
|
178
|
-
function watchRow(w){const type=String(w.type||'').toLowerCase(),label=watchLabel(w),target=watchTarget(w),reason=String(w.reason||'').trim(),filters=watchFilters(w),link=watchLink(w),meta=[];if(w.ephemeral===true)meta.push(pill('temporary','reviewed'));if(w.expires_ts)meta.push(`<span class="watch-stat">expires ${esc(watchTime(w.expires_ts))}</span>`);if(w.next_fire_ts)meta.push(`<span class="watch-stat">next ${esc(watchTime(w.next_fire_ts))}</span>`);if(w.last_checked_ts&&!type.startsWith('notion_'))meta.push(watchAgeMarkup(w.last_checked_ts));return`<article class="watch"><div class="watch-head"><strong class="watch-label">${esc(label)}</strong><span class="watch-kind">${esc(type||'watch')}</span></div>${link?`<a class="watch-source" href="${esc(link.url)}" target="_blank" rel="noopener">${link.kind==='slack'?'Open in Slack':link.kind==='github'?'Open in GitHub':link.kind==='jira'?'Open in Jira':link.kind==='notion'?'Open in Notion':'Open source'}</a>`:''}<div class="watch-target">${esc(target)}</div>${reason?`<div class="watch-reason">${esc(reason)}</div>`:''}${filters?`<div class="watch-filters">${esc(filters)}</div>`:''}${notionCoverage(w)}${meta.length?`<div class="watch-meta">${meta.join('')}</div>`:''}</article>`}
|
|
178
|
+
function watchRow(w){const type=String(w.type||'').toLowerCase(),label=watchLabel(w),target=watchTarget(w),reason=String(w.reason||'').trim(),filters=watchFilters(w),link=watchLink(w),meta=[];if(w.monitoring_enabled===false)meta.push(pill('inactive','neutral'));if(w.ephemeral===true)meta.push(pill('temporary','reviewed'));if(w.expires_ts)meta.push(`<span class="watch-stat">expires ${esc(watchTime(w.expires_ts))}</span>`);if(w.next_fire_ts)meta.push(`<span class="watch-stat">next ${esc(watchTime(w.next_fire_ts))}</span>`);if(w.last_checked_ts&&!type.startsWith('notion_'))meta.push(watchAgeMarkup(w.last_checked_ts));return`<article class="watch"><div class="watch-head"><strong class="watch-label">${esc(label)}</strong><span class="watch-kind">${esc(type||'watch')}</span></div>${link?`<a class="watch-source" href="${esc(link.url)}" target="_blank" rel="noopener">${link.kind==='slack'?'Open in Slack':link.kind==='github'?'Open in GitHub':link.kind==='jira'?'Open in Jira':link.kind==='notion'?'Open in Notion':'Open source'}</a>`:''}<div class="watch-target">${esc(target)}</div>${reason?`<div class="watch-reason">${esc(reason)}</div>`:''}${filters?`<div class="watch-filters">${esc(filters)}</div>`:''}${w.monitoring_enabled===false?'<div class="watch-filters">Not checked while this connector is disabled. Its saved position is retained.</div>':''}${notionCoverage(w)}${meta.length?`<div class="watch-meta">${meta.join('')}</div>`:''}</article>`}
|
|
179
179
|
function actionLabel(a){return{review:'Execute',revise:'Request change',edit:'Save edit',cancel:'Close issue',undo:'Undo',reclaim:'Reclaim'}[a]||a}
|
|
180
180
|
function actionNoun(t){return{slack_message:'Slack message',slack_reply:'Slack reply',email_reply:'Email',file_edit:'File edit',remote_request:'External action',manual_instruction:'Your instruction',prompt:'Your instruction',stranded_watch:'Stranded watch'}[t]||(t||'action').replaceAll('_',' ')}
|
|
181
181
|
function surfaceOf(item){const kind=String(item.link_kind||'').toLowerCase(),type=`${item.action_type||''} ${item.event||''}`.toLowerCase(),target=item.target||{};if(['slack','jira','github','email'].includes(kind))return kind;if(type.includes('slack')||type.includes('dm_')||type.includes('message_sent')||type.includes('reply_sent'))return'slack';if(type.includes('email')||target.email_thread_id||(target.to&&target.subject))return'email';if(target.jira||target.issue_key||target.jql)return'jira';if(target.repo||target.pr||target.github_issue)return'github';if(type.includes('file_edit'))return'repository';if(typeof target==='string'&&/^[CDG][A-Z0-9]+$/.test(target))return'slack';return''}
|
|
@@ -185,15 +185,17 @@ function reviewPreview(text,repo=''){return !String(text||'').trim()?'<p class="
|
|
|
185
185
|
function setReviewMode(card,source=false){const field=card.querySelector('[data-message]'),preview=card.querySelector('[data-message-preview]'),toggle=card.querySelector('[data-review-mode]');if(!field||!preview||!toggle)return;card.dataset.reviewMode=source?'source':'preview';field.hidden=!source;preview.hidden=source;preview.htmlOnce=reviewPreview(field.value,card.dataset.reviewRepo);toggle.textContent=source?'Preview':field.readOnly?'View source':'Edit';toggle.setAttribute('aria-pressed',String(source))}
|
|
186
186
|
function approvalCard(card,compact=false){
|
|
187
187
|
const acts=card.available_actions||[],editable=card.target?.action!=='sidequestor_upgrade'&&(acts.includes('review')||acts.includes('edit')),destination=reviewDestination(card),copy=reviewMessageCopy(card),link=safeUrl(card.link_url||'');
|
|
188
|
-
const
|
|
189
|
-
const
|
|
188
|
+
const sourceRaw=card.source_url||card.target?.source_url,source=sourceRaw?safeUrl(sourceRaw):null,destinationLink=card.destination_url?safeUrl(card.destination_url):card.link_role!=='source'&&card.link_url?link:null;
|
|
189
|
+
const related=destinationLink?`<span class="review-related"><a href="${esc(destinationLink)}" target="_blank" rel="noopener">Open destination</a></span>`:'';
|
|
190
|
+
const sourceBlock=`<div class="review-destination review-source"><span class="review-destination-label">Prior context</span>${source?`<a href="${esc(source)}" target="_blank" rel="noopener">Open Source</a>`:'<span class="muted">Source link not recorded</span>'}</div>`;
|
|
191
|
+
const destinationBlock=`<div class="review-destination"><span class="review-destination-label">${esc(destination.label)}</span><span class="review-destination-value${destination.missing?' missing':''}">${esc(destination.value)}</span>${related}</div>${sourceBlock}`;
|
|
190
192
|
const alerts=[card.processing_error?reviewAlert('Latest action failure',card.processing_error,card.processing_error_at,'latest',card.target?.repo):'',card.risk_reason?reviewAlert(card.processing_error?'Earlier review concern':'Review concern',card.risk_reason,card.created_at,'context',card.target?.repo):''].join('');
|
|
191
|
-
return`<article class="review-card ${card.stalled||card.processing_error?'stalled':''}" data-card="${esc(card.id)}" data-review-mode="preview" data-review-repo="${esc(card.target?.repo||'')}"><div class="card-head"><div class="card-title">${esc(actionNoun(card.action_type))}</div><div class="state-row">${pill(card.processing_error?'action failed':(card.status||'unknown').replaceAll('_',' '),card.processing_error?'blocked':card.stalled?'stalled':card.status||'neutral')}${card.human_edited?pill('edited','info'):''}<span class="card-age">${ago(card.processing_error_at||card.created_at)}</span></div></div>${destinationBlock}${alerts}${card.context?`<div class="field-label">Context</div><div class="markdown rich-copy review-context">${markdown(card.context,card.target?.repo)}</div>`:''}${conversation(card)}<div class="review-copy-head"><span class="field-label">${esc(copy.label)}</span><button type="button" class="button" data-review-mode aria-pressed="false">${editable?'Edit':'View source'}</button></div><p class="review-message-hint">${esc(copy.hint)}${destination.missing?' Check the related source for the exact destination before execution.':''}${['slack_message','slack_reply','email_reply'].includes(card.action_type)?' Formatting is approximate; the message is sent using the source text.':''}</p><div class="markdown rich-copy review-preview" data-message-preview>${reviewPreview(card.message_text||'',card.target?.repo)}</div><textarea data-message aria-label="${esc(copy.label)} source" hidden ${editable?'':'readonly'}>${esc(card.message_text||'')}</textarea>${card.target?.action!=='sidequestor_upgrade'&&(acts.includes('revise')||acts.includes('review'))?'<label class="field-label">Instruction for the agent (optional on Execute, required on Request change)</label><textarea class="review-note" data-note placeholder="e.g. “send this to the other reviewer instead” · “show me the updated draft first”"></textarea>':''}<div class="card-actions">${acts.map(a=>`<button class="button ${a==='review'?'primary':a==='cancel'?'danger':''}" data-approval-action="${esc(a)}"${a==='review'?' title="Queue this reviewed action for execution by the worker on the next tick"':''}>${esc(actionLabel(a))}</button>`).join('')}</div><div class="inline-status" data-card-status></div>${technicalReview(card)?`<div class="review-troubleshoot"><button type="button" class="quiet-action" data-troubleshoot="${esc(card.id)}" title="Continue diagnosing this issue in your selected app using the existing local logs. Nothing is executed or closed by opening the app.">Troubleshoot ↗</button></div>`:''}</article>`
|
|
193
|
+
return`<article class="review-card ${card.stalled||card.processing_error?'stalled':''}" data-card="${esc(card.id)}" data-review-mode="preview" data-review-repo="${esc(card.target?.repo||'')}"><div class="card-head"><div class="card-title">${esc(card.target?.action==='quest_setup'?'Quest setup':actionNoun(card.action_type))}</div><div class="state-row">${pill(card.processing_error?'action failed':(card.status||'unknown').replaceAll('_',' '),card.processing_error?'blocked':card.stalled?'stalled':card.status||'neutral')}${card.human_edited?pill('edited','info'):''}<span class="card-age">${ago(card.processing_error_at||card.created_at)}</span></div></div>${destinationBlock}${alerts}${card.context?`<div class="field-label">Context</div><div class="markdown rich-copy review-context">${markdown(card.context,card.target?.repo)}</div>`:''}${conversation(card)}<div class="review-copy-head"><span class="field-label">${esc(copy.label)}</span><button type="button" class="button" data-review-mode aria-pressed="false">${editable?'Edit':'View source'}</button></div><p class="review-message-hint">${esc(copy.hint)}${destination.missing?' Check the related source for the exact destination before execution.':''}${['slack_message','slack_reply','email_reply'].includes(card.action_type)?' Formatting is approximate; the message is sent using the source text.':''}</p><div class="markdown rich-copy review-preview" data-message-preview>${reviewPreview(card.message_text||'',card.target?.repo)}</div><textarea data-message aria-label="${esc(copy.label)} source" hidden ${editable?'':'readonly'}>${esc(card.message_text||'')}</textarea>${card.target?.action!=='sidequestor_upgrade'&&(acts.includes('revise')||acts.includes('review'))?'<label class="field-label">Instruction for the agent (optional on Execute, required on Request change)</label><textarea class="review-note" data-note placeholder="e.g. “send this to the other reviewer instead” · “show me the updated draft first”"></textarea>':''}<div class="card-actions">${acts.map(a=>`<button class="button ${a==='review'?'primary':a==='cancel'?'danger':''}" data-approval-action="${esc(a)}"${a==='review'?' title="Queue this reviewed action for execution by the worker on the next tick"':''}>${esc(actionLabel(a))}</button>`).join('')}</div><div class="inline-status" data-card-status></div>${technicalReview(card)?`<div class="review-troubleshoot"><button type="button" class="quiet-action" data-troubleshoot="${esc(card.id)}" title="Continue diagnosing this issue in your selected app using the existing local logs. Nothing is executed or closed by opening the app.">Troubleshoot ↗</button></div>`:''}</article>`
|
|
192
194
|
}
|
|
193
195
|
function queuedFor(qid){return(state.control.queued||[]).filter(x=>!qid||x.quest_id===qid)}
|
|
194
196
|
function attentionFor(qid){return(state.control.attention||[]).filter(x=>!qid||x.quest_id===qid)}
|
|
195
197
|
function isRunning(q){return triagePhase(state.control)==='dispatching'&&(state.control.live?.targets||[]).some(t=>t===q.id||String(t).includes(q.id))}
|
|
196
|
-
function isInitialising(q){return q.sidequestor_bootstrap===true}function questGroup(q){if(isInitialising(q))return'Initialising';const a=attentionFor(q.id);if(a.some(x=>x.kind==='review'))return'Needs you';if(q.status==='blocked'||q.last_blocked||(q.misconfigured_watches||[]).length)return'Needs a fix';if((q.backoff_watches||[]).length)return'Investigate';if(isRunning(q))return'Running';return'Watching'}
|
|
198
|
+
function isInitialising(q){return q.sidequestor_bootstrap===true}function questGroup(q){if(isInitialising(q))return'Initialising';const a=attentionFor(q.id);if(a.some(x=>x.kind==='review'))return'Needs you';if(q.status==='blocked'||q.last_blocked||(q.misconfigured_watches||[]).length)return'Needs a fix';if((q.backoff_watches||[]).length)return'Investigate';if(isRunning(q))return'Running';if(q.all_watches_inactive===true)return'Inactive';return'Watching'}
|
|
197
199
|
function renderMotion(moving){window.SidequestorBranding?.setMoving(moving);const stream=$('#motion-stream'),latest=(state.control.activity||[])[0],key=latest&&(latest.id||`${latest.quest_id}:${latest.timestamp}:${latest.event}`);stream.classList.toggle('active',moving);stream.classList.toggle('paused',document.hidden);if(moving&&motionEventKey&&key&&key!==motionEventKey){stream.classList.remove('event');void stream.offsetWidth;stream.classList.add('event');clearTimeout(motionFlashTimer);motionFlashTimer=setTimeout(()=>stream.classList.remove('event'),900)}motionEventKey=key||motionEventKey}
|
|
198
200
|
function triagePhase(control,now=Date.now()){const t=control?.triage||{},live=control?.live||{},started=Date.parse(t.tick_started_utc),completed=Date.parse(t.last_triage_completed_utc),workerStarted=Date.parse(live.started_at),open=Number.isFinite(started)&&(!Number.isFinite(completed)||started>completed),ceiling=Number(control?.liveness?.hard_tick_sec)||6300,stallMs=(Number(control?.liveness?.stall_sec)||STALE_MS/1000)*1000,matching=open&&live.lifecycle&&Number.isFinite(workerStarted)&&workerStarted>=started;if(open&&now-started>ceiling*1000)return'tick_overdue';if(matching){if(live.state==='exited'){const ended=Date.parse(live.ended_at);if(Number.isFinite(ended)&&ended>=started&&now-ended>=-30000&&now-ended<=300000)return'dispatch_gap'}if(live.stale)return'worker_stale';if(live.overdue)return'worker_overdue';if(live.running)return'dispatching'}return!Number.isFinite(completed)||now-completed>stallMs?'stale':'live'}
|
|
199
201
|
function renderSubhead(phase,last,live){const el=$('#subhead'),readiness=(state.control.attention||[]).find(x=>String(x.id||'').startsWith('worker-readiness:'));if(readiness){const reason=String(readiness.detail||'Worker connection needs attention').replace(/\s*Run sq setup\.?\s*$/i,'');const path=state.control.workspace?.path,absolute=typeof path==='string'&&path.startsWith('/'),command=absolute?"sq --workspace '"+path.replaceAll("'","'\"'\"'")+"' setup":'sq --workspace . setup';el.innerHTML=`${esc(reason)} Open Terminal and run <code>${esc(command)}</code> ${absolute?'from any folder':'from this workspace’s folder'}.`;return}const targets=(live?.targets||[]).join(', ')||'an unreported target';if(phase==='dispatching'){el.textContent=`Worker handling ${targets} for ${ago(live.started_at)} · heartbeat ${ago(live.heartbeat_at)} ago.`;return}if(phase==='dispatch_gap'){el.textContent=`Finishing a dispatch and preparing the next worker.`;return}if(phase==='worker_stale'){el.textContent=`Worker heartbeat stopped for ${targets}.`;return}if(phase==='worker_overdue'){el.textContent=`Worker handling ${targets} exceeded its time limit.`;return}if(phase==='tick_overdue'){el.textContent='Triage tick ran past its dispatch ceiling. Check the worker and triage logs.';return}const age=document.createElement('span');age.className=`live-age${phase==='stale'?' stale':''}`;age.textContent=last?ago(last):'unknown';el.replaceChildren(phase==='stale'?'Last completed ':'Last triage completed ',age,' ago.')}
|
|
@@ -201,19 +203,19 @@ function connectionStatus(control,now=Date.now()){const phase=triagePhase(contro
|
|
|
201
203
|
function setConnection(status){const conn=$('#connection');conn.className=status.className;conn.querySelector('span').textContent=status.label}
|
|
202
204
|
|
|
203
205
|
function renderSummary(){const c=state.control,t=c.triage||{},last=t.last_triage_completed_utc,phase=triagePhase(c),stale=phase==='stale',workerProblem=['worker_stale','worker_overdue','tick_overdue'].includes(phase),dispatching=phase==='dispatching'||phase==='dispatch_gap',needs=attentionFor().filter(x=>x.priority==='high').length,investigating=attentionFor().filter(x=>x.priority!=='high').length,queue=queuedFor().length,moving=!stale&&!workerProblem&&!needs;$('#needs-count').textOnce=needs;$('#queue-count').textOnce=queue;const running=dispatching,worker=$('#worker-state'),workerMode=workerProblem?'stale':running?'running':'idle';if(worker.dataset.state!==workerMode){worker.dataset.state=workerMode;worker.htmlOnce=workerProblem?'⚠️':running?'<i class="spinner"></i>':'😴';worker.className=running||workerProblem?'worker-state':'worker-state asleep';}$('#worker-label').textOnce=phase==='tick_overdue'?'Tick overdue':phase==='worker_overdue'?'Worker overdue':phase==='worker_stale'?'Worker heartbeat stale':phase==='dispatch_gap'?'Next worker starting':running?'Worker is running':'Worker is idle';$('#queue-label').textOnce=queue===1?'action queued to execute':'actions queued to execute';worker.title=$('#worker-metric').ariaLabel=workerProblem?'Worker needs attention':running?'Worker running':'No worker running';$('#quest-total').textOnce=`${c.quests.length} active`;$('#headline').textOnce=stale?'Triage loop needs attention':phase==='tick_overdue'?'Triage tick exceeded its time limit':phase==='worker_stale'?'Worker heartbeat stopped':phase==='worker_overdue'?'Dispatch exceeded its time limit':dispatching?'Dispatch in progress':needs?`${needs} item${needs===1?' needs':'s need'} your call`:investigating?`${investigating} watch${investigating===1?' is':'es are'} retrying`:'Everything is moving';renderMotion(moving);renderSubhead(phase,last,c.live);setConnection(connectionStatus(c))}
|
|
204
|
-
function renderQuestList(){const groups={Initialising:[],'Needs you':[],'Needs a fix':[],Investigate:[],Running:[],Watching:[]};state.control.quests.forEach(q=>groups[questGroup(q)].push(q));const queued=queuedFor();$('#quest-list').htmlOnce=`${queued.length?`<section class="section"><div class="section-label">Queued to run ${pill(queued.length,'reviewed')}</div>${queued.map(q=>attentionRow(q,true)).join('')}</section>`:''}${Object.entries(groups).filter(([,v])=>v.length).map(([name,qs])=>`<section class="section"><div class="section-label">${name} ${pill(qs.length)}</div>${qs.map(q=>{const reviewCount=attentionFor(q.id).filter(x=>x.kind==='review'&&['slack_message','email_reply'].includes(x.approval?.action_type||'slack_message')).length,issue=name==='Needs a fix'?(q.misconfigured_watches||[])[0]:name==='Investigate'?(q.backoff_watches||[])[0]:null,detail=issue?`${issue.type||'watch'} · ${issue.reason||issue.last_error||issue.last_status||'Automatic retry scheduled'}`:name==='Watching'&&(q.ratelimited_watches||[]).length?`Checks briefly delayed · ${state.control.slack_read_retry_at&&(q.ratelimited_watches||[]).some(w=>String(w.type||'').startsWith('slack_')&&/429|ratelimit|rate limit/i.test(w.reason||w.last_error||''))?'retry after '+new Date(state.control.slack_read_retry_at*1000).toLocaleString():'retrying automatically'}`:attentionFor(q.id)[0]?.detail||q.last_action?.note||'Monitoring for activity',signal=name==='Running'?'running':name==='Needs a fix'?'action':name==='Investigate'?'uncertain':name==='Needs you'?'review':'';return`<button class="quest${name==='Initialising'?' initialising':''}" data-quest="${esc(q.id)}"${name==='Initialising'?' title="Waiting for the first worker run, still openable"':''}><i class="signal ${signal}"></i><span><span class="quest-title-row"><span class="quest-name" title="${esc(q.title)}">${esc(q.title)}</span>${reviewCount>1?`<span class="pill pending_review quest-review-count" aria-label="${reviewCount} messages to review" title="${reviewCount} messages to review">${reviewCount}</span>`:''}</span><span class="quest-detail">${name==='Initialising'?'Waiting for the first worker run…':esc(detail)}</span></span><span class="time">${ago(q.last_action?.ts||q.last_seen_ts)}</span></button>`}).join('')}</section>`).join('')}`}
|
|
205
|
-
function loops(detail){const o=detail.open_items||{},out=[];(o.scheduled||[]).forEach(x=>out.push(['Follow-up',x.reason]));(o.threads||[]).forEach(x=>out.push(['Watching',x.reason||x.query]));(o.commitments||[]).forEach(x=>out.push(['Commitment',x.text||x.note]));return out}
|
|
206
|
+
function renderQuestList(){const groups={Initialising:[],'Needs you':[],'Needs a fix':[],Investigate:[],Running:[],Inactive:[],Watching:[]};state.control.quests.forEach(q=>groups[questGroup(q)].push(q));const queued=queuedFor();$('#quest-list').htmlOnce=`${state.control.reactions_enabled===false?'<p class="muted" role="note">Slack reaction automation is off because local Slack checking is disabled. Trigger emojis will not start work.</p>':''}${queued.length?`<section class="section"><div class="section-label">Queued to run ${pill(queued.length,'reviewed')}</div>${queued.map(q=>attentionRow(q,true)).join('')}</section>`:''}${Object.entries(groups).filter(([,v])=>v.length).map(([name,qs])=>`<section class="section"><div class="section-label">${name} ${pill(qs.length)}</div>${qs.map(q=>{const reviewCount=attentionFor(q.id).filter(x=>x.kind==='review'&&['slack_message','email_reply'].includes(x.approval?.action_type||'slack_message')).length,issue=name==='Needs a fix'?(q.misconfigured_watches||[])[0]:name==='Investigate'?(q.backoff_watches||[])[0]:null,detail=name==='Inactive'?'All stored watches are inactive; saved positions are retained.':issue?`${issue.type||'watch'} · ${issue.reason||issue.last_error||issue.last_status||'Automatic retry scheduled'}`:name==='Watching'&&(q.ratelimited_watches||[]).length?`Checks briefly delayed · ${state.control.slack_read_retry_at&&(q.ratelimited_watches||[]).some(w=>String(w.type||'').startsWith('slack_')&&/429|ratelimit|rate limit/i.test(w.reason||w.last_error||''))?'retry after '+new Date(state.control.slack_read_retry_at*1000).toLocaleString():'retrying automatically'}`:attentionFor(q.id)[0]?.detail||q.last_action?.note||'Monitoring for activity',signal=name==='Running'?'running':name==='Needs a fix'?'action':name==='Investigate'?'uncertain':name==='Needs you'?'review':'';return`<button class="quest${name==='Initialising'?' initialising':''}" data-quest="${esc(q.id)}"${name==='Initialising'?' title="Waiting for the first worker run, still openable"':''}><i class="signal ${signal}"></i><span><span class="quest-title-row"><span class="quest-name" title="${esc(q.title)}">${esc(q.title)}</span>${reviewCount>1?`<span class="pill pending_review quest-review-count" aria-label="${reviewCount} messages to review" title="${reviewCount} messages to review">${reviewCount}</span>`:''}</span><span class="quest-detail">${name==='Initialising'?'Waiting for the first worker run…':esc(detail)}</span></span><span class="time">${ago(q.last_action?.ts||q.last_seen_ts)}</span></button>`}).join('')}</section>`).join('')}`}
|
|
207
|
+
function loops(detail){const o=detail.open_items||{},out=[];(o.scheduled||[]).forEach(x=>out.push(['Follow-up',x.reason]));(o.threads||[]).forEach(x=>out.push([x.monitoring_enabled===false?'Inactive':'Watching',x.reason||x.query]));(o.commitments||[]).forEach(x=>out.push(['Commitment',x.text||x.note]));return out}
|
|
206
208
|
function issueCards(issues){const grouped=new Map;(issues||[]).forEach(x=>{const key=[x.severity,x.title,x.watch_type,x.cause,x.next].join('|');if(grouped.has(key))grouped.get(key).count++;else grouped.set(key,{...x,count:1})});return[...grouped.values()].map(x=>{const severity=['action','uncertain','transient'].includes(x.severity)?x.severity:'uncertain',icon={action:'!',uncertain:'?',transient:'↻'}[severity],label={action:'Action needed',uncertain:'Investigate',transient:'Automatic retry'}[severity];return`<article class="issue-card ${severity}"><span class="issue-icon" aria-hidden="true">${icon}</span><div><div class="issue-head"><strong>${esc(x.title)}</strong>${pill(label,severity==='action'?'blocked':severity==='uncertain'?'high':'neutral')}${pill(x.watch_type,'neutral')}</div><p class="issue-cause">${esc(x.cause)}</p><p class="issue-next"><b>Next</b> · ${esc(x.next)}</p>${x.count>1?`<div class="issue-more">${x.count} watches with this issue</div>`:''}</div></article>`}).join('')}
|
|
207
209
|
function stateLabel(status){return{pending_review:'Waiting on you',needs_reply:'Back with the agent to revise',reviewed:'Queued for the next tick',executing:'Sending now',cancelled:'Cancelled'}[status]||(status||'').replaceAll('_',' ')}
|
|
208
210
|
function usefulApprovalPurpose(a){const boilerplate=/allow[_ -]?send|send(?:ing)? (?:is )?(?:disabled|off)|draft[- ]only/i;return[a.context,a.message_text,targetText(a)].find(v=>typeof v==='string'&&v.trim()&&!boilerplate.test(v))||targetText(a)}
|
|
209
211
|
function attentionRow(item,queued=false){const a=item.approval||item,status=a.status||'pending_review',waiting=status==='pending_review',quest=a.quest_title||a.quest_id||'Unknown quest',purpose=a.processing_error||(queued?usefulApprovalPurpose(a):(a.risk_reason||item.detail||targetText(a)));return`<button class="attention-row ${waiting?'':'settled'}" data-open-review="${esc(a.id)}"><span><strong>${esc(queued?quest:actionNoun(a.action_type))}</strong><span class="queue-purpose">${queued?`<b>${esc(actionNoun(a.action_type))}</b> · `:''}${esc(purpose)}</span></span><span class="state-row">${pill(a.processing_error?'Action failed':stateLabel(status),a.processing_error?'blocked':status)}${ageMarkup(a.processing_error_at||a.reviewed_at||a.created_at,'card-age')}</span></button>`}
|
|
210
|
-
function renderFocus(){const d=state.detail;if(!state.selected||!d||d.id!==state.selected)return;const meta=d.meta||{},queued=queuedFor(d.id),reviews=attentionFor(d.id).filter(x=>x.approval),blocked=d.open_items?.blocked||(meta.status==='blocked'?{reason:'This quest is blocked.'}:null),issues=d.open_items?.watch_issues||[],open=loops(d);$('#quest-focus-content').htmlOnce=`<header class="focus-head"><button class="back" data-back>‹ All quests</button><h2>${esc(meta.title||d.id)}</h2><div class="state-row">${pill(meta.status||'active',meta.status||'active')}${pill((meta.priority||'normal')+' priority',meta.priority||'normal')}${sendPermissionControl(meta)}${window.SQQuestVisualizer?'<button type="button" class="button" data-visualise-quest>Visualise quest</button>':''}</div></header><div class="focus-body">${reviews.length||queued.length||blocked?`<section class="block"><h3>Needs your call</h3>${reviews.map(x=>attentionRow(x)).join('')}${blocked?`<div class="risk">${esc(blocked.reason||'This quest is blocked.')}</div>`:''}${queued.map(x=>attentionRow(x,true)).join('')}</section>`:''}${issues.length?`<section class="block"><h3>Watcher status</h3>${issueCards(issues)}</section>`:''}<section class="block"><h3>Context</h3><div class="markdown">${markdown(d.context_md)}</div></section><section class="block"><h3>What it watches</h3>${(d.watches||[]).map(watchRow).join('')||'<div class="muted">No watches.</div>'}</section><section class="block"><h3>Open loops</h3>${open.map(([k,v])=>`<div class="loop"><strong>${esc(k)}</strong><span>${esc(v||'')}</span></div>`).join('')||'<div class="muted">No active follow-ups.</div>'}</section></div>`}
|
|
212
|
+
function renderFocus(){const d=state.detail;if(!state.selected||!d||d.id!==state.selected)return;const meta=d.meta||{},queued=queuedFor(d.id),reviews=attentionFor(d.id).filter(x=>x.approval),blocked=d.open_items?.blocked||(meta.status==='blocked'?{reason:'This quest is blocked.'}:null),issues=d.open_items?.watch_issues||[],open=loops(d);$('#quest-focus-content').htmlOnce=`<header class="focus-head"><button class="back" data-back>‹ All quests</button><h2>${esc(meta.title||d.id)}</h2><div class="state-row">${pill(meta.status||'active',meta.status||'active')}${pill((meta.priority||'normal')+' priority',meta.priority||'normal')}${sendPermissionControl(meta)}${window.SQQuestVisualizer?'<button type="button" class="button" data-visualise-quest>Visualise quest</button>':''}</div></header><div class="focus-body">${reviews.length||queued.length||blocked?`<section class="block"><h3>Needs your call</h3>${reviews.map(x=>attentionRow(x)).join('')}${blocked?`<div class="risk">${esc(blocked.reason||'This quest is blocked.')}</div>`:''}${queued.map(x=>attentionRow(x,true)).join('')}</section>`:''}${issues.length?`<section class="block"><h3>Watcher status</h3>${issueCards(issues)}</section>`:''}<section class="block"><h3>Context</h3><div class="markdown">${markdown(d.context_md)}</div></section><section class="block"><h3>What it watches</h3>${d.monitoring?.all_watches_inactive?'<p class="muted">No active monitoring: all stored watches are disabled. Their saved positions are retained.</p>':''}${(d.watches||[]).map(watchRow).join('')||'<div class="muted">No watches.</div>'}</section><section class="block"><h3>Open loops</h3>${open.map(([k,v])=>`<div class="loop"><strong>${esc(k)}</strong><span>${esc(v||'')}</span></div>`).join('')||'<div class="muted">No active follow-ups.</div>'}</section></div>`}
|
|
211
213
|
function renderReviewDialog(){const dialog=$('#review-dialog'),shell=$('#review-dialog-shell');if(!state.reviewOpen){if(dialog.open)dialog.close();return}const card=[...(state.control.attention||[]).map(x=>x.approval).filter(Boolean),...(state.control.queued||[])].find(x=>x.id===state.reviewOpen);if(!card){state.reviewOpen=null;if(dialog.open)dialog.close();return}shell.htmlOnce=`<div class="review-dialog-head"><div><div class="eyebrow">Manual review</div><h2>${esc(card.quest_title||card.quest_id)}</h2></div><button type="button" class="icon-button" data-close-review aria-label="Close">✕</button></div><div class="review-dialog-body">${approvalCard(card)}</div>`;if(!dialog.open)dialog.showModal()}
|
|
212
214
|
function closeReviewDialog(){state.reviewOpen=null;const dialog=$('#review-dialog');if(dialog.open)dialog.close()}
|
|
213
|
-
function normalizeTimeline(e,q){const event=e.event||'note',actor=event==='info_received'?'external':['message_sent','reply_sent','dm_sent','email_replied','draft_posted','executed'].includes(event)?'agent':'system';return{id:`${q.id}:${e.ts}:${event}`,timestamp:e.ts,actor,event,action:event.replaceAll('_',' '),outcome:'recorded',risk:event==='blocked'?'alert':'normal',target:e.channel_id||'',detail:e.message_text||e.note||e.reason||'',quest_id:q.id,quest_title:q.title,link_url:e.link_url||e.slack_url,link_kind:e.link_kind,action_type:e.action_type}}
|
|
214
|
-
function trailEvents(){if(!state.selected)return state.control.activity||[];const q=state.control.quests.find(x=>x.id===state.selected),timeline=(state.detail?.timeline||[]).map(e=>normalizeTimeline(e,q)),projected=(state.control.activity||[]).filter(e=>e.quest_id===state.selected),map=new Map;[...projected,...timeline].forEach(e=>map.set(e.id||`${e.quest_id}:${e.timestamp}:${e.event}`,e));
|
|
215
|
+
function normalizeTimeline(e,q){const event=e.event||'note',actor=event==='info_received'?'external':['message_sent','reply_sent','dm_sent','email_replied','draft_posted','executed'].includes(event)?'agent':'system';return{id:`${q.id}:${e.ts}:${event}`,timestamp:e.display_timestamp??(()=>{const t=globalThis.SQQuestVisualizer?.sourceEventTime?.(e)??null;return t===null?e.ts:new Date(t).toISOString()})(),recorded_at:e.ts,actor,event,action:event.replaceAll('_',' '),outcome:'recorded',risk:event==='blocked'?'alert':'normal',target:e.channel_id||'',detail:e.message_text||e.note||e.reason||'',quest_id:q.id,quest_title:q.title,link_url:e.link_url||e.slack_url,link_kind:e.link_kind,action_type:e.action_type}}
|
|
216
|
+
function trailEvents(){if(!state.selected)return state.control.activity||[];const q=state.control.quests.find(x=>x.id===state.selected),timeline=(state.detail?.timeline||[]).map(e=>normalizeTimeline(e,q)),projected=(state.control.activity||[]).filter(e=>e.quest_id===state.selected),map=new Map;[...projected,...timeline].forEach(e=>map.set(e.id||`${e.quest_id}:${e.timestamp}:${e.event}`,e));const entries=[...map.values()],sourceDates=entries.some(e=>e.recorded_at&&e.recorded_at!==e.timestamp),when=e=>{const v=e.timestamp,n=Number(v);return typeof v!=='boolean'&&v!==null&&v!==''&&Number.isFinite(n)?n*(Math.abs(n)<1e12?1000:1):(globalThis.SQQuestVisualizer?.instant?.(v)??Date.parse(v))};return entries.sort(sourceDates?(a,b)=>(when(b)||0)-(when(a)||0):(a,b)=>String(b.timestamp).localeCompare(String(a.timestamp)))}
|
|
215
217
|
function eventClass(e){return e.event==='blocked'?'alert':e.actor==='external'?'external':e.actor==='agent'?'agent':''}
|
|
216
|
-
function renderTrail(){const q=state.selected&&state.control.quests.find(x=>x.id===state.selected);$('#trail-title').textOnce=q?'Agent Trail · This quest':'Agent Trail';$('#trail-hint').textOnce=q?`Timeline and pending drafts for ${q.title}.`:'Meaningful activity across active quests.';const events=trailEvents().filter(e=>state.filter==='all'||(state.filter==='alert'?e.event==='blocked':e.actor===state.filter));$('#trail').htmlOnce=events.map(e=>`<article class="event"><span class="event-time">${ago(e.timestamp)}</span><i class="event-dot ${eventClass(e)}"></i><div><div class="event-title">${pill((e.action||e.event).replaceAll('_',' '),e.event==='blocked'?'blocked':e.actor==='external'?'active':e.actor==='agent'?'info':'neutral')}${surfaceBadge(e)}${e.quest_id?`<button class="trail-quest" data-quest="${esc(e.quest_id)}">${esc(e.quest_title||e.quest_id)}</button>`:`<em>${esc(e.quest_title||e.quest_id||'Agent')}</em>`}</div>${e.detail?`<div class="event-detail rich-copy">${markdown(e.detail)}</div>`:''}<div class="event-meta">${esc(e.actor)} · ${esc(e.outcome||'recorded')}${e.target?' · '+esc(e.target):''}${safeUrl(e.link_url||'')?` · <a href="${esc(safeUrl(e.link_url))}" target="_blank" rel="noopener">open source</a>`:''}</div></div></article>`).join('')||'<div class="empty">No matching activity.</div>'}
|
|
218
|
+
function renderTrail(){const q=state.selected&&state.control.quests.find(x=>x.id===state.selected);$('#trail-title').textOnce=q?'Agent Trail · This quest':'Agent Trail';$('#trail-hint').textOnce=q?`Timeline and pending drafts for ${q.title}.`:'Meaningful activity across active quests.';const events=trailEvents().filter(e=>state.filter==='all'||(state.filter==='alert'?e.event==='blocked':e.actor===state.filter));$('#trail').htmlOnce=events.map(e=>`<article class="event"><span class="event-time">${ago(e.timestamp)}</span><i class="event-dot ${eventClass(e)}"></i><div><div class="event-title">${pill((e.action||e.event).replaceAll('_',' '),e.event==='blocked'?'blocked':e.actor==='external'?'active':e.actor==='agent'?'info':'neutral')}${surfaceBadge(e)}${e.quest_id?`<button class="trail-quest" data-quest="${esc(e.quest_id)}">${esc(e.quest_title||e.quest_id)}</button>`:`<em>${esc(e.quest_title||e.quest_id||'Agent')}</em>`}</div>${e.detail?`<div class="event-detail rich-copy">${markdown(e.detail)}</div>`:''}<div class="event-meta">${esc(e.actor)} · ${esc(e.outcome||'recorded')}${e.recorded_at&&e.recorded_at!==e.timestamp&&Date.parse(e.recorded_at)!==Date.parse(e.timestamp)?' · logged '+esc(ago(e.recorded_at)):''}${e.target?' · '+esc(e.target):''}${safeUrl(e.link_url||'')?` · <a href="${esc(safeUrl(e.link_url))}" target="_blank" rel="noopener">open source</a>`:''}</div></div></article>`).join('')||'<div class="empty">No matching activity.</div>'}
|
|
217
219
|
function renderAudit(){const h=state.control.history||{approvals:[],runs:[]};$('#approval-history').htmlOnce=(h.approvals||[]).map(a=>`<article class="audit-item"><div class="state-row">${pill(a.status||'unknown',a.status||'neutral')}${surfaceBadge(a)}<strong>${esc(a.quest_title||a.quest_id)}</strong><span class="time">${ago(a.sent_at||a.cancelled_at||a.reviewed_at||a.created_at)}</span></div><div class="audit-copy rich-copy">${markdown(a.message_text||a.context||'')}</div>${(a.available_actions||[]).includes('undo')?`<button class="button" data-history-action="undo" data-id="${esc(a.id)}">Undo</button>`:''}</article>`).join('')||'<div class="empty">No approval history.</div>';$('#run-history').htmlOnce=(h.runs||[]).map(r=>`<div class="run"><span class="time">${ago(r.ts)}</span><span>${esc((r.targets||[]).join(', ')||r.reason||r.kind)}</span>${pill(r.ok===false?'failed':r.kind,r.ok===false?'blocked':'neutral')}</div>`).join('')||'<div class="empty">No dispatch history.</div>'}
|
|
218
220
|
const briefTypeLabel={morning:'Morning',evening:'Evening',weekly:'Weekly',monthly:'Monthly'};
|
|
219
221
|
function briefingPrompt(kind){
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"""
|
|
19
19
|
cron-due.py — decide whether a cron schedule is due to fire.
|
|
20
20
|
|
|
21
|
-
Usage: cron-due.py CRON_EXPR TZ LAST_TS
|
|
21
|
+
Usage: cron-due.py CRON_EXPR TZ LAST_TS [CHECKED_THROUGH_TS]
|
|
22
22
|
|
|
23
23
|
CRON_EXPR Standard 5-field cron (minute hour dom month dow).
|
|
24
24
|
Supports *, */N, N, N-M, N,M. Vixie OR semantics when both
|
|
@@ -26,6 +26,7 @@ Usage: cron-due.py CRON_EXPR TZ LAST_TS
|
|
|
26
26
|
TZ IANA timezone (e.g., "Asia/Singapore"). Empty = UTC.
|
|
27
27
|
LAST_TS Previous last_checked_ts: unix epoch (Slack-style "123.456"
|
|
28
28
|
or plain int) or ISO 8601. Empty = "never run" → not-due.
|
|
29
|
+
CHECKED_THROUGH_TS Optional evaluation boundary supplied by schedule.py.
|
|
29
30
|
|
|
30
31
|
Output: "due" or "not-due". Exit 0 on success, 2 on bad input.
|
|
31
32
|
|
|
@@ -87,8 +88,8 @@ def day_matches(dt, dom_set, dow_set, dom_raw, dow_raw):
|
|
|
87
88
|
|
|
88
89
|
|
|
89
90
|
def main():
|
|
90
|
-
if len(sys.argv)
|
|
91
|
-
print("usage: cron-due.py CRON_EXPR TZ LAST_TS", file=sys.stderr)
|
|
91
|
+
if len(sys.argv) not in (4, 5):
|
|
92
|
+
print("usage: cron-due.py CRON_EXPR TZ LAST_TS [CHECKED_THROUGH_TS]", file=sys.stderr)
|
|
92
93
|
sys.exit(2)
|
|
93
94
|
expr, tz_name, last_arg = sys.argv[1:4]
|
|
94
95
|
tz = ZoneInfo(tz_name) if tz_name else timezone.utc
|
|
@@ -113,7 +114,7 @@ def main():
|
|
|
113
114
|
sys.exit(2)
|
|
114
115
|
|
|
115
116
|
last_utc = parse_last(last_arg)
|
|
116
|
-
now_utc = datetime.now(timezone.utc)
|
|
117
|
+
now_utc = parse_last(sys.argv[4]) if len(sys.argv) == 5 else datetime.now(timezone.utc)
|
|
117
118
|
if last_utc is None or last_utc >= now_utc:
|
|
118
119
|
print("not-due")
|
|
119
120
|
return
|
|
@@ -43,6 +43,7 @@ import os
|
|
|
43
43
|
import json
|
|
44
44
|
import subprocess
|
|
45
45
|
import time
|
|
46
|
+
import math
|
|
46
47
|
|
|
47
48
|
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
48
49
|
CRON_DUE = os.path.join(SCRIPT_DIR, "cron-due.py")
|
|
@@ -53,16 +54,22 @@ import result
|
|
|
53
54
|
|
|
54
55
|
def main():
|
|
55
56
|
entry = json.loads(sys.argv[1])
|
|
57
|
+
# The tick's start can precede a slot that becomes due while other checkers
|
|
58
|
+
# run. Evaluate against, and return, one checker-owned boundary so an ack
|
|
59
|
+
# cannot bookmark a time before the slot this check actually handled.
|
|
60
|
+
# Match result.emit's microsecond truncation BEFORE cron's datetime parser
|
|
61
|
+
# can round a sub-microsecond value into the next scheduled minute.
|
|
62
|
+
checked_through = math.floor(time.time() * 1_000_000) / 1_000_000
|
|
56
63
|
|
|
57
64
|
# One-shot schedule: fire once when next_fire_ts has passed.
|
|
58
65
|
if "cron" not in entry and "next_fire_ts" in entry:
|
|
59
66
|
next_fire = float(entry["next_fire_ts"])
|
|
60
|
-
now =
|
|
67
|
+
now = checked_through
|
|
61
68
|
last = float(entry.get("last_checked_ts") or 0)
|
|
62
69
|
if now >= next_fire and last < next_fire:
|
|
63
|
-
result.counted(1, "one-shot schedule due")
|
|
70
|
+
result.counted(1, "one-shot schedule due", advance_to=checked_through)
|
|
64
71
|
else:
|
|
65
|
-
result.counted(0, "")
|
|
72
|
+
result.counted(0, "", advance_to=checked_through)
|
|
66
73
|
return
|
|
67
74
|
|
|
68
75
|
cron_expr = str(entry["cron"])
|
|
@@ -70,18 +77,21 @@ def main():
|
|
|
70
77
|
since = str(entry.get("last_checked_ts", ""))
|
|
71
78
|
|
|
72
79
|
r = subprocess.run(
|
|
73
|
-
["python3", CRON_DUE, cron_expr, tz, since],
|
|
80
|
+
["python3", CRON_DUE, cron_expr, tz, since, str(checked_through)],
|
|
74
81
|
capture_output=True, text=True, timeout=10,
|
|
75
82
|
)
|
|
76
83
|
if r.returncode == 2:
|
|
77
84
|
result.misconfig(f"bad cron expression: {r.stderr.strip()}")
|
|
78
85
|
return
|
|
86
|
+
if r.returncode != 0 or r.stdout.strip() not in ("due", "not-due"):
|
|
87
|
+
result.error("cron evaluation failed; schedule watermark held")
|
|
88
|
+
return
|
|
79
89
|
|
|
80
90
|
cron_verdict = r.stdout.strip()
|
|
81
91
|
if cron_verdict == "due":
|
|
82
|
-
result.counted(1, f"schedule due '{cron_expr} ({tz})'")
|
|
92
|
+
result.counted(1, f"schedule due '{cron_expr} ({tz})'", advance_to=checked_through)
|
|
83
93
|
else:
|
|
84
|
-
result.counted(0, "")
|
|
94
|
+
result.counted(0, "", advance_to=checked_through)
|
|
85
95
|
|
|
86
96
|
|
|
87
97
|
if __name__ == "__main__":
|
|
@@ -8,6 +8,7 @@ import hashlib
|
|
|
8
8
|
import math
|
|
9
9
|
from pathlib import Path
|
|
10
10
|
import re
|
|
11
|
+
from timeline_time import display_timestamp
|
|
11
12
|
|
|
12
13
|
MAX_BYTES = 20 * 1024 * 1024
|
|
13
14
|
MAX_EVENTS = 5000
|
|
@@ -19,7 +20,7 @@ EVENT_FIELDS = ('id', 'event_id', 'ts', 'timestamp', 'event', 'note', 'reason',
|
|
|
19
20
|
'channel_id', 'channel_name', 'thread_ts', 'message_ts', 'response_ts',
|
|
20
21
|
'repo', 'issue', 'pr', 'doc_id', 'file', 'path', 'file_id',
|
|
21
22
|
'source_file_id', 'target_file_id', 'message_id', 'thread_id',
|
|
22
|
-
'link_url', 'slack_url', 'permalink', 'source_ts', 'watch_type')
|
|
23
|
+
'link_url', 'slack_url', 'permalink', 'source_ts', 'source_event_ts', 'watch_type')
|
|
23
24
|
|
|
24
25
|
EVENT_FIELDS += tuple("created_ts type parent_event_ids url html_url pr_url issue_url ticket_url doc_url source_url target_url repo_url webViewLink jira jira_key issue_key document_id new_file_id clone_file_id copy_file_id source_file_ids new_file_ids prs related_pr issue_numbers title resource_title issue_title pr_title ticket_title doc_title document_title source_title target_title thread_title subject source_channel_id target_channel_id target_channel_name slack_channel_id channel repository".split())
|
|
25
26
|
EVENT_FIELDS += tuple("links succeeded status kind resource_type threadId messageId gmail_web_thread_id block_title database_title data_source_title gmail_id message_url ticket summary brief detail finding system_event_key provider surface service account account_email gmail_account mail_account gmail_thread_id gmail_message_id peer chat_id telegram_chat_id chat_title peer_title username conversation_id participant_id post_id tweet_id post_title page_id block_id data_source_id database_id page_title coda_doc_id query search jql cron tz next_fire_ts filter_keywords filter_sender_ids filter_user_ids from_user include_outgoing exclude_replies exclude_reposts user_id issue_id health_issue_id system_key retired_at source target resource resources result watch_identity".split())
|
|
@@ -311,7 +312,7 @@ def build_visualization(workspace: Path, quest_id: str, detail: dict | None = No
|
|
|
311
312
|
'dispatch_id': str(receipt.get('run_id') or ''), 'note': str(item.get('note') or '')[:1500],
|
|
312
313
|
'outcome': str(item.get('status') or ''), 'evidence_source': 'dispatch receipt'})
|
|
313
314
|
coverage['receipts'] += 1
|
|
314
|
-
events.sort(key=lambda e: _instant(
|
|
315
|
+
events.sort(key=lambda e: _instant(display_timestamp(e)) or float('-inf'))
|
|
315
316
|
if len(events) > MAX_EVENTS:
|
|
316
317
|
coverage['truncated'] = True
|
|
317
318
|
events = events[-MAX_EVENTS:]
|
|
@@ -193,12 +193,83 @@ def has_successful_slack_read(path):
|
|
|
193
193
|
return False
|
|
194
194
|
|
|
195
195
|
|
|
196
|
+
def has_failed_slack_access(path):
|
|
197
|
+
"""Require a real failed read plus access/transport evidence, not message text.
|
|
198
|
+
|
|
199
|
+
A handled missing/deleted thread is not an access outage. Nor is a successful
|
|
200
|
+
read whose messages happen to discuss authentication or connection errors.
|
|
201
|
+
"""
|
|
202
|
+
access_error = re.compile(
|
|
203
|
+
r"invalid_auth|not_authed|token_revoked|account_inactive|missing_scope|"
|
|
204
|
+
r"ratelimited|rate.limit|needs authentication|failed to connect|"
|
|
205
|
+
r"authorization must be completed again|rejected the long-lived credential|macOS Keychain|"
|
|
206
|
+
r"timed? ?out|timeout|connection (?:refused|reset)|network|socket|"
|
|
207
|
+
r"HTTP[ :]+(?:401|403|429|500|502|503|504)|service_unavailable", re.I)
|
|
208
|
+
pending = {}
|
|
209
|
+
for raw in path.read_text(errors="replace").splitlines():
|
|
210
|
+
try:
|
|
211
|
+
event = json.loads(raw)
|
|
212
|
+
except ValueError:
|
|
213
|
+
continue
|
|
214
|
+
if not isinstance(event, dict):
|
|
215
|
+
continue
|
|
216
|
+
item = event.get("item") or {}
|
|
217
|
+
if isinstance(item, dict):
|
|
218
|
+
if (item.get("type") == "command_execution" and is_shell_slack_read(item.get("command"))
|
|
219
|
+
and item.get("exit_code") in (1, 4)):
|
|
220
|
+
return True
|
|
221
|
+
if (item.get("type") == "mcp_tool_call" and is_slack_tool(item.get("tool"))
|
|
222
|
+
and (item.get("error") or item.get("status") == "failed")
|
|
223
|
+
and access_error.search(json.dumps(item.get("error")))):
|
|
224
|
+
return True
|
|
225
|
+
tool_call = event.get("tool_call") or {}
|
|
226
|
+
shell = tool_call.get("shellToolCall") if isinstance(tool_call, dict) else None
|
|
227
|
+
if isinstance(shell, dict):
|
|
228
|
+
args, result = shell.get("args") or {}, shell.get("result") or {}
|
|
229
|
+
failure = result.get("failure") if isinstance(result, dict) else None
|
|
230
|
+
if (isinstance(args, dict) and isinstance(result, dict)
|
|
231
|
+
and is_shell_slack_read(args.get("command")) and failure is not None
|
|
232
|
+
and ((isinstance(failure, dict) and failure.get("exitCode") in (1, 4))
|
|
233
|
+
or access_error.search(json.dumps(failure)))):
|
|
234
|
+
return True
|
|
235
|
+
message = event.get("message") or {}
|
|
236
|
+
if not isinstance(message, dict):
|
|
237
|
+
continue
|
|
238
|
+
for block in blocks(message.get("content")):
|
|
239
|
+
if not isinstance(block, dict):
|
|
240
|
+
continue
|
|
241
|
+
if block.get("type") == "tool_use":
|
|
242
|
+
args = block.get("input") or {}
|
|
243
|
+
if is_slack_tool(block.get("name")):
|
|
244
|
+
pending[block.get("id")] = "native"
|
|
245
|
+
elif (block.get("name") == "Bash" and isinstance(args, dict)
|
|
246
|
+
and not args.get("run_in_background") and is_shell_slack_read(args.get("command"))):
|
|
247
|
+
pending[block.get("id")] = "shell"
|
|
248
|
+
if block.get("type") != "tool_result" or block.get("tool_use_id") not in pending:
|
|
249
|
+
continue
|
|
250
|
+
result = event.get("tool_use_result") or {}
|
|
251
|
+
result = result if isinstance(result, dict) else {}
|
|
252
|
+
if pending[block["tool_use_id"]] == "shell" and result.get("exitCode") in (1, 4):
|
|
253
|
+
return True
|
|
254
|
+
# Observed Claude Code Bash failures use a string tool_use_result
|
|
255
|
+
# and an is_error content beginning "Exit code N", not exitCode.
|
|
256
|
+
content = block.get("content")
|
|
257
|
+
if (pending[block["tool_use_id"]] == "shell" and block.get("is_error")
|
|
258
|
+
and isinstance(content, str)
|
|
259
|
+
and re.match(r"\s*(?:Error:\s*)?Exit code [14]\b", content)):
|
|
260
|
+
return True
|
|
261
|
+
if block.get("is_error") and access_error.search(json.dumps(block.get("content"))):
|
|
262
|
+
return True
|
|
263
|
+
return False
|
|
264
|
+
|
|
265
|
+
|
|
196
266
|
def main():
|
|
197
|
-
if len(sys.argv) !=
|
|
198
|
-
print(f"usage: {Path(sys.argv[0]).name} <worker.ndjson>", file=sys.stderr)
|
|
267
|
+
if len(sys.argv) not in (2, 3) or (len(sys.argv) == 3 and sys.argv[2] != "--failed-access"):
|
|
268
|
+
print(f"usage: {Path(sys.argv[0]).name} <worker.ndjson> [--failed-access]", file=sys.stderr)
|
|
199
269
|
return 2
|
|
200
270
|
path = Path(sys.argv[1])
|
|
201
|
-
|
|
271
|
+
check = has_failed_slack_access if len(sys.argv) == 3 else has_successful_slack_read
|
|
272
|
+
return 0 if path.is_file() and check(path) else 1
|
|
202
273
|
|
|
203
274
|
|
|
204
275
|
if __name__ == "__main__":
|
|
@@ -259,6 +259,13 @@ def cmd_write(payload_json: str):
|
|
|
259
259
|
data.setdefault("items", [])
|
|
260
260
|
# Inbox can receive distinct review requests for the same thread from different
|
|
261
261
|
# producers. Ordinary quest dedup remains unchanged.
|
|
262
|
+
if target.get("action") == "quest_setup":
|
|
263
|
+
existing = next((i for i in data["items"]
|
|
264
|
+
if i.get("quest_id") == quest_id
|
|
265
|
+
and i.get("target", {}).get("action") == "quest_setup"
|
|
266
|
+
and i.get("status") not in ("executed", "cancelled")), None)
|
|
267
|
+
if existing:
|
|
268
|
+
return existing["id"] # Re-arm the same review after an interrupted write.
|
|
262
269
|
origin = source if quest_id == INBOX_QUEST else quest_id
|
|
263
270
|
duplicate = any(
|
|
264
271
|
i for i in data.get("items", [])
|
|
@@ -293,6 +300,7 @@ def cmd_write(payload_json: str):
|
|
|
293
300
|
"target": target,
|
|
294
301
|
"message_text": payload.get("message_text", ""),
|
|
295
302
|
"context": payload.get("context", ""),
|
|
303
|
+
"source_url": payload.get("source_url") or target.get("source_url"),
|
|
296
304
|
"risk_reason": payload.get("risk_reason", ""),
|
|
297
305
|
}
|
|
298
306
|
if source:
|
|
@@ -307,8 +315,10 @@ def cmd_write(payload_json: str):
|
|
|
307
315
|
# Arm the tracking watch OUTSIDE the approvals lock (different file, its own
|
|
308
316
|
# flock). Coupled here so an approval can never be created without its watch.
|
|
309
317
|
if new_id:
|
|
310
|
-
cmd_arm(new_id, emit=False)
|
|
318
|
+
armed = cmd_arm(new_id, emit=False) == 0
|
|
311
319
|
print(new_id)
|
|
320
|
+
if not armed and target.get("action") == "quest_setup":
|
|
321
|
+
raise SystemExit(3)
|
|
312
322
|
|
|
313
323
|
|
|
314
324
|
def cmd_arm(approval_id: str, emit: bool = True) -> int:
|