bostrat-node 1.16.5 → 1.16.7

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