bostrat-node 1.17.1 → 1.17.2

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,7 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import te from"node:fs/promises";import Do from"node:os";import L from"node:path";var yt=(e,o)=>{if(e==null||e==="")return o;let t=Number(e);return Number.isFinite(t)&&t>=0?t:o},Uo=yt(process.env.BOSTRAT_HOOK_FOLD_MS,250);var bt=1e3;function F(e){let o=Number(e?.count);return Number.isInteger(o)&&o>1&&e?.tools&&typeof e.tools=="object"?Math.min(o,bt):1}function v(e){let o=e||{},t=F(o);if(t===1)return[o];let n=(Array.isArray(o.calls)?o.calls:[]).filter(s=>s&&typeof s=="object").slice(0,t),r={};for(let s of n)s.tool&&(r[s.tool]=(r[s.tool]||0)+1);for(let[s,c]of Object.entries(o.tools))for(let u=r[s]||0;u<Number(c)&&n.length<t;u++)n.push({tool:s});for(;n.length<t;)n.push({tool:null});return n}import{createHash as wt}from"node:crypto";var kt=new Set(["userId"]);function ie(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=>ie(t===void 0?null:t)).join(",")}]`:`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${ie(e[t])}`).join(",")}}`}function Te(e){let o={};for(let t of Object.keys(e))kt.has(t)||(o[t]=e[t]);return wt("sha256").update(ie(o)).digest("hex")}var Oe=e=>Number.isFinite(e?.seq);function Ae(e){let o={members:0,chained:0,preChain:0,intactFrom:null,intactTo:null,genesis:!1,breaks:[]},t=null,n=!1,r=(s,c)=>{t={seq:s.seq,hash:c},o.intactFrom=s.seq,o.genesis=s.seq===1&&s.prev===null};for(let s of e||[]){if(!Oe(s))continue;if(o.members++,s.prev===void 0){t&&!n?(o.breaks.push({kind:"unchained",seq:s.seq,eventId:s.id??null}),n=!0):t||o.preChain++;continue}o.chained++;let c=Te(s);if(!t||n){n=!1,r(s,c);continue}if(s.seq===t.seq+1){if(s.prev===t.hash){t={seq:s.seq,hash:c};continue}o.breaks.push({kind:"prev-mismatch",seq:s.seq,eventId:s.id??null,expected:t.hash,got:s.prev})}else s.seq>t.seq+1?o.breaks.push({kind:"seq-gap",seq:s.seq,eventId:s.id??null,from:t.seq+1,to:s.seq-1}):o.breaks.push({kind:"seq-repeat",seq:s.seq,eventId:s.id??null,headSeq:t.seq});r(s,c)}return o.intactTo=t?t.seq:null,t||(o.intactFrom=null),o}var M=6e4,$t=120*M,ve=2e3,Ne=5e3,St=2*M,xt=5e3,Et=2*M,X=5e3,_t={Workflow:360*M,Agent:60*M},It=5*M,Tt=10*M,le=80,N=3,Ot=["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"],de={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"},De={claude:{source:"hook",note:"hook-sourced: the CLI's hooks record the turn start (prompt_id), each call's intent and outcome (tool_use_id), failed calls and the Stop; the transcript is the duplicate"},codex:{source:"transcript",note:"transcript-sourced (a file the agent writes): the rollout names each turn (turn_id, turn_trigger, parent_turn_id) and each call (call_id), so a call cites the send that opened its turn; no intent before a call, no failed-call record, no turn end on the log, and a prompt typed at the pane is not on the log"},cursor:{source:"transcript",note:"transcript-sourced (a store the agent writes): message order is the turn structure, so a call cites the user message that opened its turn (its content hash); no turn ids, no per-message time (ts is synthesized), no intent, no failed-call record, no turn end, and a prompt typed at the pane is not on the log"}},R=e=>String(e??"").replace(/\s+/g," ").trim(),h=e=>e?.ts??0,pe=(e,o)=>!!e&&!!o&&(e.startsWith(o.slice(0,le))||o.startsWith(e.slice(0,le))),At=6,vt=(e,o)=>pe(e,o)||e.length>=At&&o.includes(e.slice(0,le)),Nt=/^<pasted_content\b[^>]*>\s*/i,ue=e=>R(e.payload?.promptHead??e.payload?.text).replace(Nt,""),Rt=/^<cross-session-message\b/i,jt=/^<task-notification>/i,Dt=/<tool-use-id>\s*([^<\s]+)\s*<\/tool-use-id>/i;function ae(e){let o=e.payload||{},t=F(o),n=v(o)[0],r=n.head||n.path||(o.command?R(o.command):""),s=e.type==="tool.failed"?" [failed]":e.type==="tool.started"?" [never completed]":"";return`${n.tool||"tool"}${r?`: ${r.slice(0,100)}`:""}${s}${t>1?` (+${t-1} more)`:""}`}var Mt=/\.answered$/,Pt=new Set(["loop.created","followup.created"]),Ut=16,Me=new Set(["tool.started","tool.called","tool.failed"]);function Ct(){return{byId:new Map,byDelivery:new Map,byPrompt:new Map,byToolUse:new Map,jobs:new Map}}function Ft(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(Me.has(o.type)&&o.source==="hook")for(let n of v(t))n.toolUseId&&!e.byToolUse.has(n.toolUseId)&&e.byToolUse.set(n.toolUseId,o)}function Lt(e){let o=Ct();for(let t of e)Ft(o,t);return o}function Re(e,o){let t=e;for(let n=0;t&&n<Ut;n++){let r=t.payload||{},s=t.type;if(t.causationId&&o.byId.has(t.causationId)&&t.causationId!==t.id){t=o.byId.get(t.causationId);continue}if(Me.has(s)){let c=r.promptId?o.byPrompt.get(`${t.boxId}\0${r.promptId}`):null;if(!c)return null;t=c;continue}if(s==="turn.user"){if(t.source==="hook"){if(r.kind==="task-notification"&&r.jobId){let u=o.jobs.get(r.jobId);if(!u)return null;t=u;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(s==="job.started"){let c=r.id?o.byToolUse.get(r.id):null;if(!c)return null;t=c;continue}return Mt.test(s)||Pt.has(s)?{origin:"card-answer",root:t}:s==="peer.message"?{origin:"peer",root:t}:null}return null}function Bt(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 n=Ae(e);return o.chain={state:n.chained===0?"pre-chain":n.breaks.length?"broken":n.genesis?"intact":"intact-from-mid-log",chained:n.chained,preChain:n.preChain,intactFrom:n.intactFrom,intactTo:n.intactTo,breaks:n.breaks},o}var Ht=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 qt(e){let o=new Map,t=new Map,n=new Map,r=new Map,s=(i,d,m)=>{i.has(d)||i.set(d,[]),i.get(d).push(m)};for(let i of e)if((i.type==="box.state.changed"||i.type.startsWith("handoff."))&&s(r,i.payload?.box||i.boxId||null,h(i)),i.type==="session.ready"&&([...r.get(i.boxId)||[],...r.get(null)||[]].some(m=>m<=h(i)&&h(i)-m<=Et)||s(n,i.boxId,h(i))),i.type==="turn.user")if(i.source==="orchestrator"){let d=(i.payload?.attachments||[]).map(m=>m?.id).filter(Boolean);s(o,i.boxId,{ts:h(i),head:R(i.payload?.text),files:d,actor:i.actor,usedAt:null})}else i.source==="transcript"&&s(t,i.boxId,{ts:h(i),head:R(i.payload?.text),note:i.payload?.note?.kind||null});let c=new Map,u=new Map,l=new Map;for(let i of e){if(i.type==="turn.user"&&i.source==="orchestrator"&&u.set(i.boxId,!0),i.source!=="hook")continue;if(i.type==="turn.agent"){let k=l.get(i.boxId)||0;k>0?l.set(i.boxId,k-1):u.set(i.boxId,!1);continue}if(i.type!=="turn.user")continue;let d=ue(i),m=(()=>{if(i.actor==="peer"||Rt.test(d))return{origin:"peer"};if(jt.test(d))return{origin:"task-continuation",jobId:d.match(Dt)?.[1]||null};let k=(o.get(i.boxId)||[]).filter(w=>(w.usedAt===null||h(i)-w.usedAt<=Ne)&&w.ts>=h(i)-$t&&w.ts<=h(i)+ve&&(vt(w.head,d)||!w.head&&w.files.length>0&&(w.files.some(O=>d.includes(`.bostrat/uploads/${O}`))||h(i)-w.ts<=Ne))),b=k[k.length-1];if(b)return b.usedAt=h(i),{origin:b.actor==="orchestrator"?"orchestrator":"operator"};if(Ot.some(w=>d.startsWith(w)))return{origin:"orchestrator-unlogged"};if((t.get(i.boxId)||[]).find(w=>!w.note&&w.ts>=h(i)-ve&&w.ts<=h(i)+St&&pe(w.head,d)))return{origin:"operator-terminal"};let U=(n.get(i.boxId)||[]).some(w=>w<=h(i)&&h(i)-w<=xt);return{origin:u.get(i.boxId)||U?"nested-session":"unknown-prompt"}})();c.set(i,m),m.origin==="nested-session"?l.set(i.boxId,(l.get(i.boxId)||0)+1):u.set(i.boxId,!0)}return c}function Wt(e){let o=new Map,t=new Map;for(let n of e){let r=n.payload?.id;if(r)if(n.type==="job.started"){let s={from:(n.payload?.ts??h(n))-X,to:1/0,loggedAt:h(n)};t.set(r,s),o.has(n.boxId)||o.set(n.boxId,[]),o.get(n.boxId).push(s)}else n.type==="job.stopped"&&t.has(r)&&(t.get(r).to=h(n)+X)}return{byBox:o,byId:t}}function Kt(e,{trackId:o=null,name:t=null,since:n=0}={}){let r=qt(e),s=Wt(e),c=new Set;for(let a of e)a.type==="tool.called"&&a.source==="hook"&&c.add(a.boxId);let u=a=>a.type==="tool.called"&&(a.source==="hook"||!(a.provider==="claude"&&c.has(a.boxId)))||a.type==="tool.failed"&&a.source==="hook",l=new Set,i=new Map;for(let a of e)if(a.source==="hook")if(a.type==="tool.called"||a.type==="tool.failed")for(let p of v(a.payload))p.toolUseId&&l.add(p.toolUseId);else a.type==="audit.flagged"&&a.payload?.denied===!0&&a.payload.toolUseId?l.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(h(a)));let d=e.length?h(e[e.length-1]):0,m=a=>{if(a.type!=="tool.started"||a.source!=="hook")return null;let p=v(a.payload).filter($=>$.toolUseId&&!l.has($.toolUseId));return p.length&&((i.get(a.boxId)||[]).some($=>$>h(a))||d-h(a)>Tt)?p:null},k={},b={},x={keyed:0,turn:0,timing:0},U=Lt(e),w=new Map,O=(a,p,f,$,S,g=1)=>{let j=`${a}\0${f.boxId}\0${$}`,I=w.get(j);return(!I||h(f)-I.to>It)&&(I={rule:a,severity:p,trackId:o,track:t,boxId:f.boxId,from:h(f),to:h(f),count:0,note:S,samples:[]},w.set(j,I),K.push(I)),I.to=h(f),I.count+=g,I},K=[],re=new Map,mt=a=>(re.has(a)||re.set(a,{open:!1,origin:null,nested:0,soft:null,lastSendHead:null,launch:null}),re.get(a));for(let a of e){let p=mt(a.boxId),f=h(a)>=n;if(a.type==="session.foreign"){if(a.payload?.phase==="prompted"&&f){let y=O("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`");y.samples.length<N&&y.samples.push(R(a.payload?.promptHead).slice(0,100))}continue}if(a.type==="turn.user"&&a.source==="hook"){let y=r.get(a);if(y.origin==="nested-session"){if(p.nested++,f){let C=O("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`");C.samples.length<N&&C.samples.push(ue(a).slice(0,100))}continue}if(p.open=!0,p.origin=y.origin,y.origin==="task-continuation"&&!s.byId.has(y.jobId)&&(p.origin="task-continuation-unlogged"),p.origin==="unknown-prompt"&&f){let C=O("unknown-prompt","medium",a,"","a turn opened by a prompt with no operator, machinery or job record behind it");C.samples.length<N&&C.samples.push(ue(a).slice(0,100))}}else if(a.type==="turn.agent"&&a.source==="hook")p.nested>0?p.nested--:p.open=!1;else if(a.type==="turn.aborted"||a.type==="turn.interrupted")p.open=!1;else if(a.type==="turn.user"&&a.source==="orchestrator")p.lastSendHead=R(a.payload?.text),p.soft=a.actor==="orchestrator"?"orchestrator":"operator",p.open=!0,p.origin=p.soft;else if(a.type==="turn.user"&&a.source==="transcript"){let y=R(a.payload?.text);!a.payload?.note&&!pe(y,p.lastSendHead)&&(p.soft="operator-terminal")}else a.type==="peer.message"&&(p.soft="peer");let $=m(a);if(!$&&!u(a))continue;let S=$?$.length:a.source==="hook"?F(a.payload):1,g;if(a.payload?.foreignSession)g="nested-session";else if(a.source==="hook"){let y=(s.byBox.get(a.boxId)||[]).some(D=>h(a)>=D.from&&h(a)<=D.to);p.open?g=p.origin:y?g="background-job":p.nested>0?g="nested-session":p.launch&&h(a)<=p.launch?g="background-launch":g="unrooted";let C=(s.byBox.get(a.boxId)||[]).some(D=>D.loggedAt<=h(a)+X);for(let D of v(a.payload)){let se=D.tool,gt=!!D.toolUseId&&s.byId.has(D.toolUseId);(se==="Workflow"&&!gt||se==="Agent"&&!C)&&p.open&&de[p.origin]!=="flagged"&&(p.launch=Math.max(p.launch||0,h(a)+_t[se]))}}else a.payload?.turnId?g=String(a.payload.turnTrigger||"user")==="user"?"operator-terminal":"unknown-prompt":g=p.soft||"unrooted";let j=a.payload?.foreignSession?null:Re(a,U);if(j&&(g=j.origin),!f)continue;let I=!j&&a.source!=="hook"&&!!a.payload?.turnId;x[j?"keyed":I?"turn":"timing"]+=S,k[g]=(k[g]||0)+S;let B=a.provider||"unknown";if(b[B]||={actions:0,fidelity:a.source==="hook"?"hook":"transcript",identified:!1,turnKeyed:!1,rooted:{key:0,turn:0,timing:0}},b[B].actions+=S,b[B].rooted[j?"key":I?"turn":"timing"]+=S,a.source==="hook"&&(b[B].fidelity="hook"),a.source==="hook"&&v(a.payload).some(y=>y.toolUseId)&&(b[B].identified=!0),a.source!=="hook"&&a.payload?.turnId&&(b[B].turnKeyed=!0),g==="unknown-prompt"&&a.source!=="hook"){let y=O("unexplained-turn","medium",a,String(a.payload.turnId),`calls in a transcript turn the CLI says no prompt opened (turn_trigger: ${String(a.payload.turnTrigger)}) and that cites no recorded cause`,S);y.samples.length<N&&y.samples.push(ae(a));continue}if($){let y=O("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",S);y.samples.length<N&&y.samples.push(ae(a))}if(g==="unrooted"){let y=O("unrooted-actions","high",a,"","tool calls with no open turn, no recorded job and no launch that accounts for them",S);y.samples.length<N&&y.samples.push(ae(a))}else if(g==="peer")O("peer-driven-actions","low",a,"","tool calls in a turn another session's message opened",S);else if(g==="nested-session"||g==="unknown-prompt"){let y=w.get(`${g}\0${a.boxId}\0`);y&&(y.actions=(y.actions||0)+S)}}let G={total:0,keyed:0,timing:0,unrooted:0};{let a=new Map,p=new Map;for(let f of e)f.source==="hook"&&(f.type==="turn.user"?p.set(f.boxId,h(f)):(f.type==="turn.agent"||f.type==="turn.aborted"||f.type==="turn.interrupted")&&p.has(f.boxId)&&((a.get(f.boxId)||a.set(f.boxId,[]).get(f.boxId)).push([p.get(f.boxId),h(f)]),p.delete(f.boxId)));for(let[f,$]of p)(a.get(f)||a.set(f,[]).get(f)).push([$,1/0]);for(let f of e){if(f.type!=="code.committed"||f.source!=="hook"||h(f)<n)continue;G.total++;let $=Number(f.payload?.ts??f.ts)||h(f);if(Re(f,U))G.keyed++;else if((a.get(f.boxId)||[]).some(([S,g])=>$>=S-X&&$<=g+X))G.timing++;else{G.unrooted++;let S=O("unrooted-commit","medium",f,"","a commit landed in the box's workspace with no turn open and no recorded cause");S.samples.length<N&&S.samples.push(`${String(f.payload?.sha||"").slice(0,7)} ${R(f.payload?.subject).slice(0,80)}`)}}}{let a=e.filter(p=>p.type==="audit.flagged"&&p.source!=="plane"&&p.payload?.denied===!0&&h(p)>=n);if(a.length){let p=[...new Set(a.map(f=>f.payload?.rule).filter(Boolean))];K.push({rule:"guard-denied",severity:"high",trackId:o,track:t,boxId:a[0].boxId??null,from:h(a[0]),to:h(a.at(-1)),count:a.length,samples:a.slice(0,N).map(f=>`${f.payload?.rule||"?"}: ${R(f.payload?.samples?.[0]||f.payload?.tool||"")}`.slice(0,160)),note:`${a.length} call(s) denied before running by the node's PreToolUse guard (${p.join(", ")}) \u2014 BOSTRAT_AUDIT_GUARD is on for this node`})}}let A=Bt(e),Ie=Object.values(k).reduce((a,p)=>a+p,0);if(A.headMissing&&Ie&&K.push({rule:"log-head-missing",severity:"medium",trackId:o,track:t,boxId:null,from:h(e[0]),to:h(e[0]),count:1,samples:[],note:`the log starts at seq ${A.firstSeq} \u2014 its earlier history is not on this node`}),A.chain.breaks.length){let a=new Map;for(let g of e)Number.isFinite(g?.seq)&&!a.has(g.seq)&&a.set(g.seq,g);let p=A.chain.breaks.filter(g=>g.kind==="prev-mismatch"||g.kind==="seq-repeat"),f=g=>h(a.get(g.seq))||h(e.at(-1)),$=A.chain.breaks[0],S=A.chain.breaks.at(-1);K.push({rule:"chain-broken",severity:p.length?"high":"medium",trackId:o,track:t,boxId:null,from:f($),to:f(S),count:A.chain.breaks.length,samples:A.chain.breaks.slice(0,N).map(Ht),note:`the log's hash chain breaks ${A.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:Ie,byOrigin:k,byEvidence:x,byProvider:b,commits:G,findings:K,integrity:A}}var je={high:0,medium:1,low:2};function Pe(e,{days:o=14,now:t=Date.now()}={}){let n=o?t-o*864e5:0,r={days:o||null,tracks:0,actions:0,byOrigin:{},byStrength:{strong:0,weak:0,flagged:0},byEvidence:{keyed:0,turn: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 s of e||[]){let c=Kt(s.events||[],{trackId:s.trackId,name:s.name,since:n});r.integrity.logs++,c.integrity.headMissing&&r.integrity.headMissing++,c.integrity.gaps&&r.integrity.withGaps++,c.integrity.repeats&&r.integrity.withRepeats++;let u=c.integrity.chain?.state;if(u==="intact"?r.integrity.chain.intact++:u==="intact-from-mid-log"?r.integrity.chain.intactFromMidLog++:u==="broken"?r.integrity.chain.broken++:r.integrity.chain.preChain++,!(!c.actions&&!c.findings.length)){r.tracks++,r.actions+=c.actions;for(let l of Object.keys(r.byEvidence))r.byEvidence[l]+=c.byEvidence?.[l]||0;for(let l of Object.keys(r.commits))r.commits[l]+=c.commits?.[l]||0;for(let[l,i]of Object.entries(c.byOrigin))r.byOrigin[l]=(r.byOrigin[l]||0)+i,r.byStrength[de[l]||"flagged"]+=i;for(let[l,i]of Object.entries(c.byProvider)){r.byProvider[l]||={actions:0,fidelity:i.fidelity,identified:!1,turnKeyed:!1,rooted:{key:0,turn:0,timing:0}},r.byProvider[l].actions+=i.actions,i.fidelity==="hook"&&(r.byProvider[l].fidelity="hook"),i.identified&&(r.byProvider[l].identified=!0),i.turnKeyed&&(r.byProvider[l].turnKeyed=!0);for(let d of["key","turn","timing"])r.byProvider[l].rooted[d]+=i.rooted?.[d]||0}r.findings.push(...c.findings)}}for(let[s,c]of Object.entries(r.byProvider))c.note=De[s]?.note??(c.fidelity==="hook"?"hook-sourced":"transcript-sourced (a record the agent writes); no turn structure read by its adapter \u2014 calls attributed to the latest prompt");return r.findings.sort((s,c)=>je[s.severity]-je[c.severity]||c.to-s.to),r.ok=!r.findings.some(s=>s.severity==="high"),r}var V=(e,o)=>o?`${(e/o*100).toFixed(e&&e/o<.001?2:1)}%`:"0%",ce=e=>new Date(e).toISOString().slice(0,16).replace("T"," ");function Ue(e,{limit:o=20,containment:t=null}={}){let n=[];n.push(`AGENT ACTION AUDIT \xB7 ${e.days?`last ${e.days}d`:"all history"} \xB7 ${e.actions} action(s) across ${e.tracks} Track(s)`),n.push(""),n.push("Who asked for it");for(let l of["strong","weak","flagged"]){let i=Object.entries(e.byOrigin).filter(([d])=>(de[d]||"flagged")===l).sort((d,m)=>m[1]-d[1]);if(i.length){n.push(` ${l.toUpperCase()} \xB7 ${e.byStrength[l]} (${V(e.byStrength[l],e.actions)})`);for(let[d,m]of i)n.push(` ${d.padEnd(27)} ${String(m).padStart(7)} ${V(m,e.actions)}`)}}n.push("");let r=e.byEvidence||{keyed:0,turn:0,timing:0};n.push(`Rooted by recorded key \xB7 ${r.keyed} (${V(r.keyed,e.actions)})`+(r.turn?` \xB7 by its transcript turn only \xB7 ${r.turn} (${V(r.turn,e.actions)})`:"")+` \xB7 by timing \xB7 ${r.timing} (${V(r.timing,e.actions)})`);let s=e.commits||{total:0,keyed:0,timing:0,unrooted:0};s.total&&n.push(`Commits \xB7 ${s.total}: ${s.keyed} cite their turn, ${s.timing} inside an open turn, ${s.unrooted} unrooted`),n.push(""),n.push("Evidence by provider");for(let[l,i]of Object.entries(e.byProvider).sort((d,m)=>m[1].actions-d[1].actions)){let d=i.rooted||{key:0,turn:0,timing:0},m=i.fidelity==="hook"?`${d.key} by recorded key \xB7 ${d.timing} by timing`:i.turnKeyed?`${d.key} cite the send that opened their turn \xB7 ${d.turn} cite only their transcript turn \xB7 ${d.timing} by timing (no turn key)`:"all by timing (attributed to the latest prompt)";n.push(` ${l.padEnd(10)} ${String(i.actions).padStart(7)} `+(i.fidelity==="hook"?`hook-recorded (turn boundaries known${i.identified?"; calls identified, intent and outcome paired":""})`:i.turnKeyed?"transcript-recorded (agent-written; turns keyed by the CLI's own record)":"transcript only (agent-written; no turn boundaries)")+` \xB7 ${m}`);let k=i.note??De[l]?.note;k&&n.push(` ${k}`)}n.push("");let c=e.integrity,u=c.chain||{intact:0,intactFromMidLog:0,broken:0,preChain:0};if(n.push(`Log integrity \xB7 ${c.logs} log(s): hash chain intact on ${u.intact} from seq 1 and ${u.intactFromMidLog} from mid-log, broken on ${u.broken}, ${u.preChain} pre-chain (written before the chain); ${c.headMissing} missing their head, ${c.withGaps} with seq gaps, ${c.withRepeats} with repeated seq`),n.push(" (the chain is walked over this node's copy \u2014 advisory; the plane's verified head is the anchor)"),n.push(""),!e.findings.length)n.push("Findings: none.");else{n.push(`Findings \xB7 ${e.findings.length}`);for(let l of e.findings.slice(0,o)){let i=l.to-l.from>M?`${ce(l.from)} \u2192 ${ce(l.to).slice(11)}`:ce(l.from),d=l.actions?`${l.count} prompt(s), ${l.actions} action(s)`:`${l.count}`;n.push(` [${l.severity}] ${l.rule} \xB7 ${l.track||l.trackId}${l.boxId?` \xB7 ${l.boxId}`:""} \xB7 ${i} \xB7 ${d}`),n.push(` ${l.note}`);for(let m of l.samples)n.push(` - ${m}`)}e.findings.length>o&&n.push(` \u2026 ${e.findings.length-o} more (--json for all)`)}return n.push(""),n.push(e.ok?`No action without an origin. ${t||"The log is agent-writable, so this is evidence, not proof."}`:`Actions with NO origin were found \u2014 read the [high] findings above.${t?` ${t}`:""}`),n.join(`
3
- `)}import H from"node:fs";import Le from"node:fs/promises";import Z from"node:os";import E from"node:path";import{execFile as Be}from"node:child_process";import{promisify as Gt}from"node:util";var ge=Gt(Be),Ce="BOSTRAT_BOX_USER",Vt="bostrat-box",He=Object.freeze(["root","sudo","wheel","admin","docker","lxd","libvirt","disk"]);var Xt=/^[a-z_][a-z0-9_-]{0,31}$/,zt=new Set(["","off","0","false","no","none"]),qe=e=>e.BOSTRAT_STATE_DIR||E.join(e.HOME||Z.homedir(),".bostrat");function We(e){try{return H.readFileSync(e,"utf8").split(`
4
- `).filter(o=>o&&!o.startsWith("#")).map(o=>o.split(":"))}catch{return[]}}function Ke(e,o=process.env){let n=We(o.BOSTRAT_PASSWD_FILE||"/etc/passwd").find(r=>r[0]===String(e)||r[2]===String(e));return n?{name:n[0],uid:Number(n[2]),gid:Number(n[3]),home:n[5]||null,shell:n[6]||null}:null}function Ge(e,o=process.env){let t=We(o.BOSTRAT_GROUP_FILE||"/etc/group"),n=new Set;for(let r of t)Number(r[2])===e.gid&&n.add(r[0]),(r[3]||"").split(",").includes(e.name)&&n.add(r[0]);return[...n].sort()}var J=()=>typeof process.getuid=="function"?process.getuid():0,fe=null;function Q(e=process.env){let o=String(e[Ce]||"").trim();if(zt.has(o.toLowerCase()))return null;let t=`${o}|${e.BOSTRAT_PASSWD_FILE||""}|${e.BOSTRAT_GROUP_FILE||""}|${e.BOSTRAT_BOX_HOME_VIEW||""}`;if(fe?.key===t)return fe.value;let n;if(!Xt.test(o))n={name:o,error:`${Ce}="${o}" is not a valid user name`};else{let r=Ke(o,e),s=J();if(!r)n={name:o,error:`user "${o}" does not exist \u2014 run scripts/pi/box-user-setup.sh (or the image's useradd)`};else if(r.uid===0)n={name:o,error:`user "${o}" is root`};else if(r.uid===s)n={name:o,error:`user "${o}" is the node's own uid`};else if(!r.home||r.home==="/"||r.home==="/nonexistent")n={name:o,error:`user "${o}" has no home directory`};else{let c=Ge(r,e),u=c.filter(l=>He.includes(l));n=u.length?{name:o,error:`user "${o}" is in ${u.join(", ")} \u2014 a box user must hold no route to root`}:{...r,groups:c,nodeUid:s,rootNode:s===0}}}return fe={key:t,value:n},n}function Yt(e=process.env){let o=Q(e);return o&&!o.error?o.home:Z.homedir()}function Fe(e=process.env){let o=Q(e);return!o||o.error||o.rootNode?Yt(e):e.BOSTRAT_BOX_HOME_VIEW||E.join(qe(e),"box-home")}function Jt(e,o=process.env){let t=Q(o);return!t||t.error?e:t.rootNode?["setpriv",`--reuid=${t.uid}`,`--regid=${t.gid}`,"--init-groups","--","env",`HOME=${t.home}`,`USER=${t.name}`,`LOGNAME=${t.name}`,...e]:["sudo","-n","-H","-u",t.name,"--",...e]}async function he(e,{env:o=process.env,input:t=null,timeout:n=15e3}={}){let[r,...s]=Jt(e,o);return t==null?ge(r,s,{timeout:n}):new Promise((c,u)=>{Be(r,s,{timeout:n},(i,d,m)=>i?u(i):c({stdout:d,stderr:m})).stdin.end(t)})}var me;function Zt(e){return e.BOSTRAT_SETFACL_BIN?e.BOSTRAT_SETFACL_BIN:(me===void 0&&(me=["/usr/bin/setfacl","/bin/setfacl"].find(o=>H.existsSync(o))||null),me)}function Qt(e=process.env){let o=Z.homedir(),t=qe(e);return[E.join(o,".ssh"),E.join(o,".claude.json"),E.join(o,".claude",".credentials.json"),E.join(o,".codex","auth.json"),E.join(o,".config","gh","hosts.yml"),E.join(o,".cursor","cli-config.json"),E.join(t,"node.env"),E.join(t,"api-token"),E.join(t,"plane-link"),E.join(t,"secure-inputs")]}async function Ve({env:e=process.env,probe:o=!0}={}){let t=Q(e),n=await oo(e);if(!t){let s=Ke(J(),e)||{name:Z.userInfo().username,uid:J(),gid:-1},c=s.uid===0?["root"]:Ge(s,e).filter(i=>He.includes(i)),u=s.uid!==0&&o?await to():!1,l=[...c,...u&&!c.includes("sudo")?["sudo (sudoers)"]:[]];return{level:l.length?"root-capable":"node-uid",user:s.name,routes:l,problems:[],auditd:n}}if(t.error)return{level:"misconfigured",user:t.name,error:t.error,problems:[t.error],auditd:n};let r=[];if(o){try{let{stdout:l}=await he(["id","-u"],{env:e,timeout:5e3});Number(l.trim())!==t.uid&&r.push(`switching to ${t.name} landed as uid ${l.trim()}`)}catch(l){r.push(`the node cannot switch to ${t.name} (${t.rootNode?"setpriv":"sudo -n -u"} failed: ${eo(l)})`)}if(!r.length){await he(["sudo","-n","true"],{env:e,timeout:5e3}).then(()=>!0,()=>!1)&&r.push(`${t.name} can sudo`);let l=[];for(let i of Qt(e))H.existsSync(i)&&await he(["test","-r",i],{env:e,timeout:5e3}).then(()=>!0,()=>!1)&&l.push(i);l.length&&r.push(`${t.name} can read ${l.join(", ")}`)}Zt(e)||r.push("setfacl is missing (apt install acl)");let s=Fe(e);s!==t.home&&!H.existsSync(E.join(s,".claude"))&&r.push(`the read-only mirror of ${t.home} is not mounted at ${s} \u2014 the node cannot read box transcripts`);let c=E.join(t.home,".claude","settings.json"),u=await Le.stat(c).catch(()=>null);u&&u.uid===t.uid&&r.push(`${c} is owned by ${t.name} \u2014 the box can rewrite its own hooks`)}return{level:"uid",user:t.name,uid:t.uid,home:t.home,view:Fe(e),problems:r,auditd:n}}var eo=e=>String(e?.stderr||e?.message||e).trim().split(`
5
- `)[0].slice(0,160);async function to(){try{return await ge("sudo",["-n","true"],{timeout:3e3}),!0}catch{return!1}}async function oo(e=process.env,{ask:o=!0}={}){let t=e.BOSTRAT_AUDIT_LOG||"/var/log/audit/audit.log",n=!1;try{await Le.access(t,H.constants.R_OK),n=!0}catch{}let r=e.BOSTRAT_AUDIT_RULES_FILE||"/etc/audit/rules.d/bostrat-box.rules",s=H.existsSync(r),c=null;if(o&&s){let u=J()===0?["auditctl",["-l"]]:["sudo",["-n","auditctl","-l"]];try{let{stdout:l}=await ge(u[0],u[1],{timeout:5e3});c=l.includes(`key=${Vt}`)}catch{c=null}}else s||(c=!1);return{log:t,readable:n,configured:s,rule:c,rulesFile:r}}function Xe(e){return e.level==="uid"&&!e.problems.length?`Boxes on this node run as ${e.user}, which holds no route to root and cannot write the event log or its hook settings${e.auditd?.rule===!0&&e.auditd?.readable?"; its every exec is logged by auditd and shipped to the plane":""}.`:e.level==="uid"?`Boxes on this node run as ${e.user}, but containment has gaps (${e.problems.join("; ")}) \u2014 treat this record as evidence, not proof.`:e.level==="root-capable"?`Boxes on this node are root-capable (${e.user}: ${e.routes.join(", ")}), so a root-capable agent can defeat node-side evidence \u2014 this is evidence, not proof.`:e.level==="misconfigured"?`Box containment is configured but unusable (${e.error}); no box can start until it is fixed.`:`Boxes on this node share the node's uid (${e.user}), so an agent can rewrite its own log \u2014 this is evidence, not proof.`}var no="BP-AU-R4",rt=160,ze={high:0,medium:1,low:2},Ye=200,Je=5,Ze=8,Qe=5,et=10*6e4,ro=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"]),so=5e3,we=new Set(["tool.called","tool.failed"]),ye=new Set(["Write","Edit","NotebookEdit"]),io=e=>String(e??"").replace(/\s+/g," ").trim(),P=(e,o=120)=>io(e).slice(0,o);function ao(e,o=rt){let t=String(e??""),n=t.split(/\s*(?:;|&&|\|\||\||\n)\s*/).map(r=>r.trim()).filter(Boolean);return Number.isFinite(o)&&t.length>=o&&n.length&&n.pop(),n}function ee(e){return String(e??"").replace(/\d?>>?\s*\S+|<\s*\S+|2>&1/g," ").trim().split(/\s+/).filter(Boolean)}function st(e){let o=0;for(;o<e.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[o]);)o++;return{cmd:e[o]??null,rest:e.slice(o+1),at:o}}function tt(e){let o=ee(e),t=o.findIndex(i=>i==="git"||i.endsWith("/git"));if(t<0)return null;for(t++;t<o.length&&o[t].startsWith("-");)(o[t]==="-C"||o[t]==="-c")&&t++,t++;if(o[t]!=="push")return null;let n=[],r=[];for(let i=t+1;i<o.length;i++){let d=o[i];d.startsWith("-")?(n.push(d),(d==="-o"||d==="--push-option"||d==="--repo"||d==="--receive-pack"||d==="--exec")&&i++):r.push(d)}let s=n.some(i=>i==="--force"||/^-[a-zA-Z]+$/.test(i)&&i.includes("f"))||r.some(i=>i.startsWith("+")),c=n.some(i=>i.startsWith("--force-with-lease")||i.startsWith("--force-if-includes")),u=r[0]??null,l=r.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:s,lease:c,remote:u,dsts:l}}var ke=String.raw`(?:~|\$HOME|\$\{HOME\}|/home/[^\s/"']+|/root|/Users/[^\s/"']+)`,co=new RegExp(`${ke}/\\.ssh(?:/|\\b)`),lo=new RegExp(`${ke}/(?:\\.claude\\.json\\b|\\.claude/\\.credentials\\.json|\\.codex/auth\\.json|\\.cursor(?:/|\\b))`),uo=/(?:^|[\s/"'=(])(\.env(?:\.[A-Za-z0-9_.-]+)?)(?=$|[\s"'|;&)])/g,po=/^\.env\.(?:example|sample|template|dist)$/,it=/(\.claude\/settings(?:\.local)?\.json|\.claude\/hooks\/[^\s"']*|\.bostrat\/events(?:\/[^\s"']*)?)/,at=new RegExp(`((?:/etc|/usr/lib|/lib|/run)/systemd/[^\\s"']*|${ke}/\\.config/systemd/[^\\s"']*|/etc/cron(?:tab|\\.d|\\.hourly|\\.daily|\\.weekly|\\.monthly)(?:/[^\\s"']*)?|/var/spool/cron(?:/[^\\s"']*)?)`),fo=/^(?: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)$/,ho=/^\/tmp\/|\/\.bostrat\/tmp\//,mo=/^(?:refs\/heads\/)?(?:main|master|develop|development|trunk|production|prod|staging|release(?:\/|$)|v\d)/,go=/(?:^|\/)track\/|^HEAD$|^refs\/bostrat\//,yo=/https?:\/\/([a-z0-9.-]+\.[a-z]{2,}|localhost|\d+\.\d+\.\d+\.\d+)(?::\d+)?/gi,ot=e=>co.test(e)||lo.test(e),nt=e=>[...String(e??"").matchAll(uo)].some(o=>!po.test(o[1])),bo=e=>it.test(e),wo=e=>at.test(e),ko=e=>(e.startsWith("/")||e.startsWith("~"))&&!ho.test(e);function ct(e){let{cmd:o,at:t}=st(e);if(o==="sudo"){for(t++;t<e.length&&e[t].startsWith("-");)t++;o=e[t]??null}return{cmd:o,at:t}}function lt(e,o){let t=String(e??"").match(o);if(!t)return null;let n=t[1],r=n.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&");if(new RegExp(`>{1,2}\\s*["']?[^\\s"']*${r}`).test(e))return"redirect";let s=ee(e),{cmd:c}=ct(s);return!c||!s.some(u=>u.includes(n))?null:/^(?:rm|mv|truncate|chmod|chown|tee|install|shred|unlink|ln|mkdir|touch)$/.test(c)?c:c==="sed"&&s.some(u=>/^-[a-zA-Z]*i/.test(u))?"sed -i":c==="cp"&&s[s.length-1].includes(n)?"cp":/^(?:python3?|perl|node|ruby)$/.test(c)&&/open\([^)]*['"][wa]|writeFile|write_text|appendFile|fs\.write/.test(e)?`${c} write`:null}var $o=e=>lt(e,it);function So(e){let o=ee(e),{cmd:t,at:n}=ct(o);if(!t)return null;let r=o.slice(n+1);if(t==="crontab"||t.endsWith("/crontab")){let c=!1,u=!1;for(let l=0;l<r.length;l++){if(r[l]==="-u"){l++;continue}r[l]==="-l"||/^-(?:h|V|T|-help|-version)$/.test(r[l])?c=!0:u=!0}return u||!c?"crontab":null}if(t==="systemctl"||t.endsWith("/systemctl")){let c=r.find(u=>!u.startsWith("-"));return c&&fo.test(c)?`systemctl ${c}`:null}if((t==="loginctl"||t.endsWith("/loginctl"))&&r.includes("enable-linger"))return"loginctl enable-linger";if(t==="at"&&r.length&&/^(?:now|midnight|noon|teatime|today|tomorrow|next|\d|-[fqmvt])/.test(r[0]))return"at";let s=lt(e,at);return s?`${s} unit/cron path`:null}function xo(e){let o=new Set;for(let t of String(e??"").matchAll(yo))o.add(t[1].toLowerCase());return[...o]}function Eo({knownHosts:e=[]}={}){return{known:new Set([...ro,...[...e].map(o=>String(o).toLowerCase()).filter(Boolean)]),hosts:new Set,tracks:new Map}}function _o(e,o){let t=e.tracks.get(o??"");return t||e.tracks.set(o??"",t={costs:[],peer:new Map}),t}var _=(e,o,t,n)=>Object.freeze({severity:e,requirement:no,note:o,measured:t,detect:n}),z=(e,o)=>{let t=0,n=null;for(let r of e.calls)if(r.head)for(let s of ao(r.head,e.headCap)){let c=o(s,r);c&&(t++,n??=P(c))}return t?{count:t,sample:n}:null},be=(e,o)=>{let t=0,n=null;for(let r of e.calls){let s=o(r);s&&(t++,n??=P(s))}return t?{count:t,sample:n}:null},q=Object.freeze({"force-push":_("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",(e,o)=>z(o,t=>{let n=tt(t);return n&&n.force&&!n.lease?t:null})),"protected-config-write":_("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",(e,o)=>{let t=0,n=null;for(let s of o.calls)ye.has(s.tool)&&s.path&&bo(s.path)&&(t++,n??=P(`${s.tool} ${s.path}`));let r=z(o,s=>{let c=$o(s);return c?`${c}: ${s}`:null});return r&&(t+=r.count,n??=r.sample),t?{count:t,sample:n}:null}),"persistence-install":_("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",(e,o)=>{let t=0,n=null;for(let s of o.calls)ye.has(s.tool)&&s.path&&wo(s.path)&&(t++,n??=P(`${s.tool} ${s.path}`));let r=z(o,s=>{let c=So(s);return c?`${c}: ${s}`:null});return r&&(t+=r.count,n??=r.sample),t?{count:t,sample:n}:null}),"push-outside-track":_("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",(e,o)=>z(o,t=>{let n=tt(t);return n&&(n.remote&&!/^(?:origin|upstream)$/.test(n.remote)&&!n.remote.startsWith("$")&&!n.remote.startsWith("-")||n.dsts.some(r=>mo.test(r)||!go.test(r)))?t:null})),"credential-read":_("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",(e,o)=>be(o,t=>t.head&&ot(t.head)?t.head:t.path&&ot(t.path)?`${t.tool} ${t.path}`:null)),"dotenv-read":_("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)",(e,o)=>be(o,t=>t.head&&nt(t.head)?t.head:t.path&&nt(t.path)?`${t.tool} ${t.path}`:null)),"privileged-command":_("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)",(e,o)=>z(o,t=>{let{cmd:n}=st(ee(t));return n==="sudo"||n==="docker"?t:null})),"write-outside-workspace":_("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)",(e,o)=>be(o,t=>ye.has(t.tool)&&t.path&&ko(t.path)?`${t.tool} ${t.path}`:null)),"egress-new-host":_("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)",(e,o)=>{let t=0,n=null;for(let r of o.calls)if(r.head)for(let s of xo(r.head))o.state.known.has(s)||o.state.hosts.has(s)||(o.state.hosts.add(s),o.state.hosts.size>so&&o.state.hosts.delete(o.state.hosts.values().next().value),t++,n??=P(`${s} \xB7 ${r.head}`));return t?{count:t,sample:n}:null}),"spend-spike":_("low",`a cost.recorded turn over ${Ze}\xD7 the Track's running median (its last ${Ye} cost events, at least ${Je} of them) and over $${Qe} \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)",(e,o)=>{if(e.type!=="cost.recorded")return null;let t=o.track.costs,n=Number(e.payload?.usd);if(!Number.isFinite(n)||n<0)return null;let r=null;if(t.length>=Je&&n>=Qe){let s=[...t].sort((u,l)=>u-l),c=s[Math.floor(s.length/2)];n>Ze*c&&(r={count:1,sample:`$${n.toFixed(2)} vs median $${c.toFixed(2)} over ${t.length} turns${e.payload?.model?` \xB7 ${e.payload.model}`:""}`})}return t.push(n),t.length>Ye&&t.shift(),r}),"peer-injected-call":_("medium",`a tool call within ${et/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",(e,o)=>{if(!o.calls.length)return null;let t=o.track.peer.get(o.boxKey);if(t==null||o.ts-t>et||o.ts<t)return null;let n=o.calls[0];return{count:o.count,sample:P(`${Math.round((o.ts-t)/1e3)}s after a peer message \xB7 ${n.tool}${n.head?`: ${n.head}`:n.path?` ${n.path}`:""}`)}}),"foreign-session-call":_("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",(e,o)=>{if(!o.calls.length||!e.payload?.foreignSession)return null;let t=o.calls[0];return{count:o.count,sample:P(`session ${String(e.payload.sessionId||"?").slice(0,8)} \xB7 ${t.tool}${t.head?`: ${t.head}`:t.path?` ${t.path}`:""}`)}}),"orphan-process":_("medium","a process the box left running: detached from the pane's tree (its cgroup or pty still lists it), alive at a turn's close and still alive minutes later with no turn open and no background job recorded \u2014 the node's own census (orphan-watch.js, BP-AU-D6), each process once","2026-10-27 fleet replay \xB7 0 audit.procs events in 304,814 (1,121 logs; the type is new, so the replay cannot bound this rule's rate) \xB7 live Pi census the same day: 10 boxes, 2 detached processes, both found by the cgroup census and neither by the pty one (a claude tool call runs on pipes) \u2014 one planted `nohup sleep &`, one real `flyctl agent run` that a lead's flyctl call had left behind 10 h earlier \u2192 medium (rail), never a page, until a window of live samples has been measured",e=>{if(e.type!=="audit.procs"||e.source!=="proc")return null;let o=e.payload||{},t=Array.isArray(o.orphans)?o.orphans:[],n=t.length+(Number(o.dropped)||0);if(!n)return null;let r=t[0]||{},s=Number.isFinite(r.sinceMs)?` \xB7 alive ${Math.max(1,Math.round(r.sinceMs/6e4))} min`:"";return{count:n,sample:P(`${r.comm||"process"}${r.cmd?`: ${r.cmd}`:""}${r.via?` [${r.via}]`:""}${s}${n>1?` (+${n-1} more)`:""}`)}})}),W=Object.freeze(Object.keys(q)),Io=new Set([...we,"cost.recorded","peer.message","turn.user","audit.procs"]);function To(e,o,{rules:t=null,headCap:n=rt}={}){if(!o||!Io.has(o.type)||o.source==="plane")return[];let r=_o(e,o.trackId),s=o.payload||{},c=o.boxId??"",u=Number(o.ts)||0;if(o.type==="turn.user")return(o.actor==="user"||o.actor==="orchestrator")&&r.peer.delete(c),[];if(o.type==="peer.message")return r.peer.set(c,u),[];let l=we.has(o.type)&&o.source==="hook",d={calls:l?v(s):[],count:l?F(s):0,track:r,state:e,ts:u,boxKey:c,headCap:n},m=[];for(let k of t||W){let b=q[k];if(!b)continue;let x=null;try{x=b.detect(o,d)}catch{x=null}x&&x.count>0&&m.push({rule:k,count:x.count,sample:x.sample??null})}return m}function ut(e,{days:o=14,now:t=Date.now(),rules:n=null}={}){let r=o?t-o*864e5:0,s=Eo(),c=n||W,u={days:o||null,logs:0,events:0,calls:0,callsInWindow:0,rules:Object.fromEntries(c.map(i=>[i,{severity:q[i].severity,note:q[i].note,measured:q[i].measured,hits:0,hitsInWindow:0,events:0,tracks:0,tracksInWindow:0,perTenK:0,samples:[]}]))},l=Object.fromEntries(c.map(i=>[i,{all:new Set,win:new Set}]));for(let i of e||[]){let d=Array.isArray(i?.events)?[...i.events].sort((m,k)=>(Number(m.ts)||0)-(Number(k.ts)||0)):[];if(d.length){u.logs++;for(let m of d){u.events++;let k=(Number(m.ts)||0)>=r;if(we.has(m.type)&&m.source==="hook"){let b=F(m.payload||{});u.calls+=b,k&&(u.callsInWindow+=b)}for(let b of To(s,m,{rules:c})){let x=u.rules[b.rule];if(x.hits+=b.count,x.events++,l[b.rule].all.add(m.trackId??i.trackId),k&&(x.hitsInWindow+=b.count,l[b.rule].win.add(m.trackId??i.trackId)),b.sample){let U=x.samples.find(w=>w.text===b.sample);U?U.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 c){let d=u.rules[i];d.tracks=l[i].all.size,d.tracksInWindow=l[i].win.size,d.perTenK=u.calls?Number((d.hits/u.calls*1e4).toFixed(2)):0,d.samples.sort((m,k)=>k.n-m.n||k.ts-m.ts),d.samples=d.samples.slice(0,50)}return u.ok=!c.some(i=>q[i].severity==="high"&&u.rules[i].hitsInWindow>0),u}var Oo=e=>new Date(e).toISOString().slice(0,10);function dt(e,{samples:o=5}={}){let t=[];t.push(`R4 DETECTOR REPLAY \xB7 ${e.days?`window last ${e.days}d`:"all history"} \xB7 ${e.logs} logs \xB7 ${e.events.toLocaleString()} events \xB7 ${e.calls.toLocaleString()} hook calls (${e.callsInWindow.toLocaleString()} in window)`),t.push("A rule's severity is what its measured rate supports; `high` pages (D7). Hits are what the plane fold would have flagged.");let n=Object.keys(e.rules).sort((r,s)=>ze[e.rules[r].severity]-ze[e.rules[s].severity]||r.localeCompare(s));for(let r of n){let s=e.rules[r];t.push(""),t.push(`${r} [${s.severity}] \xB7 ${s.hits} hit(s) all-time (${s.events} events, ${s.tracks} Tracks, ${s.perTenK}/10k calls) \xB7 ${s.hitsInWindow} in window (${s.tracksInWindow} Tracks)`),t.push(` ${s.note}`),s.measured&&t.push(` measured: ${s.measured}`);for(let c of s.samples.slice(0,o))t.push(` ${c.n}\xD7 ${Oo(c.ts)} ${c.name?`${c.name} `:""}(${c.trackId}) ${c.text}`)}return t.push(""),t.push(e.ok?"ok: no high-severity detector hit in the window":"ATTENTION: a high-severity detector hit inside the window (exit 2)"),t.join(`
6
- `)}import Ao from"node:path";import vo from"node:os";import{EventEmitter as No}from"node:events";var Qo=16*1024;var Ro=new No;Ro.setMaxListeners(0);var ln=process.env.BOSTRAT_STATE_DIR||Ao.join(process.env.HOME||vo.tmpdir(),".bostrat");var jo=/(?<!\\)((?:\\\\)*)\\u0000/g,pt=e=>e.includes("\\u0000"),ft=e=>e.replace(jo,"$1\\ufffd");var oe=process.env.BOSTRAT_STATE_DIR||L.join(process.env.HOME||Do.tmpdir(),".bostrat"),T=process.argv.slice(2),ne=e=>{let o=T.indexOf(e);return o>=0?T[o+1]:null};(T.includes("--help")||T.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: ${W.join(", ")}`),process.exit(0));var xe=[];try{xe=JSON.parse(await te.readFile(L.join(oe,"tracks.json"),"utf8")).tracks||[]}catch{}var Mo=new Map(xe.map(e=>[e.id,e.name])),Ee=new Set([L.join(oe,"events")]);for(let e of xe)e.cwd&&Ee.add(L.join(e.cwd,".bostrat","events"));try{for(let e of await te.readdir(L.join(oe,"workspaces")))Ee.add(L.join(oe,"workspaces",e,".bostrat","events"))}catch{}var $e=ne("--track"),_e=[];for(let e of Ee){let o=[];try{o=(await te.readdir(e)).filter(t=>t.endsWith(".ndjson"))}catch{continue}for(let t of o){let n=t.slice(0,-7),r=Mo.get(n)||null;if($e&&n!==$e&&!(r||"").toLowerCase().includes($e.toLowerCase()))continue;let s=[];for(let c of(await te.readFile(L.join(e,t),"utf8")).split(`
7
- `))if(c.trim())try{s.push(JSON.parse(pt(c)?ft(c):c))}catch{}s.length&&_e.push({trackId:n,name:r,events:s})}}var ht=T.includes("--all")?0:Number(ne("--days"))||14;if(T.includes("--detectors")){let e=T.flatMap((n,r)=>n==="--rule"&&T[r+1]?[T[r+1]]:[]),o=e.filter(n=>!W.includes(n));o.length&&(console.error(`unknown rule(s): ${o.join(", ")} \u2014 known: ${W.join(", ")}`),process.exit(1));let t=ut(_e,{days:ht,rules:e.length?e:null});console.log(T.includes("--json")?JSON.stringify(t,null,2):dt(t,{samples:Number(ne("--limit"))||5})),process.exit(t.ok?0:2)}var Y=Pe(_e,{days:ht}),Se=await Ve().catch(()=>null);Se&&(Y.containment={...Se,sentence:Xe(Se)});console.log(T.includes("--json")?JSON.stringify(Y,null,2):Ue(Y,{limit:Number(ne("--limit"))||20,containment:Y.containment?.sentence}));process.exit(Y.ok?0:2);
2
+ import ye from"node:fs/promises";import Ho from"node:os";import K from"node:path";var Vt=(e,t)=>{if(e==null||e==="")return t;let n=Number(e);return Number.isFinite(n)&&n>=0?n:t},Wo=Vt(process.env.BOSTRAT_HOOK_FOLD_MS,250);var zt=1e3;function q(e){let t=Number(e?.count);return Number.isInteger(t)&&t>1&&e?.tools&&typeof e.tools=="object"?Math.min(t,zt):1}function P(e){let t=e||{},n=q(t);if(n===1)return[t];let o=(Array.isArray(t.calls)?t.calls:[]).filter(r=>r&&typeof r=="object").slice(0,n),s={};for(let r of o)r.tool&&(s[r.tool]=(s[r.tool]||0)+1);for(let[r,a]of Object.entries(t.tools))for(let u=s[r]||0;u<Number(a)&&o.length<n;u++)o.push({tool:r});for(;o.length<n;)o.push({tool:null});return o}import{createHash as Yt}from"node:crypto";var Jt=new Set(["userId"]);function ke(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(n=>ke(n===void 0?null:n)).join(",")}]`:`{${Object.keys(e).filter(n=>e[n]!==void 0).sort().map(n=>`${JSON.stringify(n)}:${ke(e[n])}`).join(",")}}`}function oe(e){let t={};for(let n of Object.keys(e))Jt.has(n)||(t[n]=e[n]);return Yt("sha256").update(ke(t)).digest("hex")}var Ee=e=>Number.isFinite(e?.seq);function Ye(e){let t={members:0,chained:0,preChain:0,intactFrom:null,intactTo:null,genesis:!1,breaks:[]},n=null,o=!1,s=(r,a)=>{n={seq:r.seq,hash:a},t.intactFrom=r.seq,t.genesis=r.seq===1&&r.prev===null};for(let r of e||[]){if(!Ee(r))continue;if(t.members++,r.prev===void 0){n&&!o?(t.breaks.push({kind:"unchained",seq:r.seq,eventId:r.id??null}),o=!0):n||t.preChain++;continue}t.chained++;let a=oe(r);if(!n||o){o=!1,s(r,a);continue}if(r.seq===n.seq+1){if(r.prev===n.hash){n={seq:r.seq,hash:a};continue}t.breaks.push({kind:"prev-mismatch",seq:r.seq,eventId:r.id??null,expected:n.hash,got:r.prev})}else r.seq>n.seq+1?t.breaks.push({kind:"seq-gap",seq:r.seq,eventId:r.id??null,from:n.seq+1,to:r.seq-1}):t.breaks.push({kind:"seq-repeat",seq:r.seq,eventId:r.id??null,headSeq:n.seq});s(r,a)}return t.intactTo=n?n.seq:null,n||(t.intactFrom=null),t}var B=6e4,Zt=120*B,Je=2e3,Ze=5e3,Qt=2*B,en=5e3,tn=2*B,Z=5e3,nn={Workflow:360*B,Agent:60*B},on=5*B,sn=10*B,xe=80,M=3,rn=["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"],Ae={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"},tt={claude:{source:"hook",note:"hook-sourced: the CLI's hooks record the turn start (prompt_id), each call's intent and outcome (tool_use_id), failed calls and the Stop; the transcript is the duplicate"},codex:{source:"transcript",note:"transcript-sourced (a file the agent writes): the rollout names each turn (turn_id, turn_trigger, parent_turn_id) and each call (call_id), so a call cites the send that opened its turn; no intent before a call, no failed-call record, no turn end on the log, and a prompt typed at the pane is not on the log"},cursor:{source:"transcript",note:"transcript-sourced (a store the agent writes): message order is the turn structure, so a call cites the user message that opened its turn (its content hash); no turn ids, no per-message time (ts is synthesized), no intent, no failed-call record, no turn end, and a prompt typed at the pane is not on the log"}},C=e=>String(e??"").replace(/\s+/g," ").trim(),y=e=>e?.ts??0,Ie=(e,t)=>!!e&&!!t&&(e.startsWith(t.slice(0,xe))||t.startsWith(e.slice(0,xe))),an=6,cn=(e,t)=>Ie(e,t)||e.length>=an&&t.includes(e.slice(0,xe)),ln=/^<pasted_content\b[^>]*>\s*/i,Te=e=>C(e.payload?.promptHead??e.payload?.text).replace(ln,""),un=/^<cross-session-message\b/i,dn=/^<task-notification>/i,pn=/<tool-use-id>\s*([^<\s]+)\s*<\/tool-use-id>/i;function $e(e){let t=e.payload||{},n=q(t),o=P(t)[0],s=o.head||o.path||(t.command?C(t.command):""),r=e.type==="tool.failed"?" [failed]":e.type==="tool.started"?" [never completed]":"";return`${o.tool||"tool"}${s?`: ${s.slice(0,100)}`:""}${r}${n>1?` (+${n-1} more)`:""}`}var fn=/\.answered$/,hn=new Set(["loop.created","followup.created"]),mn=16,nt=new Set(["tool.started","tool.called","tool.failed"]);function gn(){return{byId:new Map,byDelivery:new Map,byPrompt:new Map,byToolUse:new Map,jobs:new Map}}function yn(e,t){if(!t||typeof t.type!="string")return;t.id&&e.byId.set(t.id,t);let n=t.payload||{};if(t.type==="turn.user")t.source==="orchestrator"&&n.deliveryId&&e.byDelivery.set(n.deliveryId,t),t.source==="hook"&&n.promptId&&!e.byPrompt.has(`${t.boxId}\0${n.promptId}`)&&e.byPrompt.set(`${t.boxId}\0${n.promptId}`,t);else if(t.type==="job.started"&&n.id)e.jobs.set(n.id,t);else if(nt.has(t.type)&&t.source==="hook")for(let o of P(n))o.toolUseId&&!e.byToolUse.has(o.toolUseId)&&e.byToolUse.set(o.toolUseId,t)}function bn(e){let t=gn();for(let n of e)yn(t,n);return t}function Qe(e,t){let n=e;for(let o=0;n&&o<mn;o++){let s=n.payload||{},r=n.type;if(n.causationId&&t.byId.has(n.causationId)&&n.causationId!==n.id){n=t.byId.get(n.causationId);continue}if(nt.has(r)){let a=s.promptId?t.byPrompt.get(`${n.boxId}\0${s.promptId}`):null;if(!a)return null;n=a;continue}if(r==="turn.user"){if(n.source==="hook"){if(s.kind==="task-notification"&&s.jobId){let u=t.jobs.get(s.jobId);if(!u)return null;n=u;continue}let a=s.deliveryId?t.byDelivery.get(s.deliveryId):null;if(!a)return null;n=a;continue}return n.source==="orchestrator"?s.loopId||s.producer==="loop"?{origin:"loop",root:n}:{origin:n.actor==="orchestrator"?"orchestrator":"operator",root:n}:n.source==="transcript"?{origin:"operator-terminal",root:n}:null}if(r==="job.started"){let a=s.id?t.byToolUse.get(s.id):null;if(!a)return null;n=a;continue}return fn.test(r)||hn.has(r)?{origin:"card-answer",root:n}:r==="peer.message"?{origin:"peer",root:n}:null}return null}function wn(e){let t={events:e.length,firstSeq:null,lastSeq:null,headMissing:!1,gaps:0,repeats:0},n=null;for(let s of e)Number.isFinite(s?.seq)&&(n===null?t.firstSeq=s.seq:s.seq>n+1?t.gaps++:s.seq<=n&&t.repeats++,n=s.seq);t.lastSeq=n,t.headMissing=t.firstSeq!==null&&t.firstSeq>1;let o=Ye(e);return t.chain={state:o.chained===0?"pre-chain":o.breaks.length?"broken":o.genesis?"intact":"intact-from-mid-log",chained:o.chained,preChain:o.preChain,intactFrom:o.intactFrom,intactTo:o.intactTo,breaks:o.breaks},t}var Sn=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 kn(e){let t=new Map,n=new Map,o=new Map,s=new Map,r=(i,d,m)=>{i.has(d)||i.set(d,[]),i.get(d).push(m)};for(let i of e)if((i.type==="box.state.changed"||i.type.startsWith("handoff."))&&r(s,i.payload?.box||i.boxId||null,y(i)),i.type==="session.ready"&&([...s.get(i.boxId)||[],...s.get(null)||[]].some(m=>m<=y(i)&&y(i)-m<=tn)||r(o,i.boxId,y(i))),i.type==="turn.user")if(i.source==="orchestrator"){let d=(i.payload?.attachments||[]).map(m=>m?.id).filter(Boolean);r(t,i.boxId,{ts:y(i),head:C(i.payload?.text),files:d,actor:i.actor,usedAt:null})}else i.source==="transcript"&&r(n,i.boxId,{ts:y(i),head:C(i.payload?.text),note:i.payload?.note?.kind||null});let a=new Map,u=new Map,l=new Map;for(let i of e){if(i.type==="turn.user"&&i.source==="orchestrator"&&u.set(i.boxId,!0),i.source!=="hook")continue;if(i.type==="turn.agent"){let h=l.get(i.boxId)||0;h>0?l.set(i.boxId,h-1):u.set(i.boxId,!1);continue}if(i.type!=="turn.user")continue;let d=Te(i),m=(()=>{if(i.actor==="peer"||un.test(d))return{origin:"peer"};if(dn.test(d))return{origin:"task-continuation",jobId:d.match(pn)?.[1]||null};let h=(t.get(i.boxId)||[]).filter(b=>(b.usedAt===null||y(i)-b.usedAt<=Ze)&&b.ts>=y(i)-Zt&&b.ts<=y(i)+Je&&(cn(b.head,d)||!b.head&&b.files.length>0&&(b.files.some(x=>d.includes(`.bostrat/uploads/${x}`))||y(i)-b.ts<=Ze))),g=h[h.length-1];if(g)return g.usedAt=y(i),{origin:g.actor==="orchestrator"?"orchestrator":"operator"};if(rn.some(b=>d.startsWith(b)))return{origin:"orchestrator-unlogged"};if((n.get(i.boxId)||[]).find(b=>!b.note&&b.ts>=y(i)-Je&&b.ts<=y(i)+Qt&&Ie(b.head,d)))return{origin:"operator-terminal"};let j=(o.get(i.boxId)||[]).some(b=>b<=y(i)&&y(i)-b<=en);return{origin:u.get(i.boxId)||j?"nested-session":"unknown-prompt"}})();a.set(i,m),m.origin==="nested-session"?l.set(i.boxId,(l.get(i.boxId)||0)+1):u.set(i.boxId,!0)}return a}function En(e){let t=new Map,n=new Map;for(let o of e){let s=o.payload?.id;if(s)if(o.type==="job.started"){let r={from:(o.payload?.ts??y(o))-Z,to:1/0,loggedAt:y(o)};n.set(s,r),t.has(o.boxId)||t.set(o.boxId,[]),t.get(o.boxId).push(r)}else o.type==="job.stopped"&&n.has(s)&&(n.get(s).to=y(o)+Z)}return{byBox:t,byId:n}}function $n(e,{trackId:t=null,name:n=null,since:o=0}={}){let s=kn(e),r=En(e),a=new Set;for(let c of e)c.type==="tool.called"&&c.source==="hook"&&a.add(c.boxId);let u=c=>c.type==="tool.called"&&(c.source==="hook"||!(c.provider==="claude"&&a.has(c.boxId)))||c.type==="tool.failed"&&c.source==="hook",l=new Set,i=new Map;for(let c of e)if(c.source==="hook")if(c.type==="tool.called"||c.type==="tool.failed")for(let p of P(c.payload))p.toolUseId&&l.add(p.toolUseId);else c.type==="audit.flagged"&&c.payload?.denied===!0&&c.payload.toolUseId?l.add(c.payload.toolUseId):(c.type==="turn.agent"||c.type==="session.ready"||c.type==="turn.aborted"||c.type==="turn.interrupted")&&(i.has(c.boxId)||i.set(c.boxId,[]),i.get(c.boxId).push(y(c)));let d=e.length?y(e[e.length-1]):0,m=c=>{if(c.type!=="tool.started"||c.source!=="hook")return null;let p=P(c.payload).filter($=>$.toolUseId&&!l.has($.toolUseId));return p.length&&((i.get(c.boxId)||[]).some($=>$>y(c))||d-y(c)>sn)?p:null},h={},g={},S={keyed:0,turn:0,timing:0},j=bn(e),b=new Map,x=(c,p,f,$,_,w=1)=>{let U=`${c}\0${f.boxId}\0${$}`,N=b.get(U);return(!N||y(f)-N.to>on)&&(N={rule:c,severity:p,trackId:t,track:n,boxId:f.boxId,from:y(f),to:y(f),count:0,note:_,samples:[]},b.set(U,N),T.push(N)),N.to=y(f),N.count+=w,N},T=[],v=new Map,k=c=>(v.has(c)||v.set(c,{open:!1,origin:null,nested:0,soft:null,lastSendHead:null,launch:null}),v.get(c));for(let c of e){let p=k(c.boxId),f=y(c)>=o;if(c.type==="session.foreign"){if(c.payload?.phase==="prompted"&&f){let E=x("nested-session","medium",c,"","a session that is not the box's own was prompted through this box \u2014 typically an agent-launched `claude -p`");E.samples.length<M&&E.samples.push(C(c.payload?.promptHead).slice(0,100))}continue}if(c.type==="turn.user"&&c.source==="hook"){let E=s.get(c);if(E.origin==="nested-session"){if(p.nested++,f){let W=x("nested-session","medium",c,"","a prompt no recorded send accounts for arrived mid-turn or right after a SessionStart \u2014 typically an agent-launched `claude -p`");W.samples.length<M&&W.samples.push(Te(c).slice(0,100))}continue}if(p.open=!0,p.origin=E.origin,E.origin==="task-continuation"&&!r.byId.has(E.jobId)&&(p.origin="task-continuation-unlogged"),p.origin==="unknown-prompt"&&f){let W=x("unknown-prompt","medium",c,"","a turn opened by a prompt with no operator, machinery or job record behind it");W.samples.length<M&&W.samples.push(Te(c).slice(0,100))}}else if(c.type==="turn.agent"&&c.source==="hook")p.nested>0?p.nested--:p.open=!1;else if(c.type==="turn.aborted"||c.type==="turn.interrupted")p.open=!1;else if(c.type==="turn.user"&&c.source==="orchestrator")p.lastSendHead=C(c.payload?.text),p.soft=c.actor==="orchestrator"?"orchestrator":"operator",p.open=!0,p.origin=p.soft;else if(c.type==="turn.user"&&c.source==="transcript"){let E=C(c.payload?.text);!c.payload?.note&&!Ie(E,p.lastSendHead)&&(p.soft="operator-terminal")}else c.type==="peer.message"&&(p.soft="peer");let $=m(c);if(!$&&!u(c))continue;let _=$?$.length:c.source==="hook"?q(c.payload):1,w;if(c.payload?.foreignSession)w="nested-session";else if(c.source==="hook"){let E=(r.byBox.get(c.boxId)||[]).some(H=>y(c)>=H.from&&y(c)<=H.to);p.open?w=p.origin:E?w="background-job":p.nested>0?w="nested-session":p.launch&&y(c)<=p.launch?w="background-launch":w="unrooted";let W=(r.byBox.get(c.boxId)||[]).some(H=>H.loggedAt<=y(c)+Z);for(let H of P(c.payload)){let Se=H.tool,Xt=!!H.toolUseId&&r.byId.has(H.toolUseId);(Se==="Workflow"&&!Xt||Se==="Agent"&&!W)&&p.open&&Ae[p.origin]!=="flagged"&&(p.launch=Math.max(p.launch||0,y(c)+nn[Se]))}}else c.payload?.turnId?w=String(c.payload.turnTrigger||"user")==="user"?"operator-terminal":"unknown-prompt":w=p.soft||"unrooted";let U=c.payload?.foreignSession?null:Qe(c,j);if(U&&(w=U.origin),!f)continue;let N=!U&&c.source!=="hook"&&!!c.payload?.turnId;S[U?"keyed":N?"turn":"timing"]+=_,h[w]=(h[w]||0)+_;let G=c.provider||"unknown";if(g[G]||={actions:0,fidelity:c.source==="hook"?"hook":"transcript",identified:!1,turnKeyed:!1,rooted:{key:0,turn:0,timing:0}},g[G].actions+=_,g[G].rooted[U?"key":N?"turn":"timing"]+=_,c.source==="hook"&&(g[G].fidelity="hook"),c.source==="hook"&&P(c.payload).some(E=>E.toolUseId)&&(g[G].identified=!0),c.source!=="hook"&&c.payload?.turnId&&(g[G].turnKeyed=!0),w==="unknown-prompt"&&c.source!=="hook"){let E=x("unexplained-turn","medium",c,String(c.payload.turnId),`calls in a transcript turn the CLI says no prompt opened (turn_trigger: ${String(c.payload.turnTrigger)}) and that cites no recorded cause`,_);E.samples.length<M&&E.samples.push($e(c));continue}if($){let E=x("unfinished-calls","low",c,"","calls the CLI began (PreToolUse) and never reported complete or failed \u2014 killed, crashed or restarted mid-call; the tool may have run",_);E.samples.length<M&&E.samples.push($e(c))}if(w==="unrooted"){let E=x("unrooted-actions","high",c,"","tool calls with no open turn, no recorded job and no launch that accounts for them",_);E.samples.length<M&&E.samples.push($e(c))}else if(w==="peer")x("peer-driven-actions","low",c,"","tool calls in a turn another session's message opened",_);else if(w==="nested-session"||w==="unknown-prompt"){let E=b.get(`${w}\0${c.boxId}\0`);E&&(E.actions=(E.actions||0)+_)}}let D={total:0,keyed:0,timing:0,unrooted:0};{let c=new Map,p=new Map;for(let f of e)f.source==="hook"&&(f.type==="turn.user"?p.set(f.boxId,y(f)):(f.type==="turn.agent"||f.type==="turn.aborted"||f.type==="turn.interrupted")&&p.has(f.boxId)&&((c.get(f.boxId)||c.set(f.boxId,[]).get(f.boxId)).push([p.get(f.boxId),y(f)]),p.delete(f.boxId)));for(let[f,$]of p)(c.get(f)||c.set(f,[]).get(f)).push([$,1/0]);for(let f of e){if(f.type!=="code.committed"||f.source!=="hook"||y(f)<o)continue;D.total++;let $=Number(f.payload?.ts??f.ts)||y(f);if(Qe(f,j))D.keyed++;else if((c.get(f.boxId)||[]).some(([_,w])=>$>=_-Z&&$<=w+Z))D.timing++;else{D.unrooted++;let _=x("unrooted-commit","medium",f,"","a commit landed in the box's workspace with no turn open and no recorded cause");_.samples.length<M&&_.samples.push(`${String(f.payload?.sha||"").slice(0,7)} ${C(f.payload?.subject).slice(0,80)}`)}}}{let c=e.filter(p=>p.type==="audit.flagged"&&p.source!=="plane"&&p.payload?.denied===!0&&y(p)>=o);if(c.length){let p=[...new Set(c.map(f=>f.payload?.rule).filter(Boolean))];T.push({rule:"guard-denied",severity:"high",trackId:t,track:n,boxId:c[0].boxId??null,from:y(c[0]),to:y(c.at(-1)),count:c.length,samples:c.slice(0,M).map(f=>`${f.payload?.rule||"?"}: ${C(f.payload?.samples?.[0]||f.payload?.tool||"")}`.slice(0,160)),note:`${c.length} call(s) denied before running by the node's PreToolUse guard (${p.join(", ")}) \u2014 BOSTRAT_AUDIT_GUARD is on for this node`})}}let O=wn(e),F=Object.values(h).reduce((c,p)=>c+p,0);if(O.headMissing&&F&&T.push({rule:"log-head-missing",severity:"medium",trackId:t,track:n,boxId:null,from:y(e[0]),to:y(e[0]),count:1,samples:[],note:`the log starts at seq ${O.firstSeq} \u2014 its earlier history is not on this node`}),O.chain.breaks.length){let c=new Map;for(let w of e)Number.isFinite(w?.seq)&&!c.has(w.seq)&&c.set(w.seq,w);let p=O.chain.breaks.filter(w=>w.kind==="prev-mismatch"||w.kind==="seq-repeat"),f=w=>y(c.get(w.seq))||y(e.at(-1)),$=O.chain.breaks[0],_=O.chain.breaks.at(-1);T.push({rule:"chain-broken",severity:p.length?"high":"medium",trackId:t,track:n,boxId:null,from:f($),to:f(_),count:O.chain.breaks.length,samples:O.chain.breaks.slice(0,M).map(Sn),note:`the log's hash chain breaks ${O.chain.breaks.length} time(s) on this node \u2014 advisory: the plane's verified head is the anchor (GET /plane/admin/chain/${t??"<track>"})`})}return{trackId:t,track:n,actions:F,byOrigin:h,byEvidence:S,byProvider:g,commits:D,findings:T,integrity:O}}var et={high:0,medium:1,low:2};function ot(e,{days:t=14,now:n=Date.now()}={}){let o=t?n-t*864e5:0,s={days:t||null,tracks:0,actions:0,byOrigin:{},byStrength:{strong:0,weak:0,flagged:0},byEvidence:{keyed:0,turn: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 r of e||[]){let a=$n(r.events||[],{trackId:r.trackId,name:r.name,since:o});s.integrity.logs++,a.integrity.headMissing&&s.integrity.headMissing++,a.integrity.gaps&&s.integrity.withGaps++,a.integrity.repeats&&s.integrity.withRepeats++;let u=a.integrity.chain?.state;if(u==="intact"?s.integrity.chain.intact++:u==="intact-from-mid-log"?s.integrity.chain.intactFromMidLog++:u==="broken"?s.integrity.chain.broken++:s.integrity.chain.preChain++,!(!a.actions&&!a.findings.length)){s.tracks++,s.actions+=a.actions;for(let l of Object.keys(s.byEvidence))s.byEvidence[l]+=a.byEvidence?.[l]||0;for(let l of Object.keys(s.commits))s.commits[l]+=a.commits?.[l]||0;for(let[l,i]of Object.entries(a.byOrigin))s.byOrigin[l]=(s.byOrigin[l]||0)+i,s.byStrength[Ae[l]||"flagged"]+=i;for(let[l,i]of Object.entries(a.byProvider)){s.byProvider[l]||={actions:0,fidelity:i.fidelity,identified:!1,turnKeyed:!1,rooted:{key:0,turn:0,timing:0}},s.byProvider[l].actions+=i.actions,i.fidelity==="hook"&&(s.byProvider[l].fidelity="hook"),i.identified&&(s.byProvider[l].identified=!0),i.turnKeyed&&(s.byProvider[l].turnKeyed=!0);for(let d of["key","turn","timing"])s.byProvider[l].rooted[d]+=i.rooted?.[d]||0}s.findings.push(...a.findings)}}for(let[r,a]of Object.entries(s.byProvider))a.note=tt[r]?.note??(a.fidelity==="hook"?"hook-sourced":"transcript-sourced (a record the agent writes); no turn structure read by its adapter \u2014 calls attributed to the latest prompt");return s.findings.sort((r,a)=>et[r.severity]-et[a.severity]||a.to-r.to),s.ok=!s.findings.some(r=>r.severity==="high"),s}var J=(e,t)=>t?`${(e/t*100).toFixed(e&&e/t<.001?2:1)}%`:"0%",_e=e=>new Date(e).toISOString().slice(0,16).replace("T"," ");function st(e,{limit:t=20,containment:n=null}={}){let o=[];o.push(`AGENT ACTION AUDIT \xB7 ${e.days?`last ${e.days}d`:"all history"} \xB7 ${e.actions} action(s) across ${e.tracks} Track(s)`),o.push(""),o.push("Who asked for it");for(let l of["strong","weak","flagged"]){let i=Object.entries(e.byOrigin).filter(([d])=>(Ae[d]||"flagged")===l).sort((d,m)=>m[1]-d[1]);if(i.length){o.push(` ${l.toUpperCase()} \xB7 ${e.byStrength[l]} (${J(e.byStrength[l],e.actions)})`);for(let[d,m]of i)o.push(` ${d.padEnd(27)} ${String(m).padStart(7)} ${J(m,e.actions)}`)}}o.push("");let s=e.byEvidence||{keyed:0,turn:0,timing:0};o.push(`Rooted by recorded key \xB7 ${s.keyed} (${J(s.keyed,e.actions)})`+(s.turn?` \xB7 by its transcript turn only \xB7 ${s.turn} (${J(s.turn,e.actions)})`:"")+` \xB7 by timing \xB7 ${s.timing} (${J(s.timing,e.actions)})`);let r=e.commits||{total:0,keyed:0,timing:0,unrooted:0};r.total&&o.push(`Commits \xB7 ${r.total}: ${r.keyed} cite their turn, ${r.timing} inside an open turn, ${r.unrooted} unrooted`),o.push(""),o.push("Evidence by provider");for(let[l,i]of Object.entries(e.byProvider).sort((d,m)=>m[1].actions-d[1].actions)){let d=i.rooted||{key:0,turn:0,timing:0},m=i.fidelity==="hook"?`${d.key} by recorded key \xB7 ${d.timing} by timing`:i.turnKeyed?`${d.key} cite the send that opened their turn \xB7 ${d.turn} cite only their transcript turn \xB7 ${d.timing} by timing (no turn key)`:"all by timing (attributed to the latest prompt)";o.push(` ${l.padEnd(10)} ${String(i.actions).padStart(7)} `+(i.fidelity==="hook"?`hook-recorded (turn boundaries known${i.identified?"; calls identified, intent and outcome paired":""})`:i.turnKeyed?"transcript-recorded (agent-written; turns keyed by the CLI's own record)":"transcript only (agent-written; no turn boundaries)")+` \xB7 ${m}`);let h=i.note??tt[l]?.note;h&&o.push(` ${h}`)}o.push("");let a=e.integrity,u=a.chain||{intact:0,intactFromMidLog:0,broken:0,preChain:0};if(o.push(`Log integrity \xB7 ${a.logs} log(s): hash chain intact on ${u.intact} from seq 1 and ${u.intactFromMidLog} from mid-log, broken on ${u.broken}, ${u.preChain} pre-chain (written before the chain); ${a.headMissing} missing their head, ${a.withGaps} with seq gaps, ${a.withRepeats} with repeated seq`),o.push(" (the chain is walked over this node's copy \u2014 advisory; the plane's verified head is the anchor)"),o.push(""),!e.findings.length)o.push("Findings: none.");else{o.push(`Findings \xB7 ${e.findings.length}`);for(let l of e.findings.slice(0,t)){let i=l.to-l.from>B?`${_e(l.from)} \u2192 ${_e(l.to).slice(11)}`:_e(l.from),d=l.actions?`${l.count} prompt(s), ${l.actions} action(s)`:`${l.count}`;o.push(` [${l.severity}] ${l.rule} \xB7 ${l.track||l.trackId}${l.boxId?` \xB7 ${l.boxId}`:""} \xB7 ${i} \xB7 ${d}`),o.push(` ${l.note}`);for(let m of l.samples)o.push(` - ${m}`)}e.findings.length>t&&o.push(` \u2026 ${e.findings.length-t} more (--json for all)`)}return o.push(""),o.push(e.ok?`No action without an origin. ${n||"The log is agent-writable, so this is evidence, not proof."}`:`Actions with NO origin were found \u2014 read the [high] findings above.${n?` ${n}`:""}`),o.join(`
3
+ `)}import X from"node:fs";import at from"node:fs/promises";import re from"node:os";import A from"node:path";import{execFile as ct}from"node:child_process";import{promisify as _n}from"node:util";var Ne=_n(ct),rt="BOSTRAT_BOX_USER",xn="bostrat-box",lt=Object.freeze(["root","sudo","wheel","admin","docker","lxd","libvirt","disk"]);var Tn=/^[a-z_][a-z0-9_-]{0,31}$/,An=new Set(["","off","0","false","no","none"]),ut=e=>e.BOSTRAT_STATE_DIR||A.join(e.HOME||re.homedir(),".bostrat");function dt(e){try{return X.readFileSync(e,"utf8").split(`
4
+ `).filter(t=>t&&!t.startsWith("#")).map(t=>t.split(":"))}catch{return[]}}function pt(e,t=process.env){let o=dt(t.BOSTRAT_PASSWD_FILE||"/etc/passwd").find(s=>s[0]===String(e)||s[2]===String(e));return o?{name:o[0],uid:Number(o[2]),gid:Number(o[3]),home:o[5]||null,shell:o[6]||null}:null}function ft(e,t=process.env){let n=dt(t.BOSTRAT_GROUP_FILE||"/etc/group"),o=new Set;for(let s of n)Number(s[2])===e.gid&&o.add(s[0]),(s[3]||"").split(",").includes(e.name)&&o.add(s[0]);return[...o].sort()}var se=()=>typeof process.getuid=="function"?process.getuid():0,Oe=null;function ie(e=process.env){let t=String(e[rt]||"").trim();if(An.has(t.toLowerCase()))return null;let n=`${t}|${e.BOSTRAT_PASSWD_FILE||""}|${e.BOSTRAT_GROUP_FILE||""}|${e.BOSTRAT_BOX_HOME_VIEW||""}`;if(Oe?.key===n)return Oe.value;let o;if(!Tn.test(t))o={name:t,error:`${rt}="${t}" is not a valid user name`};else{let s=pt(t,e),r=se();if(!s)o={name:t,error:`user "${t}" does not exist \u2014 run scripts/pi/box-user-setup.sh (or the image's useradd)`};else if(s.uid===0)o={name:t,error:`user "${t}" is root`};else if(s.uid===r)o={name:t,error:`user "${t}" is the node's own uid`};else if(!s.home||s.home==="/"||s.home==="/nonexistent")o={name:t,error:`user "${t}" has no home directory`};else{let a=ft(s,e),u=a.filter(l=>lt.includes(l));o=u.length?{name:t,error:`user "${t}" is in ${u.join(", ")} \u2014 a box user must hold no route to root`}:{...s,groups:a,nodeUid:r,rootNode:r===0}}}return Oe={key:n,value:o},o}function In(e=process.env){let t=ie(e);return t&&!t.error?t.home:re.homedir()}function it(e=process.env){let t=ie(e);return!t||t.error||t.rootNode?In(e):e.BOSTRAT_BOX_HOME_VIEW||A.join(ut(e),"box-home")}function On(e,t=process.env){let n=ie(t);return!n||n.error?e:n.rootNode?["setpriv",`--reuid=${n.uid}`,`--regid=${n.gid}`,"--init-groups","--","env",`HOME=${n.home}`,`USER=${n.name}`,`LOGNAME=${n.name}`,...e]:["sudo","-n","-H","-u",n.name,"--",...e]}async function Re(e,{env:t=process.env,input:n=null,timeout:o=15e3}={}){let[s,...r]=On(e,t);return n==null?Ne(s,r,{timeout:o}):new Promise((a,u)=>{ct(s,r,{timeout:o},(i,d,m)=>i?u(i):a({stdout:d,stderr:m})).stdin.end(n)})}var ve;function Rn(e){return e.BOSTRAT_SETFACL_BIN?e.BOSTRAT_SETFACL_BIN:(ve===void 0&&(ve=["/usr/bin/setfacl","/bin/setfacl"].find(t=>X.existsSync(t))||null),ve)}function vn(e=process.env){let t=re.homedir(),n=ut(e);return[A.join(t,".ssh"),A.join(t,".claude.json"),A.join(t,".claude",".credentials.json"),A.join(t,".codex","auth.json"),A.join(t,".config","gh","hosts.yml"),A.join(t,".cursor","cli-config.json"),A.join(n,"node.env"),A.join(n,"api-token"),A.join(n,"plane-link"),A.join(n,"secure-inputs")]}async function ht({env:e=process.env,probe:t=!0}={}){let n=ie(e),o=await Dn(e);if(!n){let r=pt(se(),e)||{name:re.userInfo().username,uid:se(),gid:-1},a=r.uid===0?["root"]:ft(r,e).filter(i=>lt.includes(i)),u=r.uid!==0&&t?await jn():!1,l=[...a,...u&&!a.includes("sudo")?["sudo (sudoers)"]:[]];return{level:l.length?"root-capable":"node-uid",user:r.name,routes:l,problems:[],auditd:o}}if(n.error)return{level:"misconfigured",user:n.name,error:n.error,problems:[n.error],auditd:o};let s=[];if(t){try{let{stdout:l}=await Re(["id","-u"],{env:e,timeout:5e3});Number(l.trim())!==n.uid&&s.push(`switching to ${n.name} landed as uid ${l.trim()}`)}catch(l){s.push(`the node cannot switch to ${n.name} (${n.rootNode?"setpriv":"sudo -n -u"} failed: ${Nn(l)})`)}if(!s.length){await Re(["sudo","-n","true"],{env:e,timeout:5e3}).then(()=>!0,()=>!1)&&s.push(`${n.name} can sudo`);let l=[];for(let i of vn(e))X.existsSync(i)&&await Re(["test","-r",i],{env:e,timeout:5e3}).then(()=>!0,()=>!1)&&l.push(i);l.length&&s.push(`${n.name} can read ${l.join(", ")}`)}Rn(e)||s.push("setfacl is missing (apt install acl)");let r=it(e);r!==n.home&&!X.existsSync(A.join(r,".claude"))&&s.push(`the read-only mirror of ${n.home} is not mounted at ${r} \u2014 the node cannot read box transcripts`);let a=A.join(n.home,".claude","settings.json"),u=await at.stat(a).catch(()=>null);u&&u.uid===n.uid&&s.push(`${a} is owned by ${n.name} \u2014 the box can rewrite its own hooks`)}return{level:"uid",user:n.name,uid:n.uid,home:n.home,view:it(e),problems:s,auditd:o}}var Nn=e=>String(e?.stderr||e?.message||e).trim().split(`
5
+ `)[0].slice(0,160);async function jn(){try{return await Ne("sudo",["-n","true"],{timeout:3e3}),!0}catch{return!1}}async function Dn(e=process.env,{ask:t=!0}={}){let n=e.BOSTRAT_AUDIT_LOG||"/var/log/audit/audit.log",o=!1;try{await at.access(n,X.constants.R_OK),o=!0}catch{}let s=e.BOSTRAT_AUDIT_RULES_FILE||"/etc/audit/rules.d/bostrat-box.rules",r=X.existsSync(s),a=null;if(t&&r){let u=se()===0?["auditctl",["-l"]]:["sudo",["-n","auditctl","-l"]];try{let{stdout:l}=await Ne(u[0],u[1],{timeout:5e3});a=l.includes(`key=${xn}`)}catch{a=null}}else r||(a=!1);return{log:n,readable:o,configured:r,rule:a,rulesFile:s}}function mt(e){return e.level==="uid"&&!e.problems.length?`Boxes on this node run as ${e.user}, which holds no route to root and cannot write the event log or its hook settings${e.auditd?.rule===!0&&e.auditd?.readable?"; its every exec is logged by auditd and shipped to the plane":""}.`:e.level==="uid"?`Boxes on this node run as ${e.user}, but containment has gaps (${e.problems.join("; ")}) \u2014 treat this record as evidence, not proof.`:e.level==="root-capable"?`Boxes on this node are root-capable (${e.user}: ${e.routes.join(", ")}), so a root-capable agent can defeat node-side evidence \u2014 this is evidence, not proof.`:e.level==="misconfigured"?`Box containment is configured but unusable (${e.error}); no box can start until it is fixed.`:`Boxes on this node share the node's uid (${e.user}), so an agent can rewrite its own log \u2014 this is evidence, not proof.`}var Pn="BP-AU-R4",xt=160,gt={high:0,medium:1,low:2},yt=200,bt=5,wt=8,St=5,kt=10*6e4,Mn=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"]),Cn=5e3,Pe=new Set(["tool.called","tool.failed"]),je=new Set(["Write","Edit","NotebookEdit"]),Ln=e=>String(e??"").replace(/\s+/g," ").trim(),L=(e,t=120)=>Ln(e).slice(0,t);function Un(e,t=xt){let n=String(e??""),o=n.split(/\s*(?:;|&&|\|\||\||\n)\s*/).map(s=>s.trim()).filter(Boolean);return Number.isFinite(t)&&n.length>=t&&o.length&&o.pop(),o}function ae(e){return String(e??"").replace(/\d?>>?\s*\S+|<\s*\S+|2>&1/g," ").trim().split(/\s+/).filter(Boolean)}function Tt(e){let t=0;for(;t<e.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[t]);)t++;return{cmd:e[t]??null,rest:e.slice(t+1),at:t}}function Et(e){let t=ae(e),n=t.findIndex(i=>i==="git"||i.endsWith("/git"));if(n<0)return null;for(n++;n<t.length&&t[n].startsWith("-");)(t[n]==="-C"||t[n]==="-c")&&n++,n++;if(t[n]!=="push")return null;let o=[],s=[];for(let i=n+1;i<t.length;i++){let d=t[i];d.startsWith("-")?(o.push(d),(d==="-o"||d==="--push-option"||d==="--repo"||d==="--receive-pack"||d==="--exec")&&i++):s.push(d)}let r=o.some(i=>i==="--force"||/^-[a-zA-Z]+$/.test(i)&&i.includes("f"))||s.some(i=>i.startsWith("+")),a=o.some(i=>i.startsWith("--force-with-lease")||i.startsWith("--force-if-includes")),u=s[0]??null,l=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:r,lease:a,remote:u,dsts:l}}var Me=String.raw`(?:~|\$HOME|\$\{HOME\}|/home/[^\s/"']+|/root|/Users/[^\s/"']+)`,Hn=new RegExp(`${Me}/\\.ssh(?:/|\\b)`),Bn=new RegExp(`${Me}/(?:\\.claude\\.json\\b|\\.claude/\\.credentials\\.json|\\.codex/auth\\.json|\\.cursor(?:/|\\b))`),Fn=/(?:^|[\s/"'=(])(\.env(?:\.[A-Za-z0-9_.-]+)?)(?=$|[\s"'|;&)])/g,Wn=/^\.env\.(?:example|sample|template|dist)$/,At=/(\.claude\/settings(?:\.local)?\.json|\.claude\/hooks\/[^\s"']*|\.bostrat\/events(?:\/[^\s"']*)?)/,It=new RegExp(`((?:/etc|/usr/lib|/lib|/run)/systemd/[^\\s"']*|${Me}/\\.config/systemd/[^\\s"']*|/etc/cron(?:tab|\\.d|\\.hourly|\\.daily|\\.weekly|\\.monthly)(?:/[^\\s"']*)?|/var/spool/cron(?:/[^\\s"']*)?)`),qn=/^(?: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)$/,Kn=/^\/tmp\/|\/\.bostrat\/tmp\//,Gn=/^(?:refs\/heads\/)?(?:main|master|develop|development|trunk|production|prod|staging|release(?:\/|$)|v\d)/,Xn=/(?:^|\/)track\/|^HEAD$|^refs\/bostrat\//,Vn=/https?:\/\/([a-z0-9.-]+\.[a-z]{2,}|localhost|\d+\.\d+\.\d+\.\d+)(?::\d+)?/gi,$t=e=>Hn.test(e)||Bn.test(e),_t=e=>[...String(e??"").matchAll(Fn)].some(t=>!Wn.test(t[1])),zn=e=>At.test(e),Yn=e=>It.test(e),Jn=e=>(e.startsWith("/")||e.startsWith("~"))&&!Kn.test(e);function Ot(e){let{cmd:t,at:n}=Tt(e);if(t==="sudo"){for(n++;n<e.length&&e[n].startsWith("-");)n++;t=e[n]??null}return{cmd:t,at:n}}function Rt(e,t){let n=String(e??"").match(t);if(!n)return null;let o=n[1],s=o.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&");if(new RegExp(`>{1,2}\\s*["']?[^\\s"']*${s}`).test(e))return"redirect";let r=ae(e),{cmd:a}=Ot(r);return!a||!r.some(u=>u.includes(o))?null:/^(?:rm|mv|truncate|chmod|chown|tee|install|shred|unlink|ln|mkdir|touch)$/.test(a)?a:a==="sed"&&r.some(u=>/^-[a-zA-Z]*i/.test(u))?"sed -i":a==="cp"&&r[r.length-1].includes(o)?"cp":/^(?:python3?|perl|node|ruby)$/.test(a)&&/open\([^)]*['"][wa]|writeFile|write_text|appendFile|fs\.write/.test(e)?`${a} write`:null}var Zn=e=>Rt(e,At);function Qn(e){let t=ae(e),{cmd:n,at:o}=Ot(t);if(!n)return null;let s=t.slice(o+1);if(n==="crontab"||n.endsWith("/crontab")){let a=!1,u=!1;for(let l=0;l<s.length;l++){if(s[l]==="-u"){l++;continue}s[l]==="-l"||/^-(?:h|V|T|-help|-version)$/.test(s[l])?a=!0:u=!0}return u||!a?"crontab":null}if(n==="systemctl"||n.endsWith("/systemctl")){let a=s.find(u=>!u.startsWith("-"));return a&&qn.test(a)?`systemctl ${a}`:null}if((n==="loginctl"||n.endsWith("/loginctl"))&&s.includes("enable-linger"))return"loginctl enable-linger";if(n==="at"&&s.length&&/^(?:now|midnight|noon|teatime|today|tomorrow|next|\d|-[fqmvt])/.test(s[0]))return"at";let r=Rt(e,It);return r?`${r} unit/cron path`:null}function eo(e){let t=new Set;for(let n of String(e??"").matchAll(Vn))t.add(n[1].toLowerCase());return[...t]}function to({knownHosts:e=[]}={}){return{known:new Set([...Mn,...[...e].map(t=>String(t).toLowerCase()).filter(Boolean)]),hosts:new Set,tracks:new Map}}function no(e,t){let n=e.tracks.get(t??"");return n||e.tracks.set(t??"",n={costs:[],peer:new Map}),n}var I=(e,t,n,o)=>Object.freeze({severity:e,requirement:Pn,note:t,measured:n,detect:o}),Q=(e,t)=>{let n=0,o=null;for(let s of e.calls)if(s.head)for(let r of Un(s.head,e.headCap)){let a=t(r,s);a&&(n++,o??=L(a))}return n?{count:n,sample:o}:null},De=(e,t)=>{let n=0,o=null;for(let s of e.calls){let r=t(s);r&&(n++,o??=L(r))}return n?{count:n,sample:o}:null},V=Object.freeze({"force-push":I("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",(e,t)=>Q(t,n=>{let o=Et(n);return o&&o.force&&!o.lease?n:null})),"protected-config-write":I("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",(e,t)=>{let n=0,o=null;for(let r of t.calls)je.has(r.tool)&&r.path&&zn(r.path)&&(n++,o??=L(`${r.tool} ${r.path}`));let s=Q(t,r=>{let a=Zn(r);return a?`${a}: ${r}`:null});return s&&(n+=s.count,o??=s.sample),n?{count:n,sample:o}:null}),"persistence-install":I("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",(e,t)=>{let n=0,o=null;for(let r of t.calls)je.has(r.tool)&&r.path&&Yn(r.path)&&(n++,o??=L(`${r.tool} ${r.path}`));let s=Q(t,r=>{let a=Qn(r);return a?`${a}: ${r}`:null});return s&&(n+=s.count,o??=s.sample),n?{count:n,sample:o}:null}),"push-outside-track":I("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",(e,t)=>Q(t,n=>{let o=Et(n);return o&&(o.remote&&!/^(?:origin|upstream)$/.test(o.remote)&&!o.remote.startsWith("$")&&!o.remote.startsWith("-")||o.dsts.some(s=>Gn.test(s)||!Xn.test(s)))?n:null})),"credential-read":I("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",(e,t)=>De(t,n=>n.head&&$t(n.head)?n.head:n.path&&$t(n.path)?`${n.tool} ${n.path}`:null)),"dotenv-read":I("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)",(e,t)=>De(t,n=>n.head&&_t(n.head)?n.head:n.path&&_t(n.path)?`${n.tool} ${n.path}`:null)),"privileged-command":I("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)",(e,t)=>Q(t,n=>{let{cmd:o}=Tt(ae(n));return o==="sudo"||o==="docker"?n:null})),"write-outside-workspace":I("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)",(e,t)=>De(t,n=>je.has(n.tool)&&n.path&&Jn(n.path)?`${n.tool} ${n.path}`:null)),"egress-new-host":I("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)",(e,t)=>{let n=0,o=null;for(let s of t.calls)if(s.head)for(let r of eo(s.head))t.state.known.has(r)||t.state.hosts.has(r)||(t.state.hosts.add(r),t.state.hosts.size>Cn&&t.state.hosts.delete(t.state.hosts.values().next().value),n++,o??=L(`${r} \xB7 ${s.head}`));return n?{count:n,sample:o}:null}),"spend-spike":I("low",`a cost.recorded turn over ${wt}\xD7 the Track's running median (its last ${yt} cost events, at least ${bt} of them) and over $${St} \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)",(e,t)=>{if(e.type!=="cost.recorded")return null;let n=t.track.costs,o=Number(e.payload?.usd);if(!Number.isFinite(o)||o<0)return null;let s=null;if(n.length>=bt&&o>=St){let r=[...n].sort((u,l)=>u-l),a=r[Math.floor(r.length/2)];o>wt*a&&(s={count:1,sample:`$${o.toFixed(2)} vs median $${a.toFixed(2)} over ${n.length} turns${e.payload?.model?` \xB7 ${e.payload.model}`:""}`})}return n.push(o),n.length>yt&&n.shift(),s}),"peer-injected-call":I("medium",`a tool call within ${kt/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",(e,t)=>{if(!t.calls.length)return null;let n=t.track.peer.get(t.boxKey);if(n==null||t.ts-n>kt||t.ts<n)return null;let o=t.calls[0];return{count:t.count,sample:L(`${Math.round((t.ts-n)/1e3)}s after a peer message \xB7 ${o.tool}${o.head?`: ${o.head}`:o.path?` ${o.path}`:""}`)}}),"foreign-session-call":I("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",(e,t)=>{if(!t.calls.length||!e.payload?.foreignSession)return null;let n=t.calls[0];return{count:t.count,sample:L(`session ${String(e.payload.sessionId||"?").slice(0,8)} \xB7 ${n.tool}${n.head?`: ${n.head}`:n.path?` ${n.path}`:""}`)}}),"orphan-process":I("medium","a process the box left running: detached from the pane's tree (its cgroup or pty still lists it), alive at a turn's close and still alive minutes later with no turn open and no background job recorded \u2014 the node's own census (orphan-watch.js, BP-AU-D6), each process once","2026-10-27 fleet replay \xB7 0 audit.procs events in 304,814 (1,121 logs; the type is new, so the replay cannot bound this rule's rate) \xB7 live Pi census the same day: 10 boxes, 2 detached processes, both found by the cgroup census and neither by the pty one (a claude tool call runs on pipes) \u2014 one planted `nohup sleep &`, one real `flyctl agent run` that a lead's flyctl call had left behind 10 h earlier \u2192 medium (rail), never a page, until a window of live samples has been measured",e=>{if(e.type!=="audit.procs"||e.source!=="proc")return null;let t=e.payload||{},n=Array.isArray(t.orphans)?t.orphans:[],o=n.length+(Number(t.dropped)||0);if(!o)return null;let s=n[0]||{},r=Number.isFinite(s.sinceMs)?` \xB7 alive ${Math.max(1,Math.round(s.sinceMs/6e4))} min`:"";return{count:o,sample:L(`${s.comm||"process"}${s.cmd?`: ${s.cmd}`:""}${s.via?` [${s.via}]`:""}${r}${o>1?` (+${o-1} more)`:""}`)}}),"unknown-harness-shape":I("medium","a harness-made user turn of a shape chat-notes.js does not list (harness.shape.seen with known: false, harness-shapes.js): Claude Code wrote a new kind of its own turn into a transcript \u2014 hidden from chat by the generic catch, counted once per shape per node here; the node pages the operator once on first sight, this row is the fleet's record","2026-10-28 fleet replay \xB7 0 harness.shape.seen events in 311,055 (1,132 logs; the type is new, so the replay cannot bound this rule's rate) \xB7 transcript scan the same day: 2,863 claude user turns in 1,539 transcripts over 90 d, 144 of them harness-made (isMeta), 9 distinct shapes, 4 of which had rendered in chat as operator messages (<system-reminder><tools-used-before-summary> on 2 Tracks under 2.1.312, a usage-limit-reset notice, a safety-classifier notice) \u2192 medium (rail finding + security row), never a page from the plane: the once-per-shape page is the node's, so a release that adds one shape pages once, not per Track per hour",e=>{if(e.type!=="harness.shape.seen"||e.source!=="transcript")return null;let t=e.payload||{};if(t.known!==!1||!t.key)return null;let n=`${t.provider||"cli"}${t.cliVersion?` ${t.cliVersion}`:""}`;return{count:1,sample:L(`${t.key} \xB7 ${n}${t.head?` \xB7 ${t.head}`:""}`)}})}),z=Object.freeze(Object.keys(V)),oo=new Set([...Pe,"cost.recorded","peer.message","turn.user","audit.procs","harness.shape.seen"]);function so(e,t,{rules:n=null,headCap:o=xt}={}){if(!t||!oo.has(t.type)||t.source==="plane")return[];let s=no(e,t.trackId),r=t.payload||{},a=t.boxId??"",u=Number(t.ts)||0;if(t.type==="turn.user")return(t.actor==="user"||t.actor==="orchestrator")&&s.peer.delete(a),[];if(t.type==="peer.message")return s.peer.set(a,u),[];let l=Pe.has(t.type)&&t.source==="hook",d={calls:l?P(r):[],count:l?q(r):0,track:s,state:e,ts:u,boxKey:a,headCap:o},m=[];for(let h of n||z){let g=V[h];if(!g)continue;let S=null;try{S=g.detect(t,d)}catch{S=null}S&&S.count>0&&m.push({rule:h,count:S.count,sample:S.sample??null})}return m}function vt(e,{days:t=14,now:n=Date.now(),rules:o=null}={}){let s=t?n-t*864e5:0,r=to(),a=o||z,u={days:t||null,logs:0,events:0,calls:0,callsInWindow:0,rules:Object.fromEntries(a.map(i=>[i,{severity:V[i].severity,note:V[i].note,measured:V[i].measured,hits:0,hitsInWindow:0,events:0,tracks:0,tracksInWindow:0,perTenK:0,samples:[]}]))},l=Object.fromEntries(a.map(i=>[i,{all:new Set,win:new Set}]));for(let i of e||[]){let d=Array.isArray(i?.events)?[...i.events].sort((m,h)=>(Number(m.ts)||0)-(Number(h.ts)||0)):[];if(d.length){u.logs++;for(let m of d){u.events++;let h=(Number(m.ts)||0)>=s;if(Pe.has(m.type)&&m.source==="hook"){let g=q(m.payload||{});u.calls+=g,h&&(u.callsInWindow+=g)}for(let g of so(r,m,{rules:a})){let S=u.rules[g.rule];if(S.hits+=g.count,S.events++,l[g.rule].all.add(m.trackId??i.trackId),h&&(S.hitsInWindow+=g.count,l[g.rule].win.add(m.trackId??i.trackId)),g.sample){let j=S.samples.find(b=>b.text===g.sample);j?j.n++:S.samples.length<200&&S.samples.push({text:g.sample,n:1,ts:Number(m.ts)||0,trackId:m.trackId??i.trackId,name:i.name??null})}}}}}for(let i of a){let d=u.rules[i];d.tracks=l[i].all.size,d.tracksInWindow=l[i].win.size,d.perTenK=u.calls?Number((d.hits/u.calls*1e4).toFixed(2)):0,d.samples.sort((m,h)=>h.n-m.n||h.ts-m.ts),d.samples=d.samples.slice(0,50)}return u.ok=!a.some(i=>V[i].severity==="high"&&u.rules[i].hitsInWindow>0),u}var ro=e=>new Date(e).toISOString().slice(0,10);function Nt(e,{samples:t=5}={}){let n=[];n.push(`R4 DETECTOR REPLAY \xB7 ${e.days?`window last ${e.days}d`:"all history"} \xB7 ${e.logs} logs \xB7 ${e.events.toLocaleString()} events \xB7 ${e.calls.toLocaleString()} hook calls (${e.callsInWindow.toLocaleString()} in window)`),n.push("A rule's severity is what its measured rate supports; `high` pages (D7). Hits are what the plane fold would have flagged.");let o=Object.keys(e.rules).sort((s,r)=>gt[e.rules[s].severity]-gt[e.rules[r].severity]||s.localeCompare(r));for(let s of o){let r=e.rules[s];n.push(""),n.push(`${s} [${r.severity}] \xB7 ${r.hits} hit(s) all-time (${r.events} events, ${r.tracks} Tracks, ${r.perTenK}/10k calls) \xB7 ${r.hitsInWindow} in window (${r.tracksInWindow} Tracks)`),n.push(` ${r.note}`),r.measured&&n.push(` measured: ${r.measured}`);for(let a of r.samples.slice(0,t))n.push(` ${a.n}\xD7 ${ro(a.ts)} ${a.name?`${a.name} `:""}(${a.trackId}) ${a.text}`)}return n.push(""),n.push(e.ok?"ok: no high-severity detector hit in the window":"ATTENTION: a high-severity detector hit inside the window (exit 2)"),n.join(`
6
+ `)}import Ft from"node:fs/promises";import Oo from"node:os";import qe from"node:path";import He from"node:fs/promises";import Y from"node:path";import mo from"node:os";import{EventEmitter as go}from"node:events";import{randomUUID as yo}from"node:crypto";import ce from"node:fs";import ue from"node:path";import io from"node:os";var ao=()=>process.env.BOSTRAT_STATE_DIR||ue.join(process.env.HOME||io.tmpdir(),".bostrat"),co="secure-inputs",Pt=()=>ue.join(ao(),co),lo=/^[A-Z][A-Z0-9_]{0,63}$/,uo=/^[A-Za-z0-9_-]{1,80}$/,po=16*1024;var Ce=8;function fo(e){return typeof e!="string"||!e?"a value is required":e.length<Ce?`a value must be at least ${Ce} characters`:Buffer.byteLength(e,"utf8")>po?"that value is too large (16 KiB max)":/[\0\r\n]/.test(e)?"a value must be one line":null}var Le=new Map,ee=[],jt=!1;function ho(){let e=[];for(let t of Le.values())for(let[n,{value:o}]of t){let s=`\u2039${n}\u203A`,r=new Set([o]);r.add(encodeURIComponent(o)),r.add(Buffer.from(o,"utf8").toString("base64")),r.add(Buffer.from(o,"utf8").toString("base64url")),r.add(JSON.stringify(o).slice(1,-1));for(let a of r)a&&a.length>=Ce&&e.push({needle:a,mark:s})}e.sort((t,n)=>n.needle.length-t.needle.length),ee=e}function Dt(e){return ue.join(Pt(),e)}function Mt(){if(jt)return;jt=!0,Le.clear();let e=[];try{e=ce.readdirSync(Pt(),{withFileTypes:!0})}catch{e=[]}for(let t of e){if(!t.isDirectory()||!uo.test(t.name))continue;let n=new Map,o=[];try{o=ce.readdirSync(Dt(t.name),{withFileTypes:!0})}catch{continue}for(let s of o)if(!(!s.isFile()||!lo.test(s.name)))try{let r=ue.join(Dt(t.name),s.name),a=ce.readFileSync(r,"utf8");if(fo(a))continue;n.set(s.name,{value:a,addedAt:ce.statSync(r).mtimeMs})}catch{}n.size&&Le.set(t.name,n)}ho()}function Ct(){return Mt(),ee.length>0}function Ue(e){if(typeof e!="string"||!e||(Mt(),!ee.length))return e;let t=e;for(let{needle:n,mark:o}of ee)t.includes(n)&&(t=t.split(n).join(o));return t}function le(e,t=new WeakSet){if(typeof e=="string")return Ue(e);if(!e||typeof e!="object"||!ee.length||t.has(e))return e;if(t.add(e),Array.isArray(e)){let s=!1,r=e.map(a=>{let u=le(a,t);return u!==a&&(s=!0),u});return s?r:e}if(Buffer.isBuffer(e)||e instanceof Date)return e;let n=!1,o={};for(let s of Object.keys(e)){let r=le(e[s],t);r!==e[s]&&(n=!0),o[s]=r}return n?o:e}var bo=new Set(["session.ready","session.foreign","turn.user","turn.agent","turn.retracted","peer.message","provider.error","delivery.queued","delivery.settled","turn.steered","turn.interrupted","turn.aborted","tool.started","tool.called","tool.failed","tool.result","prompt.raised","prompt.answered","prompt.dismissed","prompt.autoRejected","box.fullscreen.detected","box.fullscreen.answered","box.stuck.detected","box.stuck.answered","context.usage","context.refresh.offered","context.refresh.answered","handoff.offered","handoff.answered","automation.fired","refresh.flow.changed","cost.recorded","memory.seed","memory.harvested","handoff.artifact","code.pushed","code.committed","code.rework","rework.cause.offered","rework.cause.answered","rework.cause.retracted","handoff.started","handoff.step","handoff.done","handoff.failed","node.saturated","node.restarted","subtask.delegated","subtask.merged","job.started","job.stalled","job.stopped","pr.state.changed","pr.offered","pr.offer.answered","pr.exists.offered","pr.exists.answered","pr.update.reported","pr.train.boarded","pr.train.landed","pr.train.ejected","pr.train.rebuilt","box.state.changed","view.state.changed","view.spinup.failed","deps.prepare","deps.setup","secret.added","secret.renamed","secret.removed","secret.used","mock.state.changed","flow.state.changed","runbook.state.changed","ticket.linked","ticket.sync.failed","ticket.move.offered","ticket.move.answered","ticket.state.changed","ticket.commented","ticket.flow.changed","ticket.create.offered","ticket.create.answered","ticket.created","loop.create.offered","loop.create.answered","loop.created","loop.update.offered","loop.update.answered","loop.updated","loop.delete.offered","loop.delete.answered","loop.deleted","loop.paused","replay.spec.offered","replay.spec.answered","followup.armed","followup.armed.cancelled","followup.arm.saved","followup.offered","followup.answered","followup.create.offered","followup.create.answered","followup.created","planning.change.offered","planning.change.answered","planning.changed","notify.raised","usage.cap.hit","provider.limit.hit","usage.cap.warning","provider.login.started","provider.connected","track.summary.recorded","track.transferred","track.recovered","track.phase.changed","track.operation.changed","track.obligations.changed","track.interrupted.changed","track.circuit.tagged","blueprint.item.launched","blueprint.item.bound","decision.recorded","estimate.recorded","estimate.closed","changelog.published","track.conflict.predicted","track.conflict.cleared","audit.chain.broken","audit.chain.healed","audit.flagged","audit.exec","audit.procs","harness.shape.seen","stall.detected","error"]),wo=new Set(["user","agent","orchestrator","system","peer"]),So=new Set(["hook","otel","statusline","transcript","pane","orchestrator","vendor","cli","auditd","proc","plane"]),Be=new go;Be.setMaxListeners(0);var Fe=process.env.BOSTRAT_STATE_DIR||Y.join(process.env.HOME||mo.tmpdir(),".bostrat");function Lt(e){return e?.cwd?Y.join(e.cwd,".bostrat","events"):Y.join(Fe,"events")}var Ut=(e,t)=>Y.join(e,`${t}.ndjson`),te=new Map,pe=new Map,de=new Map;async function ko(e,t){if(te.has(t))return;let n=await xo(e,t),o=0,s=null;for(let r of n)r.seq>o&&(o=r.seq),Ee(r)&&(s=r);te.set(t,o),pe.set(t,s?oe(s):null)}function Eo(e,t){let o=(de.get(e)??Promise.resolve()).then(t,t),s=o.then(()=>{},()=>{});return de.set(e,s),s.then(()=>{de.get(e)===s&&de.delete(e)}),o}function $o(e,t){let n=Array.isArray(e?.epochs)?e.epochs:null;if(!(!n||n.length===0)){if(!Number.isFinite(t))return n.length-1;for(let o=n.length-1;o>=0;o--){let s=n[o].startedAt;if(s==null||s<=t)return o}return 0}}async function Ht(e,t){let n=typeof e=="string"?e:e?.id;if(!n)throw new Error("appendEvent: a track (or trackId) is required");if(!t||!bo.has(t.type))throw new Error(`appendEvent: unknown event type "${t?.type}"`);if(t.actor&&!wo.has(t.actor))throw new Error(`appendEvent: bad actor "${t.actor}"`);if(t.source&&!So.has(t.source))throw new Error(`appendEvent: bad source "${t.source}"`);let o=typeof e=="string"?Y.join(Fe,"events"):Lt(e),s=t.epoch;if(s==null&&typeof e=="object"&&t.boxId&&Array.isArray(e?.boxes)){let r=e.boxes.find(a=>a.name===t.boxId);s=$o(r,Number(t.payload?.ts??t.ts)||Date.now())}return Eo(n,async()=>{await ko(o,n);let r=te.get(n)+1;te.set(n,r);let a=pe.get(n)??null,u={id:t.id||yo(),trackId:n,boxId:t.boxId??null,...s!=null?{epoch:s}:{},seq:r,prev:a,ts:t.ts??Date.now(),type:t.type,actor:t.actor??"system",provider:t.provider??null,source:t.source??"orchestrator",payload:t.payload??{},...t.causationId?{causationId:t.causationId}:{},...t.correlationId?{correlationId:t.correlationId}:{}};if(Ct()){let d=le(u);d!==u&&Object.assign(u,d)}let l=JSON.stringify(u),i=u;fe(l)&&(l=he(l),i=JSON.parse(l)),pe.set(n,oe(i));try{await He.mkdir(o,{recursive:!0}),await He.appendFile(Ut(o,n),l+`
7
+ `)}catch(d){throw te.set(n,r-1),pe.set(n,a),d}return Be.emit("event",i),Be.emit(`track:${n}`,i),i})}var _o=/(?<!\\)((?:\\\\)*)\\u0000/g,fe=e=>e.includes("\\u0000"),he=e=>e.replace(_o,"$1\\ufffd");async function xo(e,t){let n,o;typeof e=="string"&&t?(n=e,o=t):(o=typeof e=="string"?e:e?.id,n=typeof e=="string"?Y.join(Fe,"events"):Lt(e));let s;try{s=await He.readFile(Ut(n,o),"utf8")}catch{return[]}return To(s)}function To(e){let t=[];for(let n of e.split(`
8
+ `))if(n.trim())try{t.push(JSON.parse(fe(n)?he(n):n))}catch{}return t}import me from"node:fs/promises";import Ao from"node:path";var Io=0;async function Bt(e,t,{mode:n}={}){await me.mkdir(Ao.dirname(e),{recursive:!0});let o=`${e}.${process.pid}.${++Io}.tmp`;try{await me.writeFile(o,JSON.stringify(t,null,2)+`
9
+ `,n!=null?{mode:n}:void 0),await me.rename(o,e)}catch(s){throw await me.unlink(o).catch(()=>{}),s}}var Ro=()=>process.env.BOSTRAT_STATE_DIR||qe.join(process.env.HOME||Oo.tmpdir(),".bostrat"),vo="harness-shapes.json",No=12,jo=8,Do=80,Po=e=>Ue(String(e||"").replace(/\s+/g," ").trim().slice(0,Do));function Mo({file:e=null,deps:t={},log:n=console}={}){let o={appendEvent:Ht,now:()=>Date.now(),...t},s=()=>e||qe.join(Ro(),vo),r=null,a=null,u=Promise.resolve();async function l(){return r||(a||(a=Ft.readFile(s(),"utf8").then(h=>{let g=JSON.parse(h);return g&&typeof g.shapes=="object"&&g.shapes?{version:1,shapes:g.shapes}:{version:1,shapes:{}}}).catch(()=>({version:1,shapes:{}})).then(h=>r=h)),a)}function i(){let h=JSON.stringify(r);return u=u.then(async()=>{await Ft.mkdir(qe.dirname(s()),{recursive:!0}),await Bt(s(),JSON.parse(h))}).catch(g=>n.warn?.(`[harness-shapes] write failed: ${g?.message||g}`)),u}async function d(h,g,S){if(!S||S.kind!=="harness"||!S.key)return null;let j=await l(),b=o.now(),x=String(S.key).slice(0,200),T=g?.agent||null,v=typeof g?.cliVersion=="string"?g.cliVersion:null,k=j.shapes[x],D=!k;D&&(k=j.shapes[x]={key:x,tags:Array.isArray(S.tags)?S.tags.slice(0,20):[],known:!!S.known,head:Po(S.head||g?.text),firstSeen:b,lastSeen:b,count:0,tracks:[],providers:{},versions:[],paged:!1}),k.lastSeen=b,k.count++,S.known&&!k.known&&(k.known=!0),h?.id&&!k.tracks.includes(h.id)&&(k.tracks.push(h.id),k.tracks.length>No&&k.tracks.shift()),T&&(k.providers[T]=(k.providers[T]||0)+1),v&&!k.versions.includes(v)&&(k.versions.push(v),k.versions.length>jo&&k.versions.shift());let O=!1;if(D&&h?.id){try{await o.appendEvent(h,{type:"harness.shape.seen",actor:"system",source:"transcript",boxId:g?.box??null,provider:T,payload:{key:x,tags:k.tags,known:k.known,head:k.head,provider:T,cliVersion:v,box:g?.box??null,count:1,ts:b}})}catch(F){n.warn?.(`[harness-shapes] harness.shape.seen append failed (${h.id}): ${F?.message||F}`)}if(!k.known&&!k.paged){k.paged=!0,O=!0;let F=k.tags.length?`<${k.tags.join("> <")}>`:`"${k.head}"`;try{await o.appendEvent(h,{type:"notify.raised",actor:"system",source:"transcript",boxId:g?.box??null,provider:T,payload:{title:"New Claude Code message shape hidden",body:`${T||"The CLI"}${v?` ${v}`:""} wrote a harness turn Bostrat had not seen before \u2014 ${F} \u2014 into ${h.name||h.id}. It was hidden from chat and recorded; run bostrat-audit --harness to review, and add the tag to HARNESS_TAGS once it is understood.`,urgency:"normal",trackName:h.name||null,ts:b}})}catch(c){n.warn?.(`[harness-shapes] notify.raised append failed (${h.id}): ${c?.message||c}`)}}n.log?.(`[harness-shapes] new shape ${x}${k.known?"":" (NOT in HARNESS_TAGS \u2014 paged)"} on ${h.id}${v?` \xB7 ${T} ${v}`:""}`)}return await i(),{first:D,paged:O,record:k}}async function m(){let h=await l();return Object.values(h.shapes).sort((g,S)=>S.lastSeen-g.lastSeen)}return{observe:d,list:m,flush:()=>u,reset(){r=null,a=null}}}var We=null;function Co(){return We||(We=Mo()),We}var qt=()=>Co().list();var Wt=e=>Number.isFinite(e)?new Date(e).toISOString().slice(0,16).replace("T"," "):"?";function Kt(e,{knownTags:t=[]}={}){let n=[],o=Array.isArray(e)?e:[],s=o.filter(r=>!r.known);n.push(`HARNESS SHAPES \xB7 ${o.length} shape(s) seen on this node \xB7 ${s.length} not in HARNESS_TAGS`),n.push("A harness-made user turn (Claude Code's own isMeta / tag-block turns) is hidden from chat and counted here by shape; a shape outside the table paged once when first seen."),o.length||n.push("(none yet \u2014 the registry fills as Tracks ingest harness-made turns)");for(let r of o){let a=r.versions?.length?` \xB7 ${Object.keys(r.providers||{}).join("/")||"cli"} ${r.versions.join(", ")}`:"";n.push(""),n.push(`${r.key} [${r.known?"known":"NEW"}] \xB7 ${r.count}\xD7 \xB7 ${r.tracks?.length||0} Track(s) \xB7 first ${Wt(r.firstSeen)} \xB7 last ${Wt(r.lastSeen)}${a}${r.paged?" \xB7 paged":""}`),r.head&&n.push(` ${r.head}`)}return t.length&&(n.push(""),n.push(`table (chat-notes.js HARNESS_TAGS): ${t.join(", ")}`)),n.join(`
10
+ `)}var Lo=["Primary Request and Intent","Key Technical Concepts","Files and Code Sections","Errors and Fixes","Problem Solving","All user messages","Pending Tasks","Current Work","Optional Next Step"],As=new RegExp(String.raw`^[ \t]*#{0,4}[ \t]*(?:\d+[.)][ \t]*)?\*{0,2}(${Lo.join("|")})[:*\t ]*$`,"gim");var Os=(()=>{let e=Number(process.env.BOSTRAT_CODEX_SUBMIT_SETTLE_MS??120);return Number.isFinite(e)&&e>=0?e:120})(),Rs=(()=>{let e=Number(process.env.BOSTRAT_CLAUDE_SUBMIT_SETTLE_MS??120);return Number.isFinite(e)&&e>=0?e:120})();var vs=(()=>{let e=Number(process.env.BOSTRAT_CODEX_PASTE_MIN_BYTES??512);return Number.isFinite(e)&&e>=0?e:512})();var ge=Object.freeze(["system-reminder","tools-used-before-summary","task-notification","command-name","command-message","command-args","local-command-stdout","local-command-stderr","local-command-caveat","user-prompt-submit-hook","ide_selection","ide_opened_file","ide_diagnostics"]),Bs=new Set(ge);var be=process.env.BOSTRAT_STATE_DIR||K.join(process.env.HOME||Ho.tmpdir(),".bostrat"),R=process.argv.slice(2),we=e=>{let t=R.indexOf(e);return t>=0?R[t+1]:null};(R.includes("--help")||R.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: ${z.join(", ")}`),console.log(" bostrat-audit --harness [--json] # the harness-made user-turn shapes this node has hidden from chat, by shape"),process.exit(0));if(R.includes("--harness")){let e=await qt();console.log(R.includes("--json")?JSON.stringify({shapes:e,knownTags:ge},null,2):Kt(e,{knownTags:ge})),process.exit(0)}var Xe=[];try{Xe=JSON.parse(await ye.readFile(K.join(be,"tracks.json"),"utf8")).tracks||[]}catch{}var Bo=new Map(Xe.map(e=>[e.id,e.name])),Ve=new Set([K.join(be,"events")]);for(let e of Xe)e.cwd&&Ve.add(K.join(e.cwd,".bostrat","events"));try{for(let e of await ye.readdir(K.join(be,"workspaces")))Ve.add(K.join(be,"workspaces",e,".bostrat","events"))}catch{}var Ke=we("--track"),ze=[];for(let e of Ve){let t=[];try{t=(await ye.readdir(e)).filter(n=>n.endsWith(".ndjson"))}catch{continue}for(let n of t){let o=n.slice(0,-7),s=Bo.get(o)||null;if(Ke&&o!==Ke&&!(s||"").toLowerCase().includes(Ke.toLowerCase()))continue;let r=[];for(let a of(await ye.readFile(K.join(e,n),"utf8")).split(`
11
+ `))if(a.trim())try{r.push(JSON.parse(fe(a)?he(a):a))}catch{}r.length&&ze.push({trackId:o,name:s,events:r})}}var Gt=R.includes("--all")?0:Number(we("--days"))||14;if(R.includes("--detectors")){let e=R.flatMap((o,s)=>o==="--rule"&&R[s+1]?[R[s+1]]:[]),t=e.filter(o=>!z.includes(o));t.length&&(console.error(`unknown rule(s): ${t.join(", ")} \u2014 known: ${z.join(", ")}`),process.exit(1));let n=vt(ze,{days:Gt,rules:e.length?e:null});console.log(R.includes("--json")?JSON.stringify(n,null,2):Nt(n,{samples:Number(we("--limit"))||5})),process.exit(n.ok?0:2)}var ne=ot(ze,{days:Gt}),Ge=await ht().catch(()=>null);Ge&&(ne.containment={...Ge,sentence:mt(Ge)});console.log(R.includes("--json")?JSON.stringify(ne,null,2):st(ne,{limit:Number(we("--limit"))||20,containment:ne.containment?.sentence}));process.exit(ne.ok?0:2);