bostrat-node 1.16.3 → 1.16.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/bostrat-audit CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import L from"node:fs/promises";import Ze from"node:os";import v from"node:path";var ke=(e,o)=>{if(e==null||e==="")return o;let t=Number(e);return Number.isFinite(t)&&t>=0?t:o},ot=ke(process.env.BOSTRAT_HOOK_FOLD_MS,250);var we=1e3;function U(e){let o=Number(e?.count);return Number.isInteger(o)&&o>1&&e?.tools&&typeof e.tools=="object"?Math.min(o,we):1}function q(e){let o=e||{},t=U(o);if(t===1)return[o];let a=(Array.isArray(o.calls)?o.calls:[]).filter(i=>i&&typeof i=="object").slice(0,t),r={};for(let i of a)i.tool&&(r[i.tool]=(r[i.tool]||0)+1);for(let[i,c]of Object.entries(o.tools))for(let p=r[i]||0;p<Number(c)&&a.length<t;p++)a.push({tool:i});for(;a.length<t;)a.push({tool:null});return a}import{createHash as Ie}from"node:crypto";var xe=new Set(["userId"]);function K(e){return e===null||typeof e!="object"?e===void 0||typeof e=="number"&&!Number.isFinite(e)?"null":JSON.stringify(e):Array.isArray(e)?`[${e.map(t=>K(t===void 0?null:t)).join(",")}]`:`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${K(e[t])}`).join(",")}}`}function se(e){let o={};for(let t of Object.keys(e))xe.has(t)||(o[t]=e[t]);return Ie("sha256").update(K(o)).digest("hex")}var re=e=>Number.isFinite(e?.seq);function ie(e){let o={members:0,chained:0,preChain:0,intactFrom:null,intactTo:null,genesis:!1,breaks:[]},t=null,a=!1,r=(i,c)=>{t={seq:i.seq,hash:c},o.intactFrom=i.seq,o.genesis=i.seq===1&&i.prev===null};for(let i of e||[]){if(!re(i))continue;if(o.members++,i.prev===void 0){t&&!a?(o.breaks.push({kind:"unchained",seq:i.seq,eventId:i.id??null}),a=!0):t||o.preChain++;continue}o.chained++;let c=se(i);if(!t||a){a=!1,r(i,c);continue}if(i.seq===t.seq+1){if(i.prev===t.hash){t={seq:i.seq,hash:c};continue}o.breaks.push({kind:"prev-mismatch",seq:i.seq,eventId:i.id??null,expected:t.hash,got:i.prev})}else i.seq>t.seq+1?o.breaks.push({kind:"seq-gap",seq:i.seq,eventId:i.id??null,from:t.seq+1,to:i.seq-1}):o.breaks.push({kind:"seq-repeat",seq:i.seq,eventId:i.id??null,headSeq:t.seq});r(i,c)}return o.intactTo=t?t.seq:null,t||(o.intactFrom=null),o}var A=6e4,Se=120*A,ae=2e3,ce=5e3,$e=2*A,Ee=5e3,_e=2*A,C=5e3,Me={Workflow:360*A,Agent:60*A},Ae=5*A,Oe=10*A,J=80,T=3,qe=["Checkpoint: write a work-in-progress handoff","Resume from .bostrat/handoff/latest.md","Beat: write a","You are a SUBTASK agent working in an isolated","A subtask box you delegated has finished"],X={operator:"strong",orchestrator:"strong","card-answer":"strong",loop:"strong","background-job":"strong","task-continuation":"strong","operator-terminal":"weak","orchestrator-unlogged":"weak","background-launch":"weak","task-continuation-unlogged":"weak",peer:"flagged","nested-session":"flagged","unknown-prompt":"flagged",unrooted:"flagged"},M=e=>String(e??"").replace(/\s+/g," ").trim(),u=e=>e?.ts??0,V=(e,o)=>!!e&&!!o&&(e.startsWith(o.slice(0,J))||o.startsWith(e.slice(0,J))),Te=6,ve=(e,o)=>V(e,o)||e.length>=Te&&o.includes(e.slice(0,J)),je=/^<pasted_content\b[^>]*>\s*/i,G=e=>M(e.payload?.promptHead??e.payload?.text).replace(je,""),Ne=/^<cross-session-message\b/i,Fe=/^<task-notification>/i,Ce=/<tool-use-id>\s*([^<\s]+)\s*<\/tool-use-id>/i;function de(e){let o=e.payload||{},t=U(o),a=q(o)[0],r=a.head||a.path||(o.command?M(o.command):""),i=e.type==="tool.failed"?" [failed]":e.type==="tool.started"?" [never completed]":"";return`${a.tool||"tool"}${r?`: ${r.slice(0,100)}`:""}${i}${t>1?` (+${t-1} more)`:""}`}var De=/\.answered$/,Re=new Set(["loop.created","followup.created"]),Ue=16,ue=new Set(["tool.started","tool.called","tool.failed"]);function Pe(){return{byId:new Map,byDelivery:new Map,byPrompt:new Map,byToolUse:new Map,jobs:new Map}}function Le(e,o){if(!o||typeof o.type!="string")return;o.id&&e.byId.set(o.id,o);let t=o.payload||{};if(o.type==="turn.user")o.source==="orchestrator"&&t.deliveryId&&e.byDelivery.set(t.deliveryId,o),o.source==="hook"&&t.promptId&&!e.byPrompt.has(`${o.boxId}\0${t.promptId}`)&&e.byPrompt.set(`${o.boxId}\0${t.promptId}`,o);else if(o.type==="job.started"&&t.id)e.jobs.set(t.id,o);else if(ue.has(o.type)&&o.source==="hook")for(let a of q(t))a.toolUseId&&!e.byToolUse.has(a.toolUseId)&&e.byToolUse.set(a.toolUseId,o)}function He(e){let o=Pe();for(let t of e)Le(o,t);return o}function le(e,o){let t=e;for(let a=0;t&&a<Ue;a++){let r=t.payload||{},i=t.type;if(t.causationId&&o.byId.has(t.causationId)&&t.causationId!==t.id){t=o.byId.get(t.causationId);continue}if(ue.has(i)){let c=r.promptId?o.byPrompt.get(`${t.boxId}\0${r.promptId}`):null;if(!c)return null;t=c;continue}if(i==="turn.user"){if(t.source==="hook"){if(r.kind==="task-notification"&&r.jobId){let p=o.jobs.get(r.jobId);if(!p)return null;t=p;continue}let c=r.deliveryId?o.byDelivery.get(r.deliveryId):null;if(!c)return null;t=c;continue}return t.source==="orchestrator"?r.loopId||r.producer==="loop"?{origin:"loop",root:t}:{origin:t.actor==="orchestrator"?"orchestrator":"operator",root:t}:t.source==="transcript"?{origin:"operator-terminal",root:t}:null}if(i==="job.started"){let c=r.id?o.byToolUse.get(r.id):null;if(!c)return null;t=c;continue}return De.test(i)||Re.has(i)?{origin:"card-answer",root:t}:i==="peer.message"?{origin:"peer",root:t}:null}return null}function We(e){let o={events:e.length,firstSeq:null,lastSeq:null,headMissing:!1,gaps:0,repeats:0},t=null;for(let r of e)Number.isFinite(r?.seq)&&(t===null?o.firstSeq=r.seq:r.seq>t+1?o.gaps++:r.seq<=t&&o.repeats++,t=r.seq);o.lastSeq=t,o.headMissing=o.firstSeq!==null&&o.firstSeq>1;let a=ie(e);return o.chain={state:a.chained===0?"pre-chain":a.breaks.length?"broken":a.genesis?"intact":"intact-from-mid-log",chained:a.chained,preChain:a.preChain,intactFrom:a.intactFrom,intactTo:a.intactTo,breaks:a.breaks},o}var Be=e=>{switch(e.kind){case"prev-mismatch":return`seq ${e.seq} states a predecessor that is not the line before it \u2014 the line before it changed, or was replaced`;case"seq-gap":return`seq ${e.from}${e.to!==e.from?`\u2013${e.to}`:""} missing between chained lines`;case"seq-repeat":return`seq ${e.seq} appears again after the chain passed it (a line was inserted, or the log was rewound)`;case"unchained":return`seq ${e.seq} carries no chain link after chained lines (an older node resumed this log)`;default:return`${e.kind} at seq ${e.seq}`}};function Ke(e){let o=new Map,t=new Map,a=new Map,r=new Map,i=(s,g,I)=>{s.has(g)||s.set(g,[]),s.get(g).push(I)};for(let s of e)if((s.type==="box.state.changed"||s.type.startsWith("handoff."))&&i(r,s.payload?.box||s.boxId||null,u(s)),s.type==="session.ready"&&([...r.get(s.boxId)||[],...r.get(null)||[]].some(I=>I<=u(s)&&u(s)-I<=_e)||i(a,s.boxId,u(s))),s.type==="turn.user")if(s.source==="orchestrator"){let g=(s.payload?.attachments||[]).map(I=>I?.id).filter(Boolean);i(o,s.boxId,{ts:u(s),head:M(s.payload?.text),files:g,actor:s.actor,usedAt:null})}else s.source==="transcript"&&i(t,s.boxId,{ts:u(s),head:M(s.payload?.text),note:s.payload?.note?.kind||null});let c=new Map,p=new Map,f=new Map;for(let s of e){if(s.type==="turn.user"&&s.source==="orchestrator"&&p.set(s.boxId,!0),s.source!=="hook")continue;if(s.type==="turn.agent"){let x=f.get(s.boxId)||0;x>0?f.set(s.boxId,x-1):p.set(s.boxId,!1);continue}if(s.type!=="turn.user")continue;let g=G(s),I=(()=>{if(s.actor==="peer"||Ne.test(g))return{origin:"peer"};if(Fe.test(g))return{origin:"task-continuation",jobId:g.match(Ce)?.[1]||null};let x=(o.get(s.boxId)||[]).filter(m=>(m.usedAt===null||u(s)-m.usedAt<=ce)&&m.ts>=u(s)-Se&&m.ts<=u(s)+ae&&(ve(m.head,g)||!m.head&&m.files.length>0&&(m.files.some(E=>g.includes(`.bostrat/uploads/${E}`))||u(s)-m.ts<=ce))),$=x[x.length-1];if($)return $.usedAt=u(s),{origin:$.actor==="orchestrator"?"orchestrator":"operator"};if(qe.some(m=>g.startsWith(m)))return{origin:"orchestrator-unlogged"};if((t.get(s.boxId)||[]).find(m=>!m.note&&m.ts>=u(s)-ae&&m.ts<=u(s)+$e&&V(m.head,g)))return{origin:"operator-terminal"};let D=(a.get(s.boxId)||[]).some(m=>m<=u(s)&&u(s)-m<=Ee);return{origin:p.get(s.boxId)||D?"nested-session":"unknown-prompt"}})();c.set(s,I),I.origin==="nested-session"?f.set(s.boxId,(f.get(s.boxId)||0)+1):p.set(s.boxId,!0)}return c}function Ye(e){let o=new Map,t=new Map;for(let a of e){let r=a.payload?.id;if(r)if(a.type==="job.started"){let i={from:(a.payload?.ts??u(a))-C,to:1/0,loggedAt:u(a)};t.set(r,i),o.has(a.boxId)||o.set(a.boxId,[]),o.get(a.boxId).push(i)}else a.type==="job.stopped"&&t.has(r)&&(t.get(r).to=u(a)+C)}return{byBox:o,byId:t}}function Je(e,{trackId:o=null,name:t=null,since:a=0}={}){let r=Ke(e),i=Ye(e),c=new Set;for(let n of e)n.type==="tool.called"&&n.source==="hook"&&c.add(n.boxId);let p=n=>n.type==="tool.called"&&(n.source==="hook"||!(n.provider==="claude"&&c.has(n.boxId)))||n.type==="tool.failed"&&n.source==="hook",f=new Set,s=new Map;for(let n of e)if(n.source==="hook")if(n.type==="tool.called"||n.type==="tool.failed")for(let l of q(n.payload))l.toolUseId&&f.add(l.toolUseId);else(n.type==="turn.agent"||n.type==="session.ready"||n.type==="turn.aborted"||n.type==="turn.interrupted")&&(s.has(n.boxId)||s.set(n.boxId,[]),s.get(n.boxId).push(u(n)));let g=e.length?u(e[e.length-1]):0,I=n=>{if(n.type!=="tool.started"||n.source!=="hook")return null;let l=q(n.payload).filter(b=>b.toolUseId&&!f.has(b.toolUseId));return l.length&&((s.get(n.boxId)||[]).some(b=>b>u(n))||g-u(n)>Oe)?l:null},x={},$={},W={keyed:0,timing:0},D=He(e),m=new Map,E=(n,l,d,b,k,h=1)=>{let j=`${n}\0${d.boxId}\0${b}`,w=m.get(j);return(!w||u(d)-w.to>Ae)&&(w={rule:n,severity:l,trackId:o,track:t,boxId:d.boxId,from:u(d),to:u(d),count:0,note:k,samples:[]},m.set(j,w),R.push(w)),w.to=u(d),w.count+=h,w},R=[],B=new Map,be=n=>(B.has(n)||B.set(n,{open:!1,origin:null,nested:0,soft:null,lastSendHead:null,launch:null}),B.get(n));for(let n of e){let l=be(n.boxId),d=u(n)>=a;if(n.type==="session.foreign"){if(n.payload?.phase==="prompted"&&d){let y=E("nested-session","medium",n,"","a session that is not the box's own was prompted through this box \u2014 typically an agent-launched `claude -p`");y.samples.length<T&&y.samples.push(M(n.payload?.promptHead).slice(0,100))}continue}if(n.type==="turn.user"&&n.source==="hook"){let y=r.get(n);if(y.origin==="nested-session"){if(l.nested++,d){let O=E("nested-session","medium",n,"","a prompt no recorded send accounts for arrived mid-turn or right after a SessionStart \u2014 typically an agent-launched `claude -p`");O.samples.length<T&&O.samples.push(G(n).slice(0,100))}continue}if(l.open=!0,l.origin=y.origin,y.origin==="task-continuation"&&!i.byId.has(y.jobId)&&(l.origin="task-continuation-unlogged"),l.origin==="unknown-prompt"&&d){let O=E("unknown-prompt","medium",n,"","a turn opened by a prompt with no operator, machinery or job record behind it");O.samples.length<T&&O.samples.push(G(n).slice(0,100))}}else if(n.type==="turn.agent"&&n.source==="hook")l.nested>0?l.nested--:l.open=!1;else if(n.type==="turn.aborted"||n.type==="turn.interrupted")l.open=!1;else if(n.type==="turn.user"&&n.source==="orchestrator")l.lastSendHead=M(n.payload?.text),l.soft=n.actor==="orchestrator"?"orchestrator":"operator",l.open=!0,l.origin=l.soft;else if(n.type==="turn.user"&&n.source==="transcript"){let y=M(n.payload?.text);!n.payload?.note&&!V(y,l.lastSendHead)&&(l.soft="operator-terminal")}else n.type==="peer.message"&&(l.soft="peer");let b=I(n);if(!b&&!p(n))continue;let k=b?b.length:n.source==="hook"?U(n.payload):1,h;if(n.payload?.foreignSession)h="nested-session";else if(n.source==="hook"){let y=(i.byBox.get(n.boxId)||[]).some(_=>u(n)>=_.from&&u(n)<=_.to);l.open?h=l.origin:y?h="background-job":l.nested>0?h="nested-session":l.launch&&u(n)<=l.launch?h="background-launch":h="unrooted";let O=(i.byBox.get(n.boxId)||[]).some(_=>_.loggedAt<=u(n)+C);for(let _ of new Set(q(n.payload).map(ne=>ne.tool)))(_==="Workflow"||_==="Agent"&&!O)&&l.open&&X[l.origin]!=="flagged"&&(l.launch=Math.max(l.launch||0,u(n)+Me[_]))}else h=l.soft||"unrooted";let j=n.source==="hook"&&!n.payload?.foreignSession?le(n,D):null;if(j&&(h=j.origin),!d)continue;W[j?"keyed":"timing"]+=k,x[h]=(x[h]||0)+k;let w=n.provider||"unknown";if($[w]||={actions:0,fidelity:n.source==="hook"?"hook":"transcript",identified:!1},$[w].actions+=k,n.source==="hook"&&($[w].fidelity="hook"),n.source==="hook"&&q(n.payload).some(y=>y.toolUseId)&&($[w].identified=!0),b){let y=E("unfinished-calls","low",n,"","calls the CLI began (PreToolUse) and never reported complete or failed \u2014 killed, crashed or restarted mid-call; the tool may have run",k);y.samples.length<T&&y.samples.push(de(n))}if(h==="unrooted"){let y=E("unrooted-actions","high",n,"","tool calls with no open turn, no recorded job and no launch that accounts for them",k);y.samples.length<T&&y.samples.push(de(n))}else if(h==="peer")E("peer-driven-actions","low",n,"","tool calls in a turn another session's message opened",k);else if(h==="nested-session"||h==="unknown-prompt"){let y=m.get(`${h}\0${n.boxId}\0`);y&&(y.actions=(y.actions||0)+k)}}let F={total:0,keyed:0,timing:0,unrooted:0};{let n=new Map,l=new Map;for(let d of e)d.source==="hook"&&(d.type==="turn.user"?l.set(d.boxId,u(d)):(d.type==="turn.agent"||d.type==="turn.aborted"||d.type==="turn.interrupted")&&l.has(d.boxId)&&((n.get(d.boxId)||n.set(d.boxId,[]).get(d.boxId)).push([l.get(d.boxId),u(d)]),l.delete(d.boxId)));for(let[d,b]of l)(n.get(d)||n.set(d,[]).get(d)).push([b,1/0]);for(let d of e){if(d.type!=="code.committed"||d.source!=="hook"||u(d)<a)continue;F.total++;let b=Number(d.payload?.ts??d.ts)||u(d);if(le(d,D))F.keyed++;else if((n.get(d.boxId)||[]).some(([k,h])=>b>=k-C&&b<=h+C))F.timing++;else{F.unrooted++;let k=E("unrooted-commit","medium",d,"","a commit landed in the box's workspace with no turn open and no recorded cause");k.samples.length<T&&k.samples.push(`${String(d.payload?.sha||"").slice(0,7)} ${M(d.payload?.subject).slice(0,80)}`)}}}let S=We(e),oe=Object.values(x).reduce((n,l)=>n+l,0);if(S.headMissing&&oe&&R.push({rule:"log-head-missing",severity:"medium",trackId:o,track:t,boxId:null,from:u(e[0]),to:u(e[0]),count:1,samples:[],note:`the log starts at seq ${S.firstSeq} \u2014 its earlier history is not on this node`}),S.chain.breaks.length){let n=new Map;for(let h of e)Number.isFinite(h?.seq)&&!n.has(h.seq)&&n.set(h.seq,h);let l=S.chain.breaks.filter(h=>h.kind==="prev-mismatch"||h.kind==="seq-repeat"),d=h=>u(n.get(h.seq))||u(e.at(-1)),b=S.chain.breaks[0],k=S.chain.breaks.at(-1);R.push({rule:"chain-broken",severity:l.length?"high":"medium",trackId:o,track:t,boxId:null,from:d(b),to:d(k),count:S.chain.breaks.length,samples:S.chain.breaks.slice(0,T).map(Be),note:`the log's hash chain breaks ${S.chain.breaks.length} time(s) on this node \u2014 advisory: the plane's verified head is the anchor (GET /plane/admin/chain/${o??"<track>"})`})}return{trackId:o,track:t,actions:oe,byOrigin:x,byEvidence:W,byProvider:$,commits:F,findings:R,integrity:S}}var pe={high:0,medium:1,low:2};function fe(e,{days:o=14,now:t=Date.now()}={}){let a=o?t-o*864e5:0,r={days:o||null,tracks:0,actions:0,byOrigin:{},byStrength:{strong:0,weak:0,flagged:0},byEvidence:{keyed:0,timing:0},commits:{total:0,keyed:0,timing:0,unrooted:0},byProvider:{},findings:[],integrity:{logs:0,headMissing:0,withGaps:0,withRepeats:0,chain:{intact:0,intactFromMidLog:0,broken:0,preChain:0}}};for(let i of e||[]){let c=Je(i.events||[],{trackId:i.trackId,name:i.name,since:a});r.integrity.logs++,c.integrity.headMissing&&r.integrity.headMissing++,c.integrity.gaps&&r.integrity.withGaps++,c.integrity.repeats&&r.integrity.withRepeats++;let p=c.integrity.chain?.state;if(p==="intact"?r.integrity.chain.intact++:p==="intact-from-mid-log"?r.integrity.chain.intactFromMidLog++:p==="broken"?r.integrity.chain.broken++:r.integrity.chain.preChain++,!(!c.actions&&!c.findings.length)){r.tracks++,r.actions+=c.actions;for(let f of Object.keys(r.byEvidence))r.byEvidence[f]+=c.byEvidence?.[f]||0;for(let f of Object.keys(r.commits))r.commits[f]+=c.commits?.[f]||0;for(let[f,s]of Object.entries(c.byOrigin))r.byOrigin[f]=(r.byOrigin[f]||0)+s,r.byStrength[X[f]||"flagged"]+=s;for(let[f,s]of Object.entries(c.byProvider))r.byProvider[f]||={actions:0,fidelity:s.fidelity,identified:!1},r.byProvider[f].actions+=s.actions,s.fidelity==="hook"&&(r.byProvider[f].fidelity="hook"),s.identified&&(r.byProvider[f].identified=!0);r.findings.push(...c.findings)}}return r.findings.sort((i,c)=>pe[i.severity]-pe[c.severity]||c.to-i.to),r.ok=!r.findings.some(i=>i.severity==="high"),r}var P=(e,o)=>o?`${(e/o*100).toFixed(e&&e/o<.001?2:1)}%`:"0%",Y=e=>new Date(e).toISOString().slice(0,16).replace("T"," ");function he(e,{limit:o=20}={}){let t=[];t.push(`AGENT ACTION AUDIT \xB7 ${e.days?`last ${e.days}d`:"all history"} \xB7 ${e.actions} action(s) across ${e.tracks} Track(s)`),t.push(""),t.push("Who asked for it");for(let p of["strong","weak","flagged"]){let f=Object.entries(e.byOrigin).filter(([s])=>(X[s]||"flagged")===p).sort((s,g)=>g[1]-s[1]);if(f.length){t.push(` ${p.toUpperCase()} \xB7 ${e.byStrength[p]} (${P(e.byStrength[p],e.actions)})`);for(let[s,g]of f)t.push(` ${s.padEnd(27)} ${String(g).padStart(7)} ${P(g,e.actions)}`)}}t.push("");let a=e.byEvidence||{keyed:0,timing:0};t.push(`Rooted by recorded key \xB7 ${a.keyed} (${P(a.keyed,e.actions)}) \xB7 by timing \xB7 ${a.timing} (${P(a.timing,e.actions)})`);let r=e.commits||{total:0,keyed:0,timing:0,unrooted:0};r.total&&t.push(`Commits \xB7 ${r.total}: ${r.keyed} cite their turn, ${r.timing} inside an open turn, ${r.unrooted} unrooted`),t.push(""),t.push("Evidence by provider");for(let[p,f]of Object.entries(e.byProvider).sort((s,g)=>g[1].actions-s[1].actions))t.push(` ${p.padEnd(10)} ${String(f.actions).padStart(7)} `+(f.fidelity==="hook"?`hook-recorded (turn boundaries known${f.identified?"; calls identified, intent and outcome paired":""})`:"transcript only (agent-written; no turn boundaries)"));t.push("");let i=e.integrity,c=i.chain||{intact:0,intactFromMidLog:0,broken:0,preChain:0};if(t.push(`Log integrity \xB7 ${i.logs} log(s): hash chain intact on ${c.intact} from seq 1 and ${c.intactFromMidLog} from mid-log, broken on ${c.broken}, ${c.preChain} pre-chain (written before the chain); ${i.headMissing} missing their head, ${i.withGaps} with seq gaps, ${i.withRepeats} with repeated seq`),t.push(" (the chain is walked over this node's copy \u2014 advisory; the plane's verified head is the anchor)"),t.push(""),!e.findings.length)t.push("Findings: none.");else{t.push(`Findings \xB7 ${e.findings.length}`);for(let p of e.findings.slice(0,o)){let f=p.to-p.from>A?`${Y(p.from)} \u2192 ${Y(p.to).slice(11)}`:Y(p.from),s=p.actions?`${p.count} prompt(s), ${p.actions} action(s)`:`${p.count}`;t.push(` [${p.severity}] ${p.rule} \xB7 ${p.track||p.trackId}${p.boxId?` \xB7 ${p.boxId}`:""} \xB7 ${f} \xB7 ${s}`),t.push(` ${p.note}`);for(let g of p.samples)t.push(` - ${g}`)}e.findings.length>o&&t.push(` \u2026 ${e.findings.length-o} more (--json for all)`)}return t.push(""),t.push(e.ok?"No action without an origin. The log is agent-writable, so this is evidence, not proof.":"Actions with NO origin were found \u2014 read the [high] findings above."),t.join(`
3
- `)}import Ge from"node:path";import Xe from"node:os";import{EventEmitter as Ve}from"node:events";var ze=new Ve;ze.setMaxListeners(0);var ft=process.env.BOSTRAT_STATE_DIR||Ge.join(process.env.HOME||Xe.tmpdir(),".bostrat");var Qe=/(?<!\\)((?:\\\\)*)\\u0000/g,ge=e=>e.includes("\\u0000"),me=e=>e.replace(Qe,"$1\\ufffd");var H=process.env.BOSTRAT_STATE_DIR||v.join(process.env.HOME||Ze.tmpdir(),".bostrat"),N=process.argv.slice(2),Z=e=>{let o=N.indexOf(e);return o>=0?N[o+1]:null};(N.includes("--help")||N.includes("-h"))&&(console.log("usage: bostrat-audit [--days N | --all] [--track <id-or-name>] [--limit N] [--json]"),process.exit(0));var ee=[];try{ee=JSON.parse(await L.readFile(v.join(H,"tracks.json"),"utf8")).tracks||[]}catch{}var et=new Map(ee.map(e=>[e.id,e.name])),te=new Set([v.join(H,"events")]);for(let e of ee)e.cwd&&te.add(v.join(e.cwd,".bostrat","events"));try{for(let e of await L.readdir(v.join(H,"workspaces")))te.add(v.join(H,"workspaces",e,".bostrat","events"))}catch{}var z=Z("--track"),ye=[];for(let e of te){let o=[];try{o=(await L.readdir(e)).filter(t=>t.endsWith(".ndjson"))}catch{continue}for(let t of o){let a=t.slice(0,-7),r=et.get(a)||null;if(z&&a!==z&&!(r||"").toLowerCase().includes(z.toLowerCase()))continue;let i=[];for(let c of(await L.readFile(v.join(e,t),"utf8")).split(`
4
- `))if(c.trim())try{i.push(JSON.parse(ge(c)?me(c):c))}catch{}i.length&&ye.push({trackId:a,name:r,events:i})}}var tt=N.includes("--all")?0:Number(Z("--days"))||14,Q=fe(ye,{days:tt});console.log(N.includes("--json")?JSON.stringify(Q,null,2):he(Q,{limit:Number(Z("--limit"))||20}));process.exit(Q.ok?0:2);
2
+ import G from"node:fs/promises";import Zt from"node:os";import C from"node:path";var Ye=(t,o)=>{if(t==null||t==="")return o;let e=Number(t);return Number.isFinite(e)&&e>=0?e:o},eo=Ye(process.env.BOSTRAT_HOOK_FOLD_MS,250);var Ge=1e3;function D(t){let o=Number(t?.count);return Number.isInteger(o)&&o>1&&t?.tools&&typeof t.tools=="object"?Math.min(o,Ge):1}function O(t){let o=t||{},e=D(o);if(e===1)return[o];let r=(Array.isArray(o.calls)?o.calls:[]).filter(n=>n&&typeof n=="object").slice(0,e),s={};for(let n of r)n.tool&&(s[n.tool]=(s[n.tool]||0)+1);for(let[n,l]of Object.entries(o.tools))for(let c=s[n]||0;c<Number(l)&&r.length<e;c++)r.push({tool:n});for(;r.length<e;)r.push({tool:null});return r}import{createHash as Ve}from"node:crypto";var Je=new Set(["userId"]);function Z(t){return t===null||typeof t!="object"?t===void 0||typeof t=="number"&&!Number.isFinite(t)?"null":JSON.stringify(t):Array.isArray(t)?`[${t.map(e=>Z(e===void 0?null:e)).join(",")}]`:`{${Object.keys(t).filter(e=>t[e]!==void 0).sort().map(e=>`${JSON.stringify(e)}:${Z(t[e])}`).join(",")}}`}function me(t){let o={};for(let e of Object.keys(t))Je.has(e)||(o[e]=t[e]);return Ve("sha256").update(Z(o)).digest("hex")}var ge=t=>Number.isFinite(t?.seq);function ye(t){let o={members:0,chained:0,preChain:0,intactFrom:null,intactTo:null,genesis:!1,breaks:[]},e=null,r=!1,s=(n,l)=>{e={seq:n.seq,hash:l},o.intactFrom=n.seq,o.genesis=n.seq===1&&n.prev===null};for(let n of t||[]){if(!ge(n))continue;if(o.members++,n.prev===void 0){e&&!r?(o.breaks.push({kind:"unchained",seq:n.seq,eventId:n.id??null}),r=!0):e||o.preChain++;continue}o.chained++;let l=me(n);if(!e||r){r=!1,s(n,l);continue}if(n.seq===e.seq+1){if(n.prev===e.hash){e={seq:n.seq,hash:l};continue}o.breaks.push({kind:"prev-mismatch",seq:n.seq,eventId:n.id??null,expected:e.hash,got:n.prev})}else n.seq>e.seq+1?o.breaks.push({kind:"seq-gap",seq:n.seq,eventId:n.id??null,from:e.seq+1,to:n.seq-1}):o.breaks.push({kind:"seq-repeat",seq:n.seq,eventId:n.id??null,headSeq:e.seq});s(n,l)}return o.intactTo=e?e.seq:null,e||(o.intactFrom=null),o}var M=6e4,Xe=120*M,be=2e3,we=5e3,Ze=2*M,Qe=5e3,et=2*M,B=5e3,tt={Workflow:360*M,Agent:60*M},ot=5*M,nt=10*M,ee=80,j=3,st=["Checkpoint: write a work-in-progress handoff","Resume from .bostrat/handoff/latest.md","Beat: write a","You are a SUBTASK agent working in an isolated","A subtask box you delegated has finished"],oe={operator:"strong",orchestrator:"strong","card-answer":"strong",loop:"strong","background-job":"strong","task-continuation":"strong","operator-terminal":"weak","orchestrator-unlogged":"weak","background-launch":"weak","task-continuation-unlogged":"weak",peer:"flagged","nested-session":"flagged","unknown-prompt":"flagged",unrooted:"flagged"},A=t=>String(t??"").replace(/\s+/g," ").trim(),f=t=>t?.ts??0,ne=(t,o)=>!!t&&!!o&&(t.startsWith(o.slice(0,ee))||o.startsWith(t.slice(0,ee))),rt=6,it=(t,o)=>ne(t,o)||t.length>=rt&&o.includes(t.slice(0,ee)),at=/^<pasted_content\b[^>]*>\s*/i,te=t=>A(t.payload?.promptHead??t.payload?.text).replace(at,""),lt=/^<cross-session-message\b/i,ct=/^<task-notification>/i,dt=/<tool-use-id>\s*([^<\s]+)\s*<\/tool-use-id>/i;function ke(t){let o=t.payload||{},e=D(o),r=O(o)[0],s=r.head||r.path||(o.command?A(o.command):""),n=t.type==="tool.failed"?" [failed]":t.type==="tool.started"?" [never completed]":"";return`${r.tool||"tool"}${s?`: ${s.slice(0,100)}`:""}${n}${e>1?` (+${e-1} more)`:""}`}var ut=/\.answered$/,pt=new Set(["loop.created","followup.created"]),ht=16,Ie=new Set(["tool.started","tool.called","tool.failed"]);function ft(){return{byId:new Map,byDelivery:new Map,byPrompt:new Map,byToolUse:new Map,jobs:new Map}}function mt(t,o){if(!o||typeof o.type!="string")return;o.id&&t.byId.set(o.id,o);let e=o.payload||{};if(o.type==="turn.user")o.source==="orchestrator"&&e.deliveryId&&t.byDelivery.set(e.deliveryId,o),o.source==="hook"&&e.promptId&&!t.byPrompt.has(`${o.boxId}\0${e.promptId}`)&&t.byPrompt.set(`${o.boxId}\0${e.promptId}`,o);else if(o.type==="job.started"&&e.id)t.jobs.set(e.id,o);else if(Ie.has(o.type)&&o.source==="hook")for(let r of O(e))r.toolUseId&&!t.byToolUse.has(r.toolUseId)&&t.byToolUse.set(r.toolUseId,o)}function gt(t){let o=ft();for(let e of t)mt(o,e);return o}function $e(t,o){let e=t;for(let r=0;e&&r<ht;r++){let s=e.payload||{},n=e.type;if(e.causationId&&o.byId.has(e.causationId)&&e.causationId!==e.id){e=o.byId.get(e.causationId);continue}if(Ie.has(n)){let l=s.promptId?o.byPrompt.get(`${e.boxId}\0${s.promptId}`):null;if(!l)return null;e=l;continue}if(n==="turn.user"){if(e.source==="hook"){if(s.kind==="task-notification"&&s.jobId){let c=o.jobs.get(s.jobId);if(!c)return null;e=c;continue}let l=s.deliveryId?o.byDelivery.get(s.deliveryId):null;if(!l)return null;e=l;continue}return e.source==="orchestrator"?s.loopId||s.producer==="loop"?{origin:"loop",root:e}:{origin:e.actor==="orchestrator"?"orchestrator":"operator",root:e}:e.source==="transcript"?{origin:"operator-terminal",root:e}:null}if(n==="job.started"){let l=s.id?o.byToolUse.get(s.id):null;if(!l)return null;e=l;continue}return ut.test(n)||pt.has(n)?{origin:"card-answer",root:e}:n==="peer.message"?{origin:"peer",root:e}:null}return null}function yt(t){let o={events:t.length,firstSeq:null,lastSeq:null,headMissing:!1,gaps:0,repeats:0},e=null;for(let s of t)Number.isFinite(s?.seq)&&(e===null?o.firstSeq=s.seq:s.seq>e+1?o.gaps++:s.seq<=e&&o.repeats++,e=s.seq);o.lastSeq=e,o.headMissing=o.firstSeq!==null&&o.firstSeq>1;let r=ye(t);return o.chain={state:r.chained===0?"pre-chain":r.breaks.length?"broken":r.genesis?"intact":"intact-from-mid-log",chained:r.chained,preChain:r.preChain,intactFrom:r.intactFrom,intactTo:r.intactTo,breaks:r.breaks},o}var bt=t=>{switch(t.kind){case"prev-mismatch":return`seq ${t.seq} states a predecessor that is not the line before it \u2014 the line before it changed, or was replaced`;case"seq-gap":return`seq ${t.from}${t.to!==t.from?`\u2013${t.to}`:""} missing between chained lines`;case"seq-repeat":return`seq ${t.seq} appears again after the chain passed it (a line was inserted, or the log was rewound)`;case"unchained":return`seq ${t.seq} carries no chain link after chained lines (an older node resumed this log)`;default:return`${t.kind} at seq ${t.seq}`}};function wt(t){let o=new Map,e=new Map,r=new Map,s=new Map,n=(i,h,m)=>{i.has(h)||i.set(h,[]),i.get(h).push(m)};for(let i of t)if((i.type==="box.state.changed"||i.type.startsWith("handoff."))&&n(s,i.payload?.box||i.boxId||null,f(i)),i.type==="session.ready"&&([...s.get(i.boxId)||[],...s.get(null)||[]].some(m=>m<=f(i)&&f(i)-m<=et)||n(r,i.boxId,f(i))),i.type==="turn.user")if(i.source==="orchestrator"){let h=(i.payload?.attachments||[]).map(m=>m?.id).filter(Boolean);n(o,i.boxId,{ts:f(i),head:A(i.payload?.text),files:h,actor:i.actor,usedAt:null})}else i.source==="transcript"&&n(e,i.boxId,{ts:f(i),head:A(i.payload?.text),note:i.payload?.note?.kind||null});let l=new Map,c=new Map,p=new Map;for(let i of t){if(i.type==="turn.user"&&i.source==="orchestrator"&&c.set(i.boxId,!0),i.source!=="hook")continue;if(i.type==="turn.agent"){let k=p.get(i.boxId)||0;k>0?p.set(i.boxId,k-1):c.set(i.boxId,!1);continue}if(i.type!=="turn.user")continue;let h=te(i),m=(()=>{if(i.actor==="peer"||lt.test(h))return{origin:"peer"};if(ct.test(h))return{origin:"task-continuation",jobId:h.match(dt)?.[1]||null};let k=(o.get(i.boxId)||[]).filter(y=>(y.usedAt===null||f(i)-y.usedAt<=we)&&y.ts>=f(i)-Xe&&y.ts<=f(i)+be&&(it(y.head,h)||!y.head&&y.files.length>0&&(y.files.some(_=>h.includes(`.bostrat/uploads/${_}`))||f(i)-y.ts<=we))),b=k[k.length-1];if(b)return b.usedAt=f(i),{origin:b.actor==="orchestrator"?"orchestrator":"operator"};if(st.some(y=>h.startsWith(y)))return{origin:"orchestrator-unlogged"};if((e.get(i.boxId)||[]).find(y=>!y.note&&y.ts>=f(i)-be&&y.ts<=f(i)+Ze&&ne(y.head,h)))return{origin:"operator-terminal"};let R=(r.get(i.boxId)||[]).some(y=>y<=f(i)&&f(i)-y<=Qe);return{origin:c.get(i.boxId)||R?"nested-session":"unknown-prompt"}})();l.set(i,m),m.origin==="nested-session"?p.set(i.boxId,(p.get(i.boxId)||0)+1):c.set(i.boxId,!0)}return l}function kt(t){let o=new Map,e=new Map;for(let r of t){let s=r.payload?.id;if(s)if(r.type==="job.started"){let n={from:(r.payload?.ts??f(r))-B,to:1/0,loggedAt:f(r)};e.set(s,n),o.has(r.boxId)||o.set(r.boxId,[]),o.get(r.boxId).push(n)}else r.type==="job.stopped"&&e.has(s)&&(e.get(s).to=f(r)+B)}return{byBox:o,byId:e}}function $t(t,{trackId:o=null,name:e=null,since:r=0}={}){let s=wt(t),n=kt(t),l=new Set;for(let a of t)a.type==="tool.called"&&a.source==="hook"&&l.add(a.boxId);let c=a=>a.type==="tool.called"&&(a.source==="hook"||!(a.provider==="claude"&&l.has(a.boxId)))||a.type==="tool.failed"&&a.source==="hook",p=new Set,i=new Map;for(let a of t)if(a.source==="hook")if(a.type==="tool.called"||a.type==="tool.failed")for(let d of O(a.payload))d.toolUseId&&p.add(d.toolUseId);else a.type==="audit.flagged"&&a.payload?.denied===!0&&a.payload.toolUseId?p.add(a.payload.toolUseId):(a.type==="turn.agent"||a.type==="session.ready"||a.type==="turn.aborted"||a.type==="turn.interrupted")&&(i.has(a.boxId)||i.set(a.boxId,[]),i.get(a.boxId).push(f(a)));let h=t.length?f(t[t.length-1]):0,m=a=>{if(a.type!=="tool.started"||a.source!=="hook")return null;let d=O(a.payload).filter($=>$.toolUseId&&!p.has($.toolUseId));return d.length&&((i.get(a.boxId)||[]).some($=>$>f(a))||h-f(a)>nt)?d:null},k={},b={},x={keyed:0,timing:0},R=gt(t),y=new Map,_=(a,d,u,$,I,g=1)=>{let W=`${a}\0${u.boxId}\0${$}`,S=y.get(W);return(!S||f(u)-S.to>ot)&&(S={rule:a,severity:d,trackId:o,track:e,boxId:u.boxId,from:f(u),to:f(u),count:0,note:I,samples:[]},y.set(W,S),F.push(S)),S.to=f(u),S.count+=g,S},F=[],X=new Map,ze=a=>(X.has(a)||X.set(a,{open:!1,origin:null,nested:0,soft:null,lastSendHead:null,launch:null}),X.get(a));for(let a of t){let d=ze(a.boxId),u=f(a)>=r;if(a.type==="session.foreign"){if(a.payload?.phase==="prompted"&&u){let w=_("nested-session","medium",a,"","a session that is not the box's own was prompted through this box \u2014 typically an agent-launched `claude -p`");w.samples.length<j&&w.samples.push(A(a.payload?.promptHead).slice(0,100))}continue}if(a.type==="turn.user"&&a.source==="hook"){let w=s.get(a);if(w.origin==="nested-session"){if(d.nested++,u){let q=_("nested-session","medium",a,"","a prompt no recorded send accounts for arrived mid-turn or right after a SessionStart \u2014 typically an agent-launched `claude -p`");q.samples.length<j&&q.samples.push(te(a).slice(0,100))}continue}if(d.open=!0,d.origin=w.origin,w.origin==="task-continuation"&&!n.byId.has(w.jobId)&&(d.origin="task-continuation-unlogged"),d.origin==="unknown-prompt"&&u){let q=_("unknown-prompt","medium",a,"","a turn opened by a prompt with no operator, machinery or job record behind it");q.samples.length<j&&q.samples.push(te(a).slice(0,100))}}else if(a.type==="turn.agent"&&a.source==="hook")d.nested>0?d.nested--:d.open=!1;else if(a.type==="turn.aborted"||a.type==="turn.interrupted")d.open=!1;else if(a.type==="turn.user"&&a.source==="orchestrator")d.lastSendHead=A(a.payload?.text),d.soft=a.actor==="orchestrator"?"orchestrator":"operator",d.open=!0,d.origin=d.soft;else if(a.type==="turn.user"&&a.source==="transcript"){let w=A(a.payload?.text);!a.payload?.note&&!ne(w,d.lastSendHead)&&(d.soft="operator-terminal")}else a.type==="peer.message"&&(d.soft="peer");let $=m(a);if(!$&&!c(a))continue;let I=$?$.length:a.source==="hook"?D(a.payload):1,g;if(a.payload?.foreignSession)g="nested-session";else if(a.source==="hook"){let w=(n.byBox.get(a.boxId)||[]).some(N=>f(a)>=N.from&&f(a)<=N.to);d.open?g=d.origin:w?g="background-job":d.nested>0?g="nested-session":d.launch&&f(a)<=d.launch?g="background-launch":g="unrooted";let q=(n.byBox.get(a.boxId)||[]).some(N=>N.loggedAt<=f(a)+B);for(let N of new Set(O(a.payload).map(fe=>fe.tool)))(N==="Workflow"||N==="Agent"&&!q)&&d.open&&oe[d.origin]!=="flagged"&&(d.launch=Math.max(d.launch||0,f(a)+tt[N]))}else g=d.soft||"unrooted";let W=a.source==="hook"&&!a.payload?.foreignSession?$e(a,R):null;if(W&&(g=W.origin),!u)continue;x[W?"keyed":"timing"]+=I,k[g]=(k[g]||0)+I;let S=a.provider||"unknown";if(b[S]||={actions:0,fidelity:a.source==="hook"?"hook":"transcript",identified:!1},b[S].actions+=I,a.source==="hook"&&(b[S].fidelity="hook"),a.source==="hook"&&O(a.payload).some(w=>w.toolUseId)&&(b[S].identified=!0),$){let w=_("unfinished-calls","low",a,"","calls the CLI began (PreToolUse) and never reported complete or failed \u2014 killed, crashed or restarted mid-call; the tool may have run",I);w.samples.length<j&&w.samples.push(ke(a))}if(g==="unrooted"){let w=_("unrooted-actions","high",a,"","tool calls with no open turn, no recorded job and no launch that accounts for them",I);w.samples.length<j&&w.samples.push(ke(a))}else if(g==="peer")_("peer-driven-actions","low",a,"","tool calls in a turn another session's message opened",I);else if(g==="nested-session"||g==="unknown-prompt"){let w=y.get(`${g}\0${a.boxId}\0`);w&&(w.actions=(w.actions||0)+I)}}let H={total:0,keyed:0,timing:0,unrooted:0};{let a=new Map,d=new Map;for(let u of t)u.source==="hook"&&(u.type==="turn.user"?d.set(u.boxId,f(u)):(u.type==="turn.agent"||u.type==="turn.aborted"||u.type==="turn.interrupted")&&d.has(u.boxId)&&((a.get(u.boxId)||a.set(u.boxId,[]).get(u.boxId)).push([d.get(u.boxId),f(u)]),d.delete(u.boxId)));for(let[u,$]of d)(a.get(u)||a.set(u,[]).get(u)).push([$,1/0]);for(let u of t){if(u.type!=="code.committed"||u.source!=="hook"||f(u)<r)continue;H.total++;let $=Number(u.payload?.ts??u.ts)||f(u);if($e(u,R))H.keyed++;else if((a.get(u.boxId)||[]).some(([I,g])=>$>=I-B&&$<=g+B))H.timing++;else{H.unrooted++;let I=_("unrooted-commit","medium",u,"","a commit landed in the box's workspace with no turn open and no recorded cause");I.samples.length<j&&I.samples.push(`${String(u.payload?.sha||"").slice(0,7)} ${A(u.payload?.subject).slice(0,80)}`)}}}{let a=t.filter(d=>d.type==="audit.flagged"&&d.source!=="plane"&&d.payload?.denied===!0&&f(d)>=r);if(a.length){let d=[...new Set(a.map(u=>u.payload?.rule).filter(Boolean))];F.push({rule:"guard-denied",severity:"high",trackId:o,track:e,boxId:a[0].boxId??null,from:f(a[0]),to:f(a.at(-1)),count:a.length,samples:a.slice(0,j).map(u=>`${u.payload?.rule||"?"}: ${A(u.payload?.samples?.[0]||u.payload?.tool||"")}`.slice(0,160)),note:`${a.length} call(s) denied before running by the node's PreToolUse guard (${d.join(", ")}) \u2014 BOSTRAT_AUDIT_GUARD is on for this node`})}}let T=yt(t),he=Object.values(k).reduce((a,d)=>a+d,0);if(T.headMissing&&he&&F.push({rule:"log-head-missing",severity:"medium",trackId:o,track:e,boxId:null,from:f(t[0]),to:f(t[0]),count:1,samples:[],note:`the log starts at seq ${T.firstSeq} \u2014 its earlier history is not on this node`}),T.chain.breaks.length){let a=new Map;for(let g of t)Number.isFinite(g?.seq)&&!a.has(g.seq)&&a.set(g.seq,g);let d=T.chain.breaks.filter(g=>g.kind==="prev-mismatch"||g.kind==="seq-repeat"),u=g=>f(a.get(g.seq))||f(t.at(-1)),$=T.chain.breaks[0],I=T.chain.breaks.at(-1);F.push({rule:"chain-broken",severity:d.length?"high":"medium",trackId:o,track:e,boxId:null,from:u($),to:u(I),count:T.chain.breaks.length,samples:T.chain.breaks.slice(0,j).map(bt),note:`the log's hash chain breaks ${T.chain.breaks.length} time(s) on this node \u2014 advisory: the plane's verified head is the anchor (GET /plane/admin/chain/${o??"<track>"})`})}return{trackId:o,track:e,actions:he,byOrigin:k,byEvidence:x,byProvider:b,commits:H,findings:F,integrity:T}}var xe={high:0,medium:1,low:2};function Se(t,{days:o=14,now:e=Date.now()}={}){let r=o?e-o*864e5:0,s={days:o||null,tracks:0,actions:0,byOrigin:{},byStrength:{strong:0,weak:0,flagged:0},byEvidence:{keyed:0,timing:0},commits:{total:0,keyed:0,timing:0,unrooted:0},byProvider:{},findings:[],integrity:{logs:0,headMissing:0,withGaps:0,withRepeats:0,chain:{intact:0,intactFromMidLog:0,broken:0,preChain:0}}};for(let n of t||[]){let l=$t(n.events||[],{trackId:n.trackId,name:n.name,since:r});s.integrity.logs++,l.integrity.headMissing&&s.integrity.headMissing++,l.integrity.gaps&&s.integrity.withGaps++,l.integrity.repeats&&s.integrity.withRepeats++;let c=l.integrity.chain?.state;if(c==="intact"?s.integrity.chain.intact++:c==="intact-from-mid-log"?s.integrity.chain.intactFromMidLog++:c==="broken"?s.integrity.chain.broken++:s.integrity.chain.preChain++,!(!l.actions&&!l.findings.length)){s.tracks++,s.actions+=l.actions;for(let p of Object.keys(s.byEvidence))s.byEvidence[p]+=l.byEvidence?.[p]||0;for(let p of Object.keys(s.commits))s.commits[p]+=l.commits?.[p]||0;for(let[p,i]of Object.entries(l.byOrigin))s.byOrigin[p]=(s.byOrigin[p]||0)+i,s.byStrength[oe[p]||"flagged"]+=i;for(let[p,i]of Object.entries(l.byProvider))s.byProvider[p]||={actions:0,fidelity:i.fidelity,identified:!1},s.byProvider[p].actions+=i.actions,i.fidelity==="hook"&&(s.byProvider[p].fidelity="hook"),i.identified&&(s.byProvider[p].identified=!0);s.findings.push(...l.findings)}}return s.findings.sort((n,l)=>xe[n.severity]-xe[l.severity]||l.to-n.to),s.ok=!s.findings.some(n=>n.severity==="high"),s}var z=(t,o)=>o?`${(t/o*100).toFixed(t&&t/o<.001?2:1)}%`:"0%",Q=t=>new Date(t).toISOString().slice(0,16).replace("T"," ");function Ee(t,{limit:o=20}={}){let e=[];e.push(`AGENT ACTION AUDIT \xB7 ${t.days?`last ${t.days}d`:"all history"} \xB7 ${t.actions} action(s) across ${t.tracks} Track(s)`),e.push(""),e.push("Who asked for it");for(let c of["strong","weak","flagged"]){let p=Object.entries(t.byOrigin).filter(([i])=>(oe[i]||"flagged")===c).sort((i,h)=>h[1]-i[1]);if(p.length){e.push(` ${c.toUpperCase()} \xB7 ${t.byStrength[c]} (${z(t.byStrength[c],t.actions)})`);for(let[i,h]of p)e.push(` ${i.padEnd(27)} ${String(h).padStart(7)} ${z(h,t.actions)}`)}}e.push("");let r=t.byEvidence||{keyed:0,timing:0};e.push(`Rooted by recorded key \xB7 ${r.keyed} (${z(r.keyed,t.actions)}) \xB7 by timing \xB7 ${r.timing} (${z(r.timing,t.actions)})`);let s=t.commits||{total:0,keyed:0,timing:0,unrooted:0};s.total&&e.push(`Commits \xB7 ${s.total}: ${s.keyed} cite their turn, ${s.timing} inside an open turn, ${s.unrooted} unrooted`),e.push(""),e.push("Evidence by provider");for(let[c,p]of Object.entries(t.byProvider).sort((i,h)=>h[1].actions-i[1].actions))e.push(` ${c.padEnd(10)} ${String(p.actions).padStart(7)} `+(p.fidelity==="hook"?`hook-recorded (turn boundaries known${p.identified?"; calls identified, intent and outcome paired":""})`:"transcript only (agent-written; no turn boundaries)"));e.push("");let n=t.integrity,l=n.chain||{intact:0,intactFromMidLog:0,broken:0,preChain:0};if(e.push(`Log integrity \xB7 ${n.logs} log(s): hash chain intact on ${l.intact} from seq 1 and ${l.intactFromMidLog} from mid-log, broken on ${l.broken}, ${l.preChain} pre-chain (written before the chain); ${n.headMissing} missing their head, ${n.withGaps} with seq gaps, ${n.withRepeats} with repeated seq`),e.push(" (the chain is walked over this node's copy \u2014 advisory; the plane's verified head is the anchor)"),e.push(""),!t.findings.length)e.push("Findings: none.");else{e.push(`Findings \xB7 ${t.findings.length}`);for(let c of t.findings.slice(0,o)){let p=c.to-c.from>M?`${Q(c.from)} \u2192 ${Q(c.to).slice(11)}`:Q(c.from),i=c.actions?`${c.count} prompt(s), ${c.actions} action(s)`:`${c.count}`;e.push(` [${c.severity}] ${c.rule} \xB7 ${c.track||c.trackId}${c.boxId?` \xB7 ${c.boxId}`:""} \xB7 ${p} \xB7 ${i}`),e.push(` ${c.note}`);for(let h of c.samples)e.push(` - ${h}`)}t.findings.length>o&&e.push(` \u2026 ${t.findings.length-o} more (--json for all)`)}return e.push(""),e.push(t.ok?"No action without an origin. The log is agent-writable, so this is evidence, not proof.":"Actions with NO origin were found \u2014 read the [high] findings above."),e.join(`
3
+ `)}var xt="BP-AU-R4",qe=160,ve={high:0,medium:1,low:2},Te=200,_e=5,Oe=8,Ae=5,Ne=10*6e4,It=Object.freeze(["localhost","127.0.0.1","0.0.0.0","github.com","api.github.com","raw.githubusercontent.com","objects.githubusercontent.com","registry.npmjs.org","pypi.org","files.pythonhosted.org"]),St=5e3,ie=new Set(["tool.called","tool.failed"]),se=new Set(["Write","Edit","NotebookEdit"]),Et=t=>String(t??"").replace(/\s+/g," ").trim(),P=(t,o=120)=>Et(t).slice(0,o);function vt(t,o=qe){let e=String(t??""),r=e.split(/\s*(?:;|&&|\|\||\||\n)\s*/).map(s=>s.trim()).filter(Boolean);return Number.isFinite(o)&&e.length>=o&&r.length&&r.pop(),r}function Y(t){return String(t??"").replace(/\d?>>?\s*\S+|<\s*\S+|2>&1/g," ").trim().split(/\s+/).filter(Boolean)}function De(t){let o=0;for(;o<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[o]);)o++;return{cmd:t[o]??null,rest:t.slice(o+1),at:o}}function je(t){let o=Y(t),e=o.findIndex(i=>i==="git"||i.endsWith("/git"));if(e<0)return null;for(e++;e<o.length&&o[e].startsWith("-");)(o[e]==="-C"||o[e]==="-c")&&e++,e++;if(o[e]!=="push")return null;let r=[],s=[];for(let i=e+1;i<o.length;i++){let h=o[i];h.startsWith("-")?(r.push(h),(h==="-o"||h==="--push-option"||h==="--repo"||h==="--receive-pack"||h==="--exec")&&i++):s.push(h)}let n=r.some(i=>i==="--force"||/^-[a-zA-Z]+$/.test(i)&&i.includes("f"))||s.some(i=>i.startsWith("+")),l=r.some(i=>i.startsWith("--force-with-lease")||i.startsWith("--force-if-includes")),c=s[0]??null,p=s.slice(1).map(i=>i.replace(/^["']|["']$/g,"").replace(/^\+/,"")).map(i=>i.includes(":")?i.slice(i.indexOf(":")+1):i).filter(i=>i&&!i.startsWith("$"));return{force:n,lease:l,remote:c,dsts:p}}var ae=String.raw`(?:~|\$HOME|\$\{HOME\}|/home/[^\s/"']+|/root|/Users/[^\s/"']+)`,Tt=new RegExp(`${ae}/\\.ssh(?:/|\\b)`),_t=new RegExp(`${ae}/(?:\\.claude\\.json\\b|\\.claude/\\.credentials\\.json|\\.codex/auth\\.json|\\.cursor(?:/|\\b))`),Ot=/(?:^|[\s/"'=(])(\.env(?:\.[A-Za-z0-9_.-]+)?)(?=$|[\s"'|;&)])/g,At=/^\.env\.(?:example|sample|template|dist)$/,Pe=/(\.claude\/settings(?:\.local)?\.json|\.claude\/hooks\/[^\s"']*|\.bostrat\/events(?:\/[^\s"']*)?)/,Ce=new RegExp(`((?:/etc|/usr/lib|/lib|/run)/systemd/[^\\s"']*|${ae}/\\.config/systemd/[^\\s"']*|/etc/cron(?:tab|\\.d|\\.hourly|\\.daily|\\.weekly|\\.monthly)(?:/[^\\s"']*)?|/var/spool/cron(?:/[^\\s"']*)?)`),Nt=/^(?:enable|disable|start|stop|restart|try-restart|reload|reload-or-restart|daemon-reload|daemon-reexec|link|mask|unmask|edit|preset|preset-all|set-property|revert|isolate|kill|reset-failed|import-environment|set-environment|add-wants|add-requires)$/,jt=/^\/tmp\/|\/\.bostrat\/tmp\//,Mt=/^(?:refs\/heads\/)?(?:main|master|develop|development|trunk|production|prod|staging|release(?:\/|$)|v\d)/,Rt=/(?:^|\/)track\/|^HEAD$|^refs\/bostrat\//,qt=/https?:\/\/([a-z0-9.-]+\.[a-z]{2,}|localhost|\d+\.\d+\.\d+\.\d+)(?::\d+)?/gi,Me=t=>Tt.test(t)||_t.test(t),Re=t=>[...String(t??"").matchAll(Ot)].some(o=>!At.test(o[1])),Dt=t=>Pe.test(t),Pt=t=>Ce.test(t),Ct=t=>(t.startsWith("/")||t.startsWith("~"))&&!jt.test(t);function We(t){let{cmd:o,at:e}=De(t);if(o==="sudo"){for(e++;e<t.length&&t[e].startsWith("-");)e++;o=t[e]??null}return{cmd:o,at:e}}function Ue(t,o){let e=String(t??"").match(o);if(!e)return null;let r=e[1],s=r.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&");if(new RegExp(`>{1,2}\\s*["']?[^\\s"']*${s}`).test(t))return"redirect";let n=Y(t),{cmd:l}=We(n);return!l||!n.some(c=>c.includes(r))?null:/^(?:rm|mv|truncate|chmod|chown|tee|install|shred|unlink|ln|mkdir|touch)$/.test(l)?l:l==="sed"&&n.some(c=>/^-[a-zA-Z]*i/.test(c))?"sed -i":l==="cp"&&n[n.length-1].includes(r)?"cp":/^(?:python3?|perl|node|ruby)$/.test(l)&&/open\([^)]*['"][wa]|writeFile|write_text|appendFile|fs\.write/.test(t)?`${l} write`:null}var Wt=t=>Ue(t,Pe);function Ut(t){let o=Y(t),{cmd:e,at:r}=We(o);if(!e)return null;let s=o.slice(r+1);if(e==="crontab"||e.endsWith("/crontab")){let l=!1,c=!1;for(let p=0;p<s.length;p++){if(s[p]==="-u"){p++;continue}s[p]==="-l"||/^-(?:h|V|T|-help|-version)$/.test(s[p])?l=!0:c=!0}return c||!l?"crontab":null}if(e==="systemctl"||e.endsWith("/systemctl")){let l=s.find(c=>!c.startsWith("-"));return l&&Nt.test(l)?`systemctl ${l}`:null}if((e==="loginctl"||e.endsWith("/loginctl"))&&s.includes("enable-linger"))return"loginctl enable-linger";if(e==="at"&&s.length&&/^(?:now|midnight|noon|teatime|today|tomorrow|next|\d|-[fqmvt])/.test(s[0]))return"at";let n=Ue(t,Ce);return n?`${n} unit/cron path`:null}function Lt(t){let o=new Set;for(let e of String(t??"").matchAll(qt))o.add(e[1].toLowerCase());return[...o]}function Ft({knownHosts:t=[]}={}){return{known:new Set([...It,...[...t].map(o=>String(o).toLowerCase()).filter(Boolean)]),hosts:new Set,tracks:new Map}}function Ht(t,o){let e=t.tracks.get(o??"");return e||t.tracks.set(o??"",e={costs:[],peer:new Map}),e}var E=(t,o,e,r)=>Object.freeze({severity:t,requirement:xt,note:o,measured:e,detect:r}),K=(t,o)=>{let e=0,r=null;for(let s of t.calls)if(s.head)for(let n of vt(s.head,t.headCap)){let l=o(n,s);l&&(e++,r??=P(l))}return e?{count:e,sample:r}:null},re=(t,o)=>{let e=0,r=null;for(let s of t.calls){let n=o(s);n&&(e++,r??=P(n))}return e?{count:e,sample:r}:null},U=Object.freeze({"force-push":E("high","git push --force / -f / +refspec in a command head (--force-with-lease, the Track's own rebase flow, is not one)","2026-10-21 fleet replay \xB7 0 hits / 98,690 hook calls \xB7 1,080 logs 2026-08\u219210 \xB7 58 --force-with-lease pushes excluded by design \u2192 high",(t,o)=>K(o,e=>{let r=je(e);return r&&r.force&&!r.lease?e:null})),"protected-config-write":E("high","a write to the box's own harness: .claude/settings*.json, a .claude/hooks/ script or the Track's .bostrat/events/ log \u2014 by a file tool, a redirect, rm/mv/tee/sed -i, or a scripted open-for-write (reads are not hits)","2026-10-21 fleet replay \xB7 0 hits / 98,690 hook calls \xB7 165 reads of those paths (cat, grep, python json.loads) excluded by design \u2192 high",(t,o)=>{let e=0,r=null;for(let n of o.calls)se.has(n.tool)&&n.path&&Dt(n.path)&&(e++,r??=P(`${n.tool} ${n.path}`));let s=K(o,n=>{let l=Wt(n);return l?`${l}: ${n}`:null});return s&&(e+=s.count,r??=s.sample),e?{count:e,sample:r}:null}),"persistence-install":E("medium","a shell segment that installs something the OS runs on its own \u2014 crontab (install / edit / remove; -l is a read), a mutating systemctl verb (enable / start / restart / daemon-reload \u2026; status / show / cat / list / is-* are reads), loginctl enable-linger, at / batch \u2014 or a write (file tool, redirect, cp / mv / tee / ln / sed -i) into a systemd unit or cron directory: how a process outlives its turn by the OS's hand (BP-AU-D6's other half)","2026-10-21 fleet replay \xB7 11 hits / 99,122 hook calls \xB7 10 Tracks \xB7 0 in the last 14 d \xB7 every hit operator-asked service work on the operator's own Pi (systemctl --user restart/stop/start of bostrat-node, tmp-sweep, a samba disable, one `crontab -` install for a backfill) \xB7 the bare `at` word a quoted `|` regex leaves in a segment (4 hits) excluded by design \u2192 medium (rail), the guard's deny when opted in",(t,o)=>{let e=0,r=null;for(let n of o.calls)se.has(n.tool)&&n.path&&Pt(n.path)&&(e++,r??=P(`${n.tool} ${n.path}`));let s=K(o,n=>{let l=Ut(n);return l?`${l}: ${n}`:null});return s&&(e+=s.count,r??=s.sample),e?{count:e,sample:r}:null}),"push-outside-track":E("medium","git push to a protected branch (main/master/develop/release\u2026), to a branch that is not a Track branch, or to a remote other than origin/upstream \u2014 a Track's own code leaves on its track/ branch or the WIP shadow ref","2026-10-21 fleet replay \xB7 7 hits / 98,690 hook calls \xB7 4 Tracks \xB7 0 in the last 14 d \xB7 every hit operator-instructed work on another repo (two dep/ branches, a fork's multiplayer branch, one HEAD:main) \u2192 medium, not a page",(t,o)=>K(o,e=>{let r=je(e);return r&&(r.remote&&!/^(?:origin|upstream)$/.test(r.remote)&&!r.remote.startsWith("$")&&!r.remote.startsWith("-")||r.dsts.some(s=>Mt.test(s)||!Rt.test(s)))?e:null})),"credential-read":E("medium","a command head or file path naming SSH material (~/.ssh) or a vendor auth file (~/.claude.json, ~/.claude/.credentials.json, ~/.codex/auth.json, ~/.cursor) \u2014 the box-auth policy's denylist shapes; ~/.claude/projects (transcripts) is not one","2026-10-21 fleet replay \xB7 12 hits / 98,690 hook calls \xB7 8 Tracks \xB7 3 in the last 14 d \xB7 every hit an operator-asked inspection on the operator's own node (ssh config for a host alias, stat/keys of ~/.claude.json) \u2192 medium until a 14-day window reads 0",(t,o)=>re(o,e=>e.head&&Me(e.head)?e.head:e.path&&Me(e.path)?`${e.tool} ${e.path}`:null)),"dotenv-read":E("low","a command head or file path naming a .env file (.env, .env.local, .env.production \u2026; the committed .env.example / .sample / .template are not ones)","2026-10-21 fleet replay \xB7 309 hits / 98,690 hook calls \xB7 44 Tracks \xB7 0 in the last 14 d \xB7 all of them an instructed `source \u2026/almanac/.env` on the operator's other repos \u2192 low (report only)",(t,o)=>re(o,e=>e.head&&Re(e.head)?e.head:e.path&&Re(e.path)?`${e.tool} ${e.path}`:null)),"privileged-command":E("medium","a shell segment whose command is sudo or docker (after any VAR=value prefix) \u2014 host-level reach from inside a box","2026-10-21 fleet replay \xB7 220 hits (183 events) / 98,690 hook calls \xB7 57 Tracks \xB7 3 in the last 14 d \xB7 sudo = the operator's own journalctl/systemctl asks on the Pi, docker = instructed compose/psql work on the operator's other services \u2192 medium (a hosted node's first hit is the number to watch)",(t,o)=>K(o,e=>{let{cmd:r}=De(Y(e));return r==="sudo"||r==="docker"?e:null})),"write-outside-workspace":E("low","a file tool (Write / Edit / NotebookEdit) on an absolute path \u2014 the hook strips the box's workspace prefix, so an absolute path is outside it \u2014 that is not the box's scratch dir (/tmp/\u2026, \u2026/.bostrat/tmp/\u2026)","2026-10-21 fleet replay \xB7 106 hits / 98,690 hook calls \xB7 10 Tracks \xB7 44 in the last 14 d \xB7 the operator's other repos and Agent-tool worktrees under .bostrat/repos on the operator's own node \u2192 low (report only)",(t,o)=>re(o,e=>se.has(e.tool)&&e.path&&Ct(e.path)?`${e.tool} ${e.path}`:null)),"egress-new-host":E("low","a command head reaching, by URL, a host no box in the fleet has reached before (this projection's lifetime, seeded from the warm tails; KNOWN_HOSTS + PLANE_AUDIT_KNOWN_HOSTS never count) \u2014 a baseline-growth signal, so each host is reported once","2026-10-21 fleet replay \xB7 140 first sightings / 98,690 hook calls \xB7 69 Tracks \xB7 8 in the last 14 d \xB7 198 if the baseline were per Track \xB7 every host a vendor API, a docs site or the operator's own services \u2192 low (report only)",(t,o)=>{let e=0,r=null;for(let s of o.calls)if(s.head)for(let n of Lt(s.head))o.state.known.has(n)||o.state.hosts.has(n)||(o.state.hosts.add(n),o.state.hosts.size>St&&o.state.hosts.delete(o.state.hosts.values().next().value),e++,r??=P(`${n} \xB7 ${s.head}`));return e?{count:e,sample:r}:null}),"spend-spike":E("low",`a cost.recorded turn over ${Oe}\xD7 the Track's running median (its last ${Te} cost events, at least ${_e} of them) and over $${Ae} \u2014 a turn that cost far more than this Track's turns do`,"2026-10-21 fleet replay \xB7 114 hits / 8,421 cost events \xB7 64 Tracks \xB7 2 in the last 14 d \xB7 every hit a long build turn after short prompts (a $25\u201378 turn on a $0.37 median) \u2014 real spend, no one's attack \u2192 low (report only)",(t,o)=>{if(t.type!=="cost.recorded")return null;let e=o.track.costs,r=Number(t.payload?.usd);if(!Number.isFinite(r)||r<0)return null;let s=null;if(e.length>=_e&&r>=Ae){let n=[...e].sort((c,p)=>c-p),l=n[Math.floor(n.length/2)];r>Oe*l&&(s={count:1,sample:`$${r.toFixed(2)} vs median $${l.toFixed(2)} over ${e.length} turns${t.payload?.model?` \xB7 ${t.payload.model}`:""}`})}return e.push(r),e.length>Te&&e.shift(),s}),"peer-injected-call":E("medium",`a tool call within ${Ne/6e4} min of a peer.message on the same box with no operator or node-typed turn in between \u2014 the cross-session injection vector (peer-message.js); a peer is never a root (BP-AU-D1)`,"2026-10-21 fleet replay \xB7 0 peer.message events in 288,395 \xB7 the replay cannot bound this rule's rate, so it stays medium (rail) until a window with peer traffic has been measured; the shape itself is BP-AU-D1's stated R4 case",(t,o)=>{if(!o.calls.length)return null;let e=o.track.peer.get(o.boxKey);if(e==null||o.ts-e>Ne||o.ts<e)return null;let r=o.calls[0];return{count:o.count,sample:P(`${Math.round((o.ts-e)/1e3)}s after a peer message \xB7 ${r.tool}${r.head?`: ${r.head}`:r.path?` ${r.path}`:""}`)}}),"foreign-session-call":E("medium","a hook-recorded tool call from a claude session that is not the box's own (payload.foreignSession, BP-AU-I12): a nested or stray CLI driving the box's hooks \u2014 R3 never roots it, this names it","2026-10-21 fleet replay \xB7 14 hits / 98,744 hook calls \xB7 3 Tracks \xB7 4 in the last 14 d \xB7 all the xscout loop's nested claude prompts, I12's own acceptance case \u2192 medium (rail), not a page",(t,o)=>{if(!o.calls.length||!t.payload?.foreignSession)return null;let e=o.calls[0];return{count:o.count,sample:P(`session ${String(t.payload.sessionId||"?").slice(0,8)} \xB7 ${e.tool}${e.head?`: ${e.head}`:e.path?` ${e.path}`:""}`)}})}),L=Object.freeze(Object.keys(U)),Bt=new Set([...ie,"cost.recorded","peer.message","turn.user"]);function Kt(t,o,{rules:e=null,headCap:r=qe}={}){if(!o||!Bt.has(o.type)||o.source==="plane")return[];let s=Ht(t,o.trackId),n=o.payload||{},l=o.boxId??"",c=Number(o.ts)||0;if(o.type==="turn.user")return(o.actor==="user"||o.actor==="orchestrator")&&s.peer.delete(l),[];if(o.type==="peer.message")return s.peer.set(l,c),[];let p=ie.has(o.type)&&o.source==="hook",h={calls:p?O(n):[],count:p?D(n):0,track:s,state:t,ts:c,boxKey:l,headCap:r},m=[];for(let k of e||L){let b=U[k];if(!b)continue;let x=null;try{x=b.detect(o,h)}catch{x=null}x&&x.count>0&&m.push({rule:k,count:x.count,sample:x.sample??null})}return m}function Le(t,{days:o=14,now:e=Date.now(),rules:r=null}={}){let s=o?e-o*864e5:0,n=Ft(),l=r||L,c={days:o||null,logs:0,events:0,calls:0,callsInWindow:0,rules:Object.fromEntries(l.map(i=>[i,{severity:U[i].severity,note:U[i].note,measured:U[i].measured,hits:0,hitsInWindow:0,events:0,tracks:0,tracksInWindow:0,perTenK:0,samples:[]}]))},p=Object.fromEntries(l.map(i=>[i,{all:new Set,win:new Set}]));for(let i of t||[]){let h=Array.isArray(i?.events)?[...i.events].sort((m,k)=>(Number(m.ts)||0)-(Number(k.ts)||0)):[];if(h.length){c.logs++;for(let m of h){c.events++;let k=(Number(m.ts)||0)>=s;if(ie.has(m.type)&&m.source==="hook"){let b=D(m.payload||{});c.calls+=b,k&&(c.callsInWindow+=b)}for(let b of Kt(n,m,{rules:l})){let x=c.rules[b.rule];if(x.hits+=b.count,x.events++,p[b.rule].all.add(m.trackId??i.trackId),k&&(x.hitsInWindow+=b.count,p[b.rule].win.add(m.trackId??i.trackId)),b.sample){let R=x.samples.find(y=>y.text===b.sample);R?R.n++:x.samples.length<200&&x.samples.push({text:b.sample,n:1,ts:Number(m.ts)||0,trackId:m.trackId??i.trackId,name:i.name??null})}}}}}for(let i of l){let h=c.rules[i];h.tracks=p[i].all.size,h.tracksInWindow=p[i].win.size,h.perTenK=c.calls?Number((h.hits/c.calls*1e4).toFixed(2)):0,h.samples.sort((m,k)=>k.n-m.n||k.ts-m.ts),h.samples=h.samples.slice(0,50)}return c.ok=!l.some(i=>U[i].severity==="high"&&c.rules[i].hitsInWindow>0),c}var zt=t=>new Date(t).toISOString().slice(0,10);function Fe(t,{samples:o=5}={}){let e=[];e.push(`R4 DETECTOR REPLAY \xB7 ${t.days?`window last ${t.days}d`:"all history"} \xB7 ${t.logs} logs \xB7 ${t.events.toLocaleString()} events \xB7 ${t.calls.toLocaleString()} hook calls (${t.callsInWindow.toLocaleString()} in window)`),e.push("A rule's severity is what its measured rate supports; `high` pages (D7). Hits are what the plane fold would have flagged.");let r=Object.keys(t.rules).sort((s,n)=>ve[t.rules[s].severity]-ve[t.rules[n].severity]||s.localeCompare(n));for(let s of r){let n=t.rules[s];e.push(""),e.push(`${s} [${n.severity}] \xB7 ${n.hits} hit(s) all-time (${n.events} events, ${n.tracks} Tracks, ${n.perTenK}/10k calls) \xB7 ${n.hitsInWindow} in window (${n.tracksInWindow} Tracks)`),e.push(` ${n.note}`),n.measured&&e.push(` measured: ${n.measured}`);for(let l of n.samples.slice(0,o))e.push(` ${l.n}\xD7 ${zt(l.ts)} ${l.name?`${l.name} `:""}(${l.trackId}) ${l.text}`)}return e.push(""),e.push(t.ok?"ok: no high-severity detector hit in the window":"ATTENTION: a high-severity detector hit inside the window (exit 2)"),e.join(`
4
+ `)}import Yt from"node:path";import Gt from"node:os";import{EventEmitter as Vt}from"node:events";var Jt=new Vt;Jt.setMaxListeners(0);var fo=process.env.BOSTRAT_STATE_DIR||Yt.join(process.env.HOME||Gt.tmpdir(),".bostrat");var Xt=/(?<!\\)((?:\\\\)*)\\u0000/g,He=t=>t.includes("\\u0000"),Be=t=>t.replace(Xt,"$1\\ufffd");var V=process.env.BOSTRAT_STATE_DIR||C.join(process.env.HOME||Zt.tmpdir(),".bostrat"),v=process.argv.slice(2),J=t=>{let o=v.indexOf(t);return o>=0?v[o+1]:null};(v.includes("--help")||v.includes("-h"))&&(console.log("usage: bostrat-audit [--days N | --all] [--track <id-or-name>] [--limit N] [--json]"),console.log(" bostrat-audit --detectors [--days N | --all] [--track <id-or-name>] [--rule <name>]... [--limit N] [--json]"),console.log(` rules: ${L.join(", ")}`),process.exit(0));var de=[];try{de=JSON.parse(await G.readFile(C.join(V,"tracks.json"),"utf8")).tracks||[]}catch{}var Qt=new Map(de.map(t=>[t.id,t.name])),ue=new Set([C.join(V,"events")]);for(let t of de)t.cwd&&ue.add(C.join(t.cwd,".bostrat","events"));try{for(let t of await G.readdir(C.join(V,"workspaces")))ue.add(C.join(V,"workspaces",t,".bostrat","events"))}catch{}var le=J("--track"),pe=[];for(let t of ue){let o=[];try{o=(await G.readdir(t)).filter(e=>e.endsWith(".ndjson"))}catch{continue}for(let e of o){let r=e.slice(0,-7),s=Qt.get(r)||null;if(le&&r!==le&&!(s||"").toLowerCase().includes(le.toLowerCase()))continue;let n=[];for(let l of(await G.readFile(C.join(t,e),"utf8")).split(`
5
+ `))if(l.trim())try{n.push(JSON.parse(He(l)?Be(l):l))}catch{}n.length&&pe.push({trackId:r,name:s,events:n})}}var Ke=v.includes("--all")?0:Number(J("--days"))||14;if(v.includes("--detectors")){let t=v.flatMap((r,s)=>r==="--rule"&&v[s+1]?[v[s+1]]:[]),o=t.filter(r=>!L.includes(r));o.length&&(console.error(`unknown rule(s): ${o.join(", ")} \u2014 known: ${L.join(", ")}`),process.exit(1));let e=Le(pe,{days:Ke,rules:t.length?t:null});console.log(v.includes("--json")?JSON.stringify(e,null,2):Fe(e,{samples:Number(J("--limit"))||5})),process.exit(e.ok?0:2)}var ce=Se(pe,{days:Ke});console.log(v.includes("--json")?JSON.stringify(ce,null,2):Ee(ce,{limit:Number(J("--limit"))||20}));process.exit(ce.ok?0:2);
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ var w=process.env.BOSTRAT_AGENT_URL||`http://127.0.0.1:${process.env.BOSTRAT_AGENT_PORT||3362}`;async function p(n,l,s){let o=await fetch(`${w}${l}`,{method:n,headers:s?{"content-type":"application/json"}:void 0,body:s?JSON.stringify(s):void 0}),e=await o.json().catch(()=>({}));if(!o.ok)throw new Error(e.error||`HTTP ${o.status}`);return e}function a(n){console.error(`[bostrat-estimate] ${n}`),process.exit(1)}function d(n){let l=Number(n)||0;if(l<60)return`${l}m`;let s=l/60;if(s<8)return`${Number.isInteger(s)?s:s.toFixed(1)}h`;let o=s/8;return`${Number.isInteger(o)?o:o.toFixed(1)}d`}var $=n=>n?new Date(n).toISOString().slice(0,10):"?",c=process.argv.slice(2),f=c.shift(),g='usage: bostrat-estimate record --human <dur> --agent <dur> --scope "<one line, \u2264160 chars>" [--bp BP-XX-I3 | --ticket KEY-123]',m='usage: bostrat-estimate close <estimate-id> [--note "<what landed>"] (or: close --latest)';if(f==="record"){let n=null,l=null,s=null,o=null,e=null,i=[];for(let t=0;t<c.length;t++)c[t]==="--human"?n=c[++t]:c[t]==="--agent"?l=c[++t]:c[t]==="--scope"?s=c[++t]:c[t]==="--bp"?o=c[++t]:c[t]==="--ticket"?e=c[++t]:i.push(c[t]);!s&&i.length&&(s=i.join(" ").trim()),(!n||!l||!s)&&a(g);try{let t=await p("POST","/api/estimates/record",{cwd:process.cwd(),human:n,agent:l,scope:s,bp:o,ticket:e}),u=t.bp?` for ${t.bp}`:t.ticket?` for ${t.ticket}`:"",r=[t.provider,t.model].filter(Boolean).join(" \xB7 ");console.log(`[bostrat-estimate] recorded ${t.estimateId}${u}: human ${d(t.human.minutes)} \xB7 agent-active ${d(t.agent.minutes)}${r?` (${r})`:""}`),console.log(` \u201C${t.scope}\u201D \u2014 close it when the work lands: bostrat-estimate close ${t.estimateId}`)}catch(t){a(`${t.message}
3
+ ${g}`)}}else if(f==="close"){let n=null,l=!1,s="";for(let o=0;o<c.length;o++)c[o]==="--latest"?l=!0:c[o]==="--note"?s=c[++o]:!n&&!c[o].startsWith("--")?n=c[o]:a(m);!n&&!l&&a(m);try{let o=await p("POST","/api/estimates/close",{cwd:process.cwd(),estimateId:n,latest:l,note:s});console.log(`[bostrat-estimate] closed ${o.estimateId} \u2014 \u201C${o.scope}\u201D`),console.log(" Its actuals are folded from this Track's own log and held against the estimate.")}catch(o){a(`${o.message}
4
+ ${m}`)}}else if(f==="ls"){let n=c.includes("--open");try{let{estimates:l,counts:s}=await p("GET",`/api/estimates?cwd=${encodeURIComponent(process.cwd())}`),o=n?l.filter(e=>e.status==="open"):l;o.length||console.log(`[bostrat-estimate] ${n?"no open estimates":"nothing recorded"} on this Track yet`);for(let e of o){let i=e.status==="open"?"o":e.status==="expired"?"!":"x",t=e.bp||e.ticket||"",u=[e.provider,e.model].filter(Boolean).join(" \xB7 ");console.log(`${i} ${e.estimateId.padEnd(13)} ${$(e.recordedAt)} human ${d(e.human?.minutes).padEnd(6)} agent ${d(e.agent?.minutes).padEnd(6)} ${t.padEnd(12)} ${e.scope}`);let r=e.status==="closed"?`closed ${$(e.closedAt)} (${e.closeReason}${e.closeRef?` ${e.closeRef}`:""})`:e.status==="expired"?`expired ${$(e.closedAt)} \u2014 unclosed`:null,h=[u,r?`${r}${e.closeNote?` \u2014 ${e.closeNote}`:""}`:null].filter(Boolean).join(" \xB7 ");h&&console.log(` ${h}`)}if(s&&o.length){let e=s.unclosed??s.open+(s.expired||0);console.log(` (${s.open} open \xB7 ${s.closed} closed${s.expired?` \xB7 ${s.expired} expired`:""} \u2014 ${e} unclosed)`)}}catch(l){a(l.message)}}else a("usage: bostrat-estimate <record|close|ls> \u2026");
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ var p=process.env.BOSTRAT_AGENT_URL||`http://127.0.0.1:${process.env.BOSTRAT_AGENT_PORT||3362}`,c=process.argv.slice(2),$=c.shift(),r=e=>{console.error(`[bostrat-track] ${e}`),process.exit(1)};async function u(e,t,n){let o=await fetch(`${p}${t}`,{method:e,headers:n?{"content-type":"application/json"}:void 0,body:n?JSON.stringify(n):void 0}),l=await o.json().catch(()=>({}));if(!o.ok)throw new Error(l.error||`HTTP ${o.status}`);return l}var f=["contextFull"],w=["contextFull","contextFullPct","contextFullTokens","limitHit"],i="usage: bostrat-track flow [set <field>=<value> ... [--owner]] (fields: contextFull=prompt|auto|off[|default]; --owner also contextFullPct=<1-100>, contextFullTokens=<n|null>, limitHit=prompt|auto|off)",d=e=>{let t=e.owner?.flow||{},n=t.contextFullTokens?`${t.contextFullTokens} tokens (absolute pin)`:`${t.contextFullPct??75}% of the model's window`;if(console.log(` owner default contextFull=${t.contextFull??"prompt"} \xB7 rung ${n} \xB7 limitHit=${t.limitHit??"prompt"}${e.owner?.source?` [${e.owner.source}]`:""}`),e.track){let o=e.track.refreshFlow?.contextFull,l=e.track.refreshFlow?.autoPausedUntil&&e.track.refreshFlow.autoPausedUntil>Date.now();console.log(` this Track contextFull=${o??`${t.contextFull??"prompt"} (owner default)`}${l?` \xB7 auto PAUSED until ${new Date(e.track.refreshFlow.autoPausedUntil).toLocaleString()} (two failed refreshes in a row)`:""}`),console.log(` in force ${e.track.effective?.mode??o??t.contextFull??"prompt"}`)}console.log("(prompt = one-tap offer card \xB7 auto = Bostrat refreshes at the next turn boundary and leaves a receipt \xB7 off = chip only)")};try{if($!=="flow"&&r("usage: bostrat-track flow [set <field>=<value> ... [--owner]]"),c[0]==="set"){let e=c.includes("--owner"),t={};for(let o of c.slice(1)){if(o==="--owner")continue;let l=o.match(/^([A-Za-z]+)=([A-Za-z0-9.-]+|null)$/);l||r(`bad assignment "${o}" \u2014 ${i}`);let[,a,s]=l;(e?w:f).includes(a)||r(e?`unknown field "${a}" \u2014 owner-level fields: ${w.join(", ")}`:`"${a}" is an owner-level rule \u2014 add --owner (per-Track fields: ${f.join(", ")})`),t[a]=s==="null"||s==="default"?null:/^[0-9.]+$/.test(s)?Number(s):s}Object.keys(t).length||r(i);let n=await u("POST","/api/refresh-flow",{cwd:process.cwd(),level:e?"owner":"track",set:t});console.log(`[bostrat-track] ${e?"owner":"Track"} refresh rules updated:`),d(n)}else if(c.length)r(i);else{let e=await u("GET",`/api/refresh-flow?cwd=${encodeURIComponent(process.cwd())}`);console.log("[bostrat-track] context-refresh automation:"),d(e)}}catch(e){r(e?.message||String(e))}