bostrat-node 1.17.2 → 1.17.3

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
@@ -3,7 +3,7 @@ import ye from"node:fs/promises";import Ho from"node:os";import K from"node:path
3
3
  `)}import X from"node:fs";import at from"node:fs/promises";import re from"node:os";import A from"node:path";import{execFile as ct}from"node:child_process";import{promisify as _n}from"node:util";var Ne=_n(ct),rt="BOSTRAT_BOX_USER",xn="bostrat-box",lt=Object.freeze(["root","sudo","wheel","admin","docker","lxd","libvirt","disk"]);var Tn=/^[a-z_][a-z0-9_-]{0,31}$/,An=new Set(["","off","0","false","no","none"]),ut=e=>e.BOSTRAT_STATE_DIR||A.join(e.HOME||re.homedir(),".bostrat");function dt(e){try{return X.readFileSync(e,"utf8").split(`
4
4
  `).filter(t=>t&&!t.startsWith("#")).map(t=>t.split(":"))}catch{return[]}}function pt(e,t=process.env){let o=dt(t.BOSTRAT_PASSWD_FILE||"/etc/passwd").find(s=>s[0]===String(e)||s[2]===String(e));return o?{name:o[0],uid:Number(o[2]),gid:Number(o[3]),home:o[5]||null,shell:o[6]||null}:null}function ft(e,t=process.env){let n=dt(t.BOSTRAT_GROUP_FILE||"/etc/group"),o=new Set;for(let s of n)Number(s[2])===e.gid&&o.add(s[0]),(s[3]||"").split(",").includes(e.name)&&o.add(s[0]);return[...o].sort()}var se=()=>typeof process.getuid=="function"?process.getuid():0,Oe=null;function ie(e=process.env){let t=String(e[rt]||"").trim();if(An.has(t.toLowerCase()))return null;let n=`${t}|${e.BOSTRAT_PASSWD_FILE||""}|${e.BOSTRAT_GROUP_FILE||""}|${e.BOSTRAT_BOX_HOME_VIEW||""}`;if(Oe?.key===n)return Oe.value;let o;if(!Tn.test(t))o={name:t,error:`${rt}="${t}" is not a valid user name`};else{let s=pt(t,e),r=se();if(!s)o={name:t,error:`user "${t}" does not exist \u2014 run scripts/pi/box-user-setup.sh (or the image's useradd)`};else if(s.uid===0)o={name:t,error:`user "${t}" is root`};else if(s.uid===r)o={name:t,error:`user "${t}" is the node's own uid`};else if(!s.home||s.home==="/"||s.home==="/nonexistent")o={name:t,error:`user "${t}" has no home directory`};else{let a=ft(s,e),u=a.filter(l=>lt.includes(l));o=u.length?{name:t,error:`user "${t}" is in ${u.join(", ")} \u2014 a box user must hold no route to root`}:{...s,groups:a,nodeUid:r,rootNode:r===0}}}return Oe={key:n,value:o},o}function In(e=process.env){let t=ie(e);return t&&!t.error?t.home:re.homedir()}function it(e=process.env){let t=ie(e);return!t||t.error||t.rootNode?In(e):e.BOSTRAT_BOX_HOME_VIEW||A.join(ut(e),"box-home")}function On(e,t=process.env){let n=ie(t);return!n||n.error?e:n.rootNode?["setpriv",`--reuid=${n.uid}`,`--regid=${n.gid}`,"--init-groups","--","env",`HOME=${n.home}`,`USER=${n.name}`,`LOGNAME=${n.name}`,...e]:["sudo","-n","-H","-u",n.name,"--",...e]}async function Re(e,{env:t=process.env,input:n=null,timeout:o=15e3}={}){let[s,...r]=On(e,t);return n==null?Ne(s,r,{timeout:o}):new Promise((a,u)=>{ct(s,r,{timeout:o},(i,d,m)=>i?u(i):a({stdout:d,stderr:m})).stdin.end(n)})}var ve;function Rn(e){return e.BOSTRAT_SETFACL_BIN?e.BOSTRAT_SETFACL_BIN:(ve===void 0&&(ve=["/usr/bin/setfacl","/bin/setfacl"].find(t=>X.existsSync(t))||null),ve)}function vn(e=process.env){let t=re.homedir(),n=ut(e);return[A.join(t,".ssh"),A.join(t,".claude.json"),A.join(t,".claude",".credentials.json"),A.join(t,".codex","auth.json"),A.join(t,".config","gh","hosts.yml"),A.join(t,".cursor","cli-config.json"),A.join(n,"node.env"),A.join(n,"api-token"),A.join(n,"plane-link"),A.join(n,"secure-inputs")]}async function ht({env:e=process.env,probe:t=!0}={}){let n=ie(e),o=await Dn(e);if(!n){let r=pt(se(),e)||{name:re.userInfo().username,uid:se(),gid:-1},a=r.uid===0?["root"]:ft(r,e).filter(i=>lt.includes(i)),u=r.uid!==0&&t?await jn():!1,l=[...a,...u&&!a.includes("sudo")?["sudo (sudoers)"]:[]];return{level:l.length?"root-capable":"node-uid",user:r.name,routes:l,problems:[],auditd:o}}if(n.error)return{level:"misconfigured",user:n.name,error:n.error,problems:[n.error],auditd:o};let s=[];if(t){try{let{stdout:l}=await Re(["id","-u"],{env:e,timeout:5e3});Number(l.trim())!==n.uid&&s.push(`switching to ${n.name} landed as uid ${l.trim()}`)}catch(l){s.push(`the node cannot switch to ${n.name} (${n.rootNode?"setpriv":"sudo -n -u"} failed: ${Nn(l)})`)}if(!s.length){await Re(["sudo","-n","true"],{env:e,timeout:5e3}).then(()=>!0,()=>!1)&&s.push(`${n.name} can sudo`);let l=[];for(let i of vn(e))X.existsSync(i)&&await Re(["test","-r",i],{env:e,timeout:5e3}).then(()=>!0,()=>!1)&&l.push(i);l.length&&s.push(`${n.name} can read ${l.join(", ")}`)}Rn(e)||s.push("setfacl is missing (apt install acl)");let r=it(e);r!==n.home&&!X.existsSync(A.join(r,".claude"))&&s.push(`the read-only mirror of ${n.home} is not mounted at ${r} \u2014 the node cannot read box transcripts`);let a=A.join(n.home,".claude","settings.json"),u=await at.stat(a).catch(()=>null);u&&u.uid===n.uid&&s.push(`${a} is owned by ${n.name} \u2014 the box can rewrite its own hooks`)}return{level:"uid",user:n.name,uid:n.uid,home:n.home,view:it(e),problems:s,auditd:o}}var Nn=e=>String(e?.stderr||e?.message||e).trim().split(`
5
5
  `)[0].slice(0,160);async function jn(){try{return await Ne("sudo",["-n","true"],{timeout:3e3}),!0}catch{return!1}}async function Dn(e=process.env,{ask:t=!0}={}){let n=e.BOSTRAT_AUDIT_LOG||"/var/log/audit/audit.log",o=!1;try{await at.access(n,X.constants.R_OK),o=!0}catch{}let s=e.BOSTRAT_AUDIT_RULES_FILE||"/etc/audit/rules.d/bostrat-box.rules",r=X.existsSync(s),a=null;if(t&&r){let u=se()===0?["auditctl",["-l"]]:["sudo",["-n","auditctl","-l"]];try{let{stdout:l}=await Ne(u[0],u[1],{timeout:5e3});a=l.includes(`key=${xn}`)}catch{a=null}}else r||(a=!1);return{log:n,readable:o,configured:r,rule:a,rulesFile:s}}function mt(e){return e.level==="uid"&&!e.problems.length?`Boxes on this node run as ${e.user}, which holds no route to root and cannot write the event log or its hook settings${e.auditd?.rule===!0&&e.auditd?.readable?"; its every exec is logged by auditd and shipped to the plane":""}.`:e.level==="uid"?`Boxes on this node run as ${e.user}, but containment has gaps (${e.problems.join("; ")}) \u2014 treat this record as evidence, not proof.`:e.level==="root-capable"?`Boxes on this node are root-capable (${e.user}: ${e.routes.join(", ")}), so a root-capable agent can defeat node-side evidence \u2014 this is evidence, not proof.`:e.level==="misconfigured"?`Box containment is configured but unusable (${e.error}); no box can start until it is fixed.`:`Boxes on this node share the node's uid (${e.user}), so an agent can rewrite its own log \u2014 this is evidence, not proof.`}var Pn="BP-AU-R4",xt=160,gt={high:0,medium:1,low:2},yt=200,bt=5,wt=8,St=5,kt=10*6e4,Mn=Object.freeze(["localhost","127.0.0.1","0.0.0.0","github.com","api.github.com","raw.githubusercontent.com","objects.githubusercontent.com","registry.npmjs.org","pypi.org","files.pythonhosted.org"]),Cn=5e3,Pe=new Set(["tool.called","tool.failed"]),je=new Set(["Write","Edit","NotebookEdit"]),Ln=e=>String(e??"").replace(/\s+/g," ").trim(),L=(e,t=120)=>Ln(e).slice(0,t);function Un(e,t=xt){let n=String(e??""),o=n.split(/\s*(?:;|&&|\|\||\||\n)\s*/).map(s=>s.trim()).filter(Boolean);return Number.isFinite(t)&&n.length>=t&&o.length&&o.pop(),o}function ae(e){return String(e??"").replace(/\d?>>?\s*\S+|<\s*\S+|2>&1/g," ").trim().split(/\s+/).filter(Boolean)}function Tt(e){let t=0;for(;t<e.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[t]);)t++;return{cmd:e[t]??null,rest:e.slice(t+1),at:t}}function Et(e){let t=ae(e),n=t.findIndex(i=>i==="git"||i.endsWith("/git"));if(n<0)return null;for(n++;n<t.length&&t[n].startsWith("-");)(t[n]==="-C"||t[n]==="-c")&&n++,n++;if(t[n]!=="push")return null;let o=[],s=[];for(let i=n+1;i<t.length;i++){let d=t[i];d.startsWith("-")?(o.push(d),(d==="-o"||d==="--push-option"||d==="--repo"||d==="--receive-pack"||d==="--exec")&&i++):s.push(d)}let r=o.some(i=>i==="--force"||/^-[a-zA-Z]+$/.test(i)&&i.includes("f"))||s.some(i=>i.startsWith("+")),a=o.some(i=>i.startsWith("--force-with-lease")||i.startsWith("--force-if-includes")),u=s[0]??null,l=s.slice(1).map(i=>i.replace(/^["']|["']$/g,"").replace(/^\+/,"")).map(i=>i.includes(":")?i.slice(i.indexOf(":")+1):i).filter(i=>i&&!i.startsWith("$"));return{force:r,lease:a,remote:u,dsts:l}}var Me=String.raw`(?:~|\$HOME|\$\{HOME\}|/home/[^\s/"']+|/root|/Users/[^\s/"']+)`,Hn=new RegExp(`${Me}/\\.ssh(?:/|\\b)`),Bn=new RegExp(`${Me}/(?:\\.claude\\.json\\b|\\.claude/\\.credentials\\.json|\\.codex/auth\\.json|\\.cursor(?:/|\\b))`),Fn=/(?:^|[\s/"'=(])(\.env(?:\.[A-Za-z0-9_.-]+)?)(?=$|[\s"'|;&)])/g,Wn=/^\.env\.(?:example|sample|template|dist)$/,At=/(\.claude\/settings(?:\.local)?\.json|\.claude\/hooks\/[^\s"']*|\.bostrat\/events(?:\/[^\s"']*)?)/,It=new RegExp(`((?:/etc|/usr/lib|/lib|/run)/systemd/[^\\s"']*|${Me}/\\.config/systemd/[^\\s"']*|/etc/cron(?:tab|\\.d|\\.hourly|\\.daily|\\.weekly|\\.monthly)(?:/[^\\s"']*)?|/var/spool/cron(?:/[^\\s"']*)?)`),qn=/^(?:enable|disable|start|stop|restart|try-restart|reload|reload-or-restart|daemon-reload|daemon-reexec|link|mask|unmask|edit|preset|preset-all|set-property|revert|isolate|kill|reset-failed|import-environment|set-environment|add-wants|add-requires)$/,Kn=/^\/tmp\/|\/\.bostrat\/tmp\//,Gn=/^(?:refs\/heads\/)?(?:main|master|develop|development|trunk|production|prod|staging|release(?:\/|$)|v\d)/,Xn=/(?:^|\/)track\/|^HEAD$|^refs\/bostrat\//,Vn=/https?:\/\/([a-z0-9.-]+\.[a-z]{2,}|localhost|\d+\.\d+\.\d+\.\d+)(?::\d+)?/gi,$t=e=>Hn.test(e)||Bn.test(e),_t=e=>[...String(e??"").matchAll(Fn)].some(t=>!Wn.test(t[1])),zn=e=>At.test(e),Yn=e=>It.test(e),Jn=e=>(e.startsWith("/")||e.startsWith("~"))&&!Kn.test(e);function Ot(e){let{cmd:t,at:n}=Tt(e);if(t==="sudo"){for(n++;n<e.length&&e[n].startsWith("-");)n++;t=e[n]??null}return{cmd:t,at:n}}function Rt(e,t){let n=String(e??"").match(t);if(!n)return null;let o=n[1],s=o.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&");if(new RegExp(`>{1,2}\\s*["']?[^\\s"']*${s}`).test(e))return"redirect";let r=ae(e),{cmd:a}=Ot(r);return!a||!r.some(u=>u.includes(o))?null:/^(?:rm|mv|truncate|chmod|chown|tee|install|shred|unlink|ln|mkdir|touch)$/.test(a)?a:a==="sed"&&r.some(u=>/^-[a-zA-Z]*i/.test(u))?"sed -i":a==="cp"&&r[r.length-1].includes(o)?"cp":/^(?:python3?|perl|node|ruby)$/.test(a)&&/open\([^)]*['"][wa]|writeFile|write_text|appendFile|fs\.write/.test(e)?`${a} write`:null}var Zn=e=>Rt(e,At);function Qn(e){let t=ae(e),{cmd:n,at:o}=Ot(t);if(!n)return null;let s=t.slice(o+1);if(n==="crontab"||n.endsWith("/crontab")){let a=!1,u=!1;for(let l=0;l<s.length;l++){if(s[l]==="-u"){l++;continue}s[l]==="-l"||/^-(?:h|V|T|-help|-version)$/.test(s[l])?a=!0:u=!0}return u||!a?"crontab":null}if(n==="systemctl"||n.endsWith("/systemctl")){let a=s.find(u=>!u.startsWith("-"));return a&&qn.test(a)?`systemctl ${a}`:null}if((n==="loginctl"||n.endsWith("/loginctl"))&&s.includes("enable-linger"))return"loginctl enable-linger";if(n==="at"&&s.length&&/^(?:now|midnight|noon|teatime|today|tomorrow|next|\d|-[fqmvt])/.test(s[0]))return"at";let r=Rt(e,It);return r?`${r} unit/cron path`:null}function eo(e){let t=new Set;for(let n of String(e??"").matchAll(Vn))t.add(n[1].toLowerCase());return[...t]}function to({knownHosts:e=[]}={}){return{known:new Set([...Mn,...[...e].map(t=>String(t).toLowerCase()).filter(Boolean)]),hosts:new Set,tracks:new Map}}function no(e,t){let n=e.tracks.get(t??"");return n||e.tracks.set(t??"",n={costs:[],peer:new Map}),n}var I=(e,t,n,o)=>Object.freeze({severity:e,requirement:Pn,note:t,measured:n,detect:o}),Q=(e,t)=>{let n=0,o=null;for(let s of e.calls)if(s.head)for(let r of Un(s.head,e.headCap)){let a=t(r,s);a&&(n++,o??=L(a))}return n?{count:n,sample:o}:null},De=(e,t)=>{let n=0,o=null;for(let s of e.calls){let r=t(s);r&&(n++,o??=L(r))}return n?{count:n,sample:o}:null},V=Object.freeze({"force-push":I("high","git push --force / -f / +refspec in a command head (--force-with-lease, the Track's own rebase flow, is not one)","2026-10-21 fleet replay \xB7 0 hits / 98,690 hook calls \xB7 1,080 logs 2026-08\u219210 \xB7 58 --force-with-lease pushes excluded by design \u2192 high",(e,t)=>Q(t,n=>{let o=Et(n);return o&&o.force&&!o.lease?n:null})),"protected-config-write":I("high","a write to the box's own harness: .claude/settings*.json, a .claude/hooks/ script or the Track's .bostrat/events/ log \u2014 by a file tool, a redirect, rm/mv/tee/sed -i, or a scripted open-for-write (reads are not hits)","2026-10-21 fleet replay \xB7 0 hits / 98,690 hook calls \xB7 165 reads of those paths (cat, grep, python json.loads) excluded by design \u2192 high",(e,t)=>{let n=0,o=null;for(let r of t.calls)je.has(r.tool)&&r.path&&zn(r.path)&&(n++,o??=L(`${r.tool} ${r.path}`));let s=Q(t,r=>{let a=Zn(r);return a?`${a}: ${r}`:null});return s&&(n+=s.count,o??=s.sample),n?{count:n,sample:o}:null}),"persistence-install":I("medium","a shell segment that installs something the OS runs on its own \u2014 crontab (install / edit / remove; -l is a read), a mutating systemctl verb (enable / start / restart / daemon-reload \u2026; status / show / cat / list / is-* are reads), loginctl enable-linger, at / batch \u2014 or a write (file tool, redirect, cp / mv / tee / ln / sed -i) into a systemd unit or cron directory: how a process outlives its turn by the OS's hand (BP-AU-D6's other half)","2026-10-21 fleet replay \xB7 11 hits / 99,122 hook calls \xB7 10 Tracks \xB7 0 in the last 14 d \xB7 every hit operator-asked service work on the operator's own Pi (systemctl --user restart/stop/start of bostrat-node, tmp-sweep, a samba disable, one `crontab -` install for a backfill) \xB7 the bare `at` word a quoted `|` regex leaves in a segment (4 hits) excluded by design \u2192 medium (rail), the guard's deny when opted in",(e,t)=>{let n=0,o=null;for(let r of t.calls)je.has(r.tool)&&r.path&&Yn(r.path)&&(n++,o??=L(`${r.tool} ${r.path}`));let s=Q(t,r=>{let a=Qn(r);return a?`${a}: ${r}`:null});return s&&(n+=s.count,o??=s.sample),n?{count:n,sample:o}:null}),"push-outside-track":I("medium","git push to a protected branch (main/master/develop/release\u2026), to a branch that is not a Track branch, or to a remote other than origin/upstream \u2014 a Track's own code leaves on its track/ branch or the WIP shadow ref","2026-10-21 fleet replay \xB7 7 hits / 98,690 hook calls \xB7 4 Tracks \xB7 0 in the last 14 d \xB7 every hit operator-instructed work on another repo (two dep/ branches, a fork's multiplayer branch, one HEAD:main) \u2192 medium, not a page",(e,t)=>Q(t,n=>{let o=Et(n);return o&&(o.remote&&!/^(?:origin|upstream)$/.test(o.remote)&&!o.remote.startsWith("$")&&!o.remote.startsWith("-")||o.dsts.some(s=>Gn.test(s)||!Xn.test(s)))?n:null})),"credential-read":I("medium","a command head or file path naming SSH material (~/.ssh) or a vendor auth file (~/.claude.json, ~/.claude/.credentials.json, ~/.codex/auth.json, ~/.cursor) \u2014 the box-auth policy's denylist shapes; ~/.claude/projects (transcripts) is not one","2026-10-21 fleet replay \xB7 12 hits / 98,690 hook calls \xB7 8 Tracks \xB7 3 in the last 14 d \xB7 every hit an operator-asked inspection on the operator's own node (ssh config for a host alias, stat/keys of ~/.claude.json) \u2192 medium until a 14-day window reads 0",(e,t)=>De(t,n=>n.head&&$t(n.head)?n.head:n.path&&$t(n.path)?`${n.tool} ${n.path}`:null)),"dotenv-read":I("low","a command head or file path naming a .env file (.env, .env.local, .env.production \u2026; the committed .env.example / .sample / .template are not ones)","2026-10-21 fleet replay \xB7 309 hits / 98,690 hook calls \xB7 44 Tracks \xB7 0 in the last 14 d \xB7 all of them an instructed `source \u2026/almanac/.env` on the operator's other repos \u2192 low (report only)",(e,t)=>De(t,n=>n.head&&_t(n.head)?n.head:n.path&&_t(n.path)?`${n.tool} ${n.path}`:null)),"privileged-command":I("medium","a shell segment whose command is sudo or docker (after any VAR=value prefix) \u2014 host-level reach from inside a box","2026-10-21 fleet replay \xB7 220 hits (183 events) / 98,690 hook calls \xB7 57 Tracks \xB7 3 in the last 14 d \xB7 sudo = the operator's own journalctl/systemctl asks on the Pi, docker = instructed compose/psql work on the operator's other services \u2192 medium (a hosted node's first hit is the number to watch)",(e,t)=>Q(t,n=>{let{cmd:o}=Tt(ae(n));return o==="sudo"||o==="docker"?n:null})),"write-outside-workspace":I("low","a file tool (Write / Edit / NotebookEdit) on an absolute path \u2014 the hook strips the box's workspace prefix, so an absolute path is outside it \u2014 that is not the box's scratch dir (/tmp/\u2026, \u2026/.bostrat/tmp/\u2026)","2026-10-21 fleet replay \xB7 106 hits / 98,690 hook calls \xB7 10 Tracks \xB7 44 in the last 14 d \xB7 the operator's other repos and Agent-tool worktrees under .bostrat/repos on the operator's own node \u2192 low (report only)",(e,t)=>De(t,n=>je.has(n.tool)&&n.path&&Jn(n.path)?`${n.tool} ${n.path}`:null)),"egress-new-host":I("low","a command head reaching, by URL, a host no box in the fleet has reached before (this projection's lifetime, seeded from the warm tails; KNOWN_HOSTS + PLANE_AUDIT_KNOWN_HOSTS never count) \u2014 a baseline-growth signal, so each host is reported once","2026-10-21 fleet replay \xB7 140 first sightings / 98,690 hook calls \xB7 69 Tracks \xB7 8 in the last 14 d \xB7 198 if the baseline were per Track \xB7 every host a vendor API, a docs site or the operator's own services \u2192 low (report only)",(e,t)=>{let n=0,o=null;for(let s of t.calls)if(s.head)for(let r of eo(s.head))t.state.known.has(r)||t.state.hosts.has(r)||(t.state.hosts.add(r),t.state.hosts.size>Cn&&t.state.hosts.delete(t.state.hosts.values().next().value),n++,o??=L(`${r} \xB7 ${s.head}`));return n?{count:n,sample:o}:null}),"spend-spike":I("low",`a cost.recorded turn over ${wt}\xD7 the Track's running median (its last ${yt} cost events, at least ${bt} of them) and over $${St} \u2014 a turn that cost far more than this Track's turns do`,"2026-10-21 fleet replay \xB7 114 hits / 8,421 cost events \xB7 64 Tracks \xB7 2 in the last 14 d \xB7 every hit a long build turn after short prompts (a $25\u201378 turn on a $0.37 median) \u2014 real spend, no one's attack \u2192 low (report only)",(e,t)=>{if(e.type!=="cost.recorded")return null;let n=t.track.costs,o=Number(e.payload?.usd);if(!Number.isFinite(o)||o<0)return null;let s=null;if(n.length>=bt&&o>=St){let r=[...n].sort((u,l)=>u-l),a=r[Math.floor(r.length/2)];o>wt*a&&(s={count:1,sample:`$${o.toFixed(2)} vs median $${a.toFixed(2)} over ${n.length} turns${e.payload?.model?` \xB7 ${e.payload.model}`:""}`})}return n.push(o),n.length>yt&&n.shift(),s}),"peer-injected-call":I("medium",`a tool call within ${kt/6e4} min of a peer.message on the same box with no operator or node-typed turn in between \u2014 the cross-session injection vector (peer-message.js); a peer is never a root (BP-AU-D1)`,"2026-10-21 fleet replay \xB7 0 peer.message events in 288,395 \xB7 the replay cannot bound this rule's rate, so it stays medium (rail) until a window with peer traffic has been measured; the shape itself is BP-AU-D1's stated R4 case",(e,t)=>{if(!t.calls.length)return null;let n=t.track.peer.get(t.boxKey);if(n==null||t.ts-n>kt||t.ts<n)return null;let o=t.calls[0];return{count:t.count,sample:L(`${Math.round((t.ts-n)/1e3)}s after a peer message \xB7 ${o.tool}${o.head?`: ${o.head}`:o.path?` ${o.path}`:""}`)}}),"foreign-session-call":I("medium","a hook-recorded tool call from a claude session that is not the box's own (payload.foreignSession, BP-AU-I12): a nested or stray CLI driving the box's hooks \u2014 R3 never roots it, this names it","2026-10-21 fleet replay \xB7 14 hits / 98,744 hook calls \xB7 3 Tracks \xB7 4 in the last 14 d \xB7 all the xscout loop's nested claude prompts, I12's own acceptance case \u2192 medium (rail), not a page",(e,t)=>{if(!t.calls.length||!e.payload?.foreignSession)return null;let n=t.calls[0];return{count:t.count,sample:L(`session ${String(e.payload.sessionId||"?").slice(0,8)} \xB7 ${n.tool}${n.head?`: ${n.head}`:n.path?` ${n.path}`:""}`)}}),"orphan-process":I("medium","a process the box left running: detached from the pane's tree (its cgroup or pty still lists it), alive at a turn's close and still alive minutes later with no turn open and no background job recorded \u2014 the node's own census (orphan-watch.js, BP-AU-D6), each process once","2026-10-27 fleet replay \xB7 0 audit.procs events in 304,814 (1,121 logs; the type is new, so the replay cannot bound this rule's rate) \xB7 live Pi census the same day: 10 boxes, 2 detached processes, both found by the cgroup census and neither by the pty one (a claude tool call runs on pipes) \u2014 one planted `nohup sleep &`, one real `flyctl agent run` that a lead's flyctl call had left behind 10 h earlier \u2192 medium (rail), never a page, until a window of live samples has been measured",e=>{if(e.type!=="audit.procs"||e.source!=="proc")return null;let t=e.payload||{},n=Array.isArray(t.orphans)?t.orphans:[],o=n.length+(Number(t.dropped)||0);if(!o)return null;let s=n[0]||{},r=Number.isFinite(s.sinceMs)?` \xB7 alive ${Math.max(1,Math.round(s.sinceMs/6e4))} min`:"";return{count:o,sample:L(`${s.comm||"process"}${s.cmd?`: ${s.cmd}`:""}${s.via?` [${s.via}]`:""}${r}${o>1?` (+${o-1} more)`:""}`)}}),"unknown-harness-shape":I("medium","a harness-made user turn of a shape chat-notes.js does not list (harness.shape.seen with known: false, harness-shapes.js): Claude Code wrote a new kind of its own turn into a transcript \u2014 hidden from chat by the generic catch, counted once per shape per node here; the node pages the operator once on first sight, this row is the fleet's record","2026-10-28 fleet replay \xB7 0 harness.shape.seen events in 311,055 (1,132 logs; the type is new, so the replay cannot bound this rule's rate) \xB7 transcript scan the same day: 2,863 claude user turns in 1,539 transcripts over 90 d, 144 of them harness-made (isMeta), 9 distinct shapes, 4 of which had rendered in chat as operator messages (<system-reminder><tools-used-before-summary> on 2 Tracks under 2.1.312, a usage-limit-reset notice, a safety-classifier notice) \u2192 medium (rail finding + security row), never a page from the plane: the once-per-shape page is the node's, so a release that adds one shape pages once, not per Track per hour",e=>{if(e.type!=="harness.shape.seen"||e.source!=="transcript")return null;let t=e.payload||{};if(t.known!==!1||!t.key)return null;let n=`${t.provider||"cli"}${t.cliVersion?` ${t.cliVersion}`:""}`;return{count:1,sample:L(`${t.key} \xB7 ${n}${t.head?` \xB7 ${t.head}`:""}`)}})}),z=Object.freeze(Object.keys(V)),oo=new Set([...Pe,"cost.recorded","peer.message","turn.user","audit.procs","harness.shape.seen"]);function so(e,t,{rules:n=null,headCap:o=xt}={}){if(!t||!oo.has(t.type)||t.source==="plane")return[];let s=no(e,t.trackId),r=t.payload||{},a=t.boxId??"",u=Number(t.ts)||0;if(t.type==="turn.user")return(t.actor==="user"||t.actor==="orchestrator")&&s.peer.delete(a),[];if(t.type==="peer.message")return s.peer.set(a,u),[];let l=Pe.has(t.type)&&t.source==="hook",d={calls:l?P(r):[],count:l?q(r):0,track:s,state:e,ts:u,boxKey:a,headCap:o},m=[];for(let h of n||z){let g=V[h];if(!g)continue;let S=null;try{S=g.detect(t,d)}catch{S=null}S&&S.count>0&&m.push({rule:h,count:S.count,sample:S.sample??null})}return m}function vt(e,{days:t=14,now:n=Date.now(),rules:o=null}={}){let s=t?n-t*864e5:0,r=to(),a=o||z,u={days:t||null,logs:0,events:0,calls:0,callsInWindow:0,rules:Object.fromEntries(a.map(i=>[i,{severity:V[i].severity,note:V[i].note,measured:V[i].measured,hits:0,hitsInWindow:0,events:0,tracks:0,tracksInWindow:0,perTenK:0,samples:[]}]))},l=Object.fromEntries(a.map(i=>[i,{all:new Set,win:new Set}]));for(let i of e||[]){let d=Array.isArray(i?.events)?[...i.events].sort((m,h)=>(Number(m.ts)||0)-(Number(h.ts)||0)):[];if(d.length){u.logs++;for(let m of d){u.events++;let h=(Number(m.ts)||0)>=s;if(Pe.has(m.type)&&m.source==="hook"){let g=q(m.payload||{});u.calls+=g,h&&(u.callsInWindow+=g)}for(let g of so(r,m,{rules:a})){let S=u.rules[g.rule];if(S.hits+=g.count,S.events++,l[g.rule].all.add(m.trackId??i.trackId),h&&(S.hitsInWindow+=g.count,l[g.rule].win.add(m.trackId??i.trackId)),g.sample){let j=S.samples.find(b=>b.text===g.sample);j?j.n++:S.samples.length<200&&S.samples.push({text:g.sample,n:1,ts:Number(m.ts)||0,trackId:m.trackId??i.trackId,name:i.name??null})}}}}}for(let i of a){let d=u.rules[i];d.tracks=l[i].all.size,d.tracksInWindow=l[i].win.size,d.perTenK=u.calls?Number((d.hits/u.calls*1e4).toFixed(2)):0,d.samples.sort((m,h)=>h.n-m.n||h.ts-m.ts),d.samples=d.samples.slice(0,50)}return u.ok=!a.some(i=>V[i].severity==="high"&&u.rules[i].hitsInWindow>0),u}var ro=e=>new Date(e).toISOString().slice(0,10);function Nt(e,{samples:t=5}={}){let n=[];n.push(`R4 DETECTOR REPLAY \xB7 ${e.days?`window last ${e.days}d`:"all history"} \xB7 ${e.logs} logs \xB7 ${e.events.toLocaleString()} events \xB7 ${e.calls.toLocaleString()} hook calls (${e.callsInWindow.toLocaleString()} in window)`),n.push("A rule's severity is what its measured rate supports; `high` pages (D7). Hits are what the plane fold would have flagged.");let o=Object.keys(e.rules).sort((s,r)=>gt[e.rules[s].severity]-gt[e.rules[r].severity]||s.localeCompare(r));for(let s of o){let r=e.rules[s];n.push(""),n.push(`${s} [${r.severity}] \xB7 ${r.hits} hit(s) all-time (${r.events} events, ${r.tracks} Tracks, ${r.perTenK}/10k calls) \xB7 ${r.hitsInWindow} in window (${r.tracksInWindow} Tracks)`),n.push(` ${r.note}`),r.measured&&n.push(` measured: ${r.measured}`);for(let a of r.samples.slice(0,t))n.push(` ${a.n}\xD7 ${ro(a.ts)} ${a.name?`${a.name} `:""}(${a.trackId}) ${a.text}`)}return n.push(""),n.push(e.ok?"ok: no high-severity detector hit in the window":"ATTENTION: a high-severity detector hit inside the window (exit 2)"),n.join(`
6
- `)}import Ft from"node:fs/promises";import Oo from"node:os";import qe from"node:path";import He from"node:fs/promises";import Y from"node:path";import mo from"node:os";import{EventEmitter as go}from"node:events";import{randomUUID as yo}from"node:crypto";import ce from"node:fs";import ue from"node:path";import io from"node:os";var ao=()=>process.env.BOSTRAT_STATE_DIR||ue.join(process.env.HOME||io.tmpdir(),".bostrat"),co="secure-inputs",Pt=()=>ue.join(ao(),co),lo=/^[A-Z][A-Z0-9_]{0,63}$/,uo=/^[A-Za-z0-9_-]{1,80}$/,po=16*1024;var Ce=8;function fo(e){return typeof e!="string"||!e?"a value is required":e.length<Ce?`a value must be at least ${Ce} characters`:Buffer.byteLength(e,"utf8")>po?"that value is too large (16 KiB max)":/[\0\r\n]/.test(e)?"a value must be one line":null}var Le=new Map,ee=[],jt=!1;function ho(){let e=[];for(let t of Le.values())for(let[n,{value:o}]of t){let s=`\u2039${n}\u203A`,r=new Set([o]);r.add(encodeURIComponent(o)),r.add(Buffer.from(o,"utf8").toString("base64")),r.add(Buffer.from(o,"utf8").toString("base64url")),r.add(JSON.stringify(o).slice(1,-1));for(let a of r)a&&a.length>=Ce&&e.push({needle:a,mark:s})}e.sort((t,n)=>n.needle.length-t.needle.length),ee=e}function Dt(e){return ue.join(Pt(),e)}function Mt(){if(jt)return;jt=!0,Le.clear();let e=[];try{e=ce.readdirSync(Pt(),{withFileTypes:!0})}catch{e=[]}for(let t of e){if(!t.isDirectory()||!uo.test(t.name))continue;let n=new Map,o=[];try{o=ce.readdirSync(Dt(t.name),{withFileTypes:!0})}catch{continue}for(let s of o)if(!(!s.isFile()||!lo.test(s.name)))try{let r=ue.join(Dt(t.name),s.name),a=ce.readFileSync(r,"utf8");if(fo(a))continue;n.set(s.name,{value:a,addedAt:ce.statSync(r).mtimeMs})}catch{}n.size&&Le.set(t.name,n)}ho()}function Ct(){return Mt(),ee.length>0}function Ue(e){if(typeof e!="string"||!e||(Mt(),!ee.length))return e;let t=e;for(let{needle:n,mark:o}of ee)t.includes(n)&&(t=t.split(n).join(o));return t}function le(e,t=new WeakSet){if(typeof e=="string")return Ue(e);if(!e||typeof e!="object"||!ee.length||t.has(e))return e;if(t.add(e),Array.isArray(e)){let s=!1,r=e.map(a=>{let u=le(a,t);return u!==a&&(s=!0),u});return s?r:e}if(Buffer.isBuffer(e)||e instanceof Date)return e;let n=!1,o={};for(let s of Object.keys(e)){let r=le(e[s],t);r!==e[s]&&(n=!0),o[s]=r}return n?o:e}var bo=new Set(["session.ready","session.foreign","turn.user","turn.agent","turn.retracted","peer.message","provider.error","delivery.queued","delivery.settled","turn.steered","turn.interrupted","turn.aborted","tool.started","tool.called","tool.failed","tool.result","prompt.raised","prompt.answered","prompt.dismissed","prompt.autoRejected","box.fullscreen.detected","box.fullscreen.answered","box.stuck.detected","box.stuck.answered","context.usage","context.refresh.offered","context.refresh.answered","handoff.offered","handoff.answered","automation.fired","refresh.flow.changed","cost.recorded","memory.seed","memory.harvested","handoff.artifact","code.pushed","code.committed","code.rework","rework.cause.offered","rework.cause.answered","rework.cause.retracted","handoff.started","handoff.step","handoff.done","handoff.failed","node.saturated","node.restarted","subtask.delegated","subtask.merged","job.started","job.stalled","job.stopped","pr.state.changed","pr.offered","pr.offer.answered","pr.exists.offered","pr.exists.answered","pr.update.reported","pr.train.boarded","pr.train.landed","pr.train.ejected","pr.train.rebuilt","box.state.changed","view.state.changed","view.spinup.failed","deps.prepare","deps.setup","secret.added","secret.renamed","secret.removed","secret.used","mock.state.changed","flow.state.changed","runbook.state.changed","ticket.linked","ticket.sync.failed","ticket.move.offered","ticket.move.answered","ticket.state.changed","ticket.commented","ticket.flow.changed","ticket.create.offered","ticket.create.answered","ticket.created","loop.create.offered","loop.create.answered","loop.created","loop.update.offered","loop.update.answered","loop.updated","loop.delete.offered","loop.delete.answered","loop.deleted","loop.paused","replay.spec.offered","replay.spec.answered","followup.armed","followup.armed.cancelled","followup.arm.saved","followup.offered","followup.answered","followup.create.offered","followup.create.answered","followup.created","planning.change.offered","planning.change.answered","planning.changed","notify.raised","usage.cap.hit","provider.limit.hit","usage.cap.warning","provider.login.started","provider.connected","track.summary.recorded","track.transferred","track.recovered","track.phase.changed","track.operation.changed","track.obligations.changed","track.interrupted.changed","track.circuit.tagged","blueprint.item.launched","blueprint.item.bound","decision.recorded","estimate.recorded","estimate.closed","changelog.published","track.conflict.predicted","track.conflict.cleared","audit.chain.broken","audit.chain.healed","audit.flagged","audit.exec","audit.procs","harness.shape.seen","stall.detected","error"]),wo=new Set(["user","agent","orchestrator","system","peer"]),So=new Set(["hook","otel","statusline","transcript","pane","orchestrator","vendor","cli","auditd","proc","plane"]),Be=new go;Be.setMaxListeners(0);var Fe=process.env.BOSTRAT_STATE_DIR||Y.join(process.env.HOME||mo.tmpdir(),".bostrat");function Lt(e){return e?.cwd?Y.join(e.cwd,".bostrat","events"):Y.join(Fe,"events")}var Ut=(e,t)=>Y.join(e,`${t}.ndjson`),te=new Map,pe=new Map,de=new Map;async function ko(e,t){if(te.has(t))return;let n=await xo(e,t),o=0,s=null;for(let r of n)r.seq>o&&(o=r.seq),Ee(r)&&(s=r);te.set(t,o),pe.set(t,s?oe(s):null)}function Eo(e,t){let o=(de.get(e)??Promise.resolve()).then(t,t),s=o.then(()=>{},()=>{});return de.set(e,s),s.then(()=>{de.get(e)===s&&de.delete(e)}),o}function $o(e,t){let n=Array.isArray(e?.epochs)?e.epochs:null;if(!(!n||n.length===0)){if(!Number.isFinite(t))return n.length-1;for(let o=n.length-1;o>=0;o--){let s=n[o].startedAt;if(s==null||s<=t)return o}return 0}}async function Ht(e,t){let n=typeof e=="string"?e:e?.id;if(!n)throw new Error("appendEvent: a track (or trackId) is required");if(!t||!bo.has(t.type))throw new Error(`appendEvent: unknown event type "${t?.type}"`);if(t.actor&&!wo.has(t.actor))throw new Error(`appendEvent: bad actor "${t.actor}"`);if(t.source&&!So.has(t.source))throw new Error(`appendEvent: bad source "${t.source}"`);let o=typeof e=="string"?Y.join(Fe,"events"):Lt(e),s=t.epoch;if(s==null&&typeof e=="object"&&t.boxId&&Array.isArray(e?.boxes)){let r=e.boxes.find(a=>a.name===t.boxId);s=$o(r,Number(t.payload?.ts??t.ts)||Date.now())}return Eo(n,async()=>{await ko(o,n);let r=te.get(n)+1;te.set(n,r);let a=pe.get(n)??null,u={id:t.id||yo(),trackId:n,boxId:t.boxId??null,...s!=null?{epoch:s}:{},seq:r,prev:a,ts:t.ts??Date.now(),type:t.type,actor:t.actor??"system",provider:t.provider??null,source:t.source??"orchestrator",payload:t.payload??{},...t.causationId?{causationId:t.causationId}:{},...t.correlationId?{correlationId:t.correlationId}:{}};if(Ct()){let d=le(u);d!==u&&Object.assign(u,d)}let l=JSON.stringify(u),i=u;fe(l)&&(l=he(l),i=JSON.parse(l)),pe.set(n,oe(i));try{await He.mkdir(o,{recursive:!0}),await He.appendFile(Ut(o,n),l+`
6
+ `)}import Ft from"node:fs/promises";import Oo from"node:os";import qe from"node:path";import He from"node:fs/promises";import Y from"node:path";import mo from"node:os";import{EventEmitter as go}from"node:events";import{randomUUID as yo}from"node:crypto";import ce from"node:fs";import ue from"node:path";import io from"node:os";var ao=()=>process.env.BOSTRAT_STATE_DIR||ue.join(process.env.HOME||io.tmpdir(),".bostrat"),co="secure-inputs",Pt=()=>ue.join(ao(),co),lo=/^[A-Z][A-Z0-9_]{0,63}$/,uo=/^[A-Za-z0-9_-]{1,80}$/,po=16*1024;var Ce=8;function fo(e){return typeof e!="string"||!e?"a value is required":e.length<Ce?`a value must be at least ${Ce} characters`:Buffer.byteLength(e,"utf8")>po?"that value is too large (16 KiB max)":/[\0\r\n]/.test(e)?"a value must be one line":null}var Le=new Map,ee=[],jt=!1;function ho(){let e=[];for(let t of Le.values())for(let[n,{value:o}]of t){let s=`\u2039${n}\u203A`,r=new Set([o]);r.add(encodeURIComponent(o)),r.add(Buffer.from(o,"utf8").toString("base64")),r.add(Buffer.from(o,"utf8").toString("base64url")),r.add(JSON.stringify(o).slice(1,-1));for(let a of r)a&&a.length>=Ce&&e.push({needle:a,mark:s})}e.sort((t,n)=>n.needle.length-t.needle.length),ee=e}function Dt(e){return ue.join(Pt(),e)}function Mt(){if(jt)return;jt=!0,Le.clear();let e=[];try{e=ce.readdirSync(Pt(),{withFileTypes:!0})}catch{e=[]}for(let t of e){if(!t.isDirectory()||!uo.test(t.name))continue;let n=new Map,o=[];try{o=ce.readdirSync(Dt(t.name),{withFileTypes:!0})}catch{continue}for(let s of o)if(!(!s.isFile()||!lo.test(s.name)))try{let r=ue.join(Dt(t.name),s.name),a=ce.readFileSync(r,"utf8");if(fo(a))continue;n.set(s.name,{value:a,addedAt:ce.statSync(r).mtimeMs})}catch{}n.size&&Le.set(t.name,n)}ho()}function Ct(){return Mt(),ee.length>0}function Ue(e){if(typeof e!="string"||!e||(Mt(),!ee.length))return e;let t=e;for(let{needle:n,mark:o}of ee)t.includes(n)&&(t=t.split(n).join(o));return t}function le(e,t=new WeakSet){if(typeof e=="string")return Ue(e);if(!e||typeof e!="object"||!ee.length||t.has(e))return e;if(t.add(e),Array.isArray(e)){let s=!1,r=e.map(a=>{let u=le(a,t);return u!==a&&(s=!0),u});return s?r:e}if(Buffer.isBuffer(e)||e instanceof Date)return e;let n=!1,o={};for(let s of Object.keys(e)){let r=le(e[s],t);r!==e[s]&&(n=!0),o[s]=r}return n?o:e}var bo=new Set(["session.ready","session.foreign","turn.user","turn.agent","turn.retracted","peer.message","provider.error","delivery.queued","delivery.settled","turn.steered","turn.interrupted","turn.aborted","tool.started","tool.called","tool.failed","tool.result","prompt.raised","prompt.answered","prompt.dismissed","prompt.autoRejected","box.fullscreen.detected","box.fullscreen.answered","box.stuck.detected","box.stuck.answered","context.usage","context.refresh.offered","context.refresh.answered","handoff.offered","handoff.answered","automation.fired","refresh.flow.changed","cost.recorded","memory.seed","memory.harvested","handoff.artifact","code.pushed","code.committed","code.rework","rework.cause.offered","rework.cause.answered","rework.cause.retracted","handoff.started","handoff.step","handoff.done","handoff.failed","node.saturated","node.restarted","subtask.delegated","subtask.merged","job.started","job.stalled","job.stopped","pr.state.changed","pr.offered","pr.offer.answered","pr.exists.offered","pr.exists.answered","pr.update.reported","pr.train.boarded","pr.train.landed","pr.train.ejected","pr.train.rebuilt","box.state.changed","view.state.changed","view.spinup.failed","deps.prepare","deps.setup","secret.added","secret.renamed","secret.removed","secret.used","mock.state.changed","flow.state.changed","runbook.state.changed","ticket.linked","ticket.sync.failed","ticket.move.offered","ticket.move.answered","ticket.state.changed","ticket.commented","ticket.flow.changed","ticket.create.offered","ticket.create.answered","ticket.created","loop.create.offered","loop.create.answered","loop.created","loop.update.offered","loop.update.answered","loop.updated","loop.delete.offered","loop.delete.answered","loop.deleted","loop.paused","replay.spec.offered","replay.spec.answered","replay.run.started","replay.run.nudged","replay.run.capped","replay.run.stopped","replay.run.checked","replay.run.finished","followup.armed","followup.armed.cancelled","followup.arm.saved","followup.offered","followup.answered","followup.create.offered","followup.create.answered","followup.created","planning.change.offered","planning.change.answered","planning.changed","notify.raised","usage.cap.hit","provider.limit.hit","usage.cap.warning","provider.login.started","provider.connected","track.summary.recorded","track.transferred","track.recovered","track.phase.changed","track.operation.changed","track.obligations.changed","track.interrupted.changed","track.circuit.tagged","blueprint.item.launched","blueprint.item.bound","decision.recorded","estimate.recorded","estimate.closed","changelog.published","track.conflict.predicted","track.conflict.cleared","audit.chain.broken","audit.chain.healed","audit.flagged","audit.exec","audit.procs","harness.shape.seen","stall.detected","error"]),wo=new Set(["user","agent","orchestrator","system","peer"]),So=new Set(["hook","otel","statusline","transcript","pane","orchestrator","vendor","cli","auditd","proc","plane"]),Be=new go;Be.setMaxListeners(0);var Fe=process.env.BOSTRAT_STATE_DIR||Y.join(process.env.HOME||mo.tmpdir(),".bostrat");function Lt(e){return e?.cwd?Y.join(e.cwd,".bostrat","events"):Y.join(Fe,"events")}var Ut=(e,t)=>Y.join(e,`${t}.ndjson`),te=new Map,pe=new Map,de=new Map;async function ko(e,t){if(te.has(t))return;let n=await xo(e,t),o=0,s=null;for(let r of n)r.seq>o&&(o=r.seq),Ee(r)&&(s=r);te.set(t,o),pe.set(t,s?oe(s):null)}function Eo(e,t){let o=(de.get(e)??Promise.resolve()).then(t,t),s=o.then(()=>{},()=>{});return de.set(e,s),s.then(()=>{de.get(e)===s&&de.delete(e)}),o}function $o(e,t){let n=Array.isArray(e?.epochs)?e.epochs:null;if(!(!n||n.length===0)){if(!Number.isFinite(t))return n.length-1;for(let o=n.length-1;o>=0;o--){let s=n[o].startedAt;if(s==null||s<=t)return o}return 0}}async function Ht(e,t){let n=typeof e=="string"?e:e?.id;if(!n)throw new Error("appendEvent: a track (or trackId) is required");if(!t||!bo.has(t.type))throw new Error(`appendEvent: unknown event type "${t?.type}"`);if(t.actor&&!wo.has(t.actor))throw new Error(`appendEvent: bad actor "${t.actor}"`);if(t.source&&!So.has(t.source))throw new Error(`appendEvent: bad source "${t.source}"`);let o=typeof e=="string"?Y.join(Fe,"events"):Lt(e),s=t.epoch;if(s==null&&typeof e=="object"&&t.boxId&&Array.isArray(e?.boxes)){let r=e.boxes.find(a=>a.name===t.boxId);s=$o(r,Number(t.payload?.ts??t.ts)||Date.now())}return Eo(n,async()=>{await ko(o,n);let r=te.get(n)+1;te.set(n,r);let a=pe.get(n)??null,u={id:t.id||yo(),trackId:n,boxId:t.boxId??null,...s!=null?{epoch:s}:{},seq:r,prev:a,ts:t.ts??Date.now(),type:t.type,actor:t.actor??"system",provider:t.provider??null,source:t.source??"orchestrator",payload:t.payload??{},...t.causationId?{causationId:t.causationId}:{},...t.correlationId?{correlationId:t.correlationId}:{}};if(Ct()){let d=le(u);d!==u&&Object.assign(u,d)}let l=JSON.stringify(u),i=u;fe(l)&&(l=he(l),i=JSON.parse(l)),pe.set(n,oe(i));try{await He.mkdir(o,{recursive:!0}),await He.appendFile(Ut(o,n),l+`
7
7
  `)}catch(d){throw te.set(n,r-1),pe.set(n,a),d}return Be.emit("event",i),Be.emit(`track:${n}`,i),i})}var _o=/(?<!\\)((?:\\\\)*)\\u0000/g,fe=e=>e.includes("\\u0000"),he=e=>e.replace(_o,"$1\\ufffd");async function xo(e,t){let n,o;typeof e=="string"&&t?(n=e,o=t):(o=typeof e=="string"?e:e?.id,n=typeof e=="string"?Y.join(Fe,"events"):Lt(e));let s;try{s=await He.readFile(Ut(n,o),"utf8")}catch{return[]}return To(s)}function To(e){let t=[];for(let n of e.split(`
8
8
  `))if(n.trim())try{t.push(JSON.parse(fe(n)?he(n):n))}catch{}return t}import me from"node:fs/promises";import Ao from"node:path";var Io=0;async function Bt(e,t,{mode:n}={}){await me.mkdir(Ao.dirname(e),{recursive:!0});let o=`${e}.${process.pid}.${++Io}.tmp`;try{await me.writeFile(o,JSON.stringify(t,null,2)+`
9
9
  `,n!=null?{mode:n}:void 0),await me.rename(o,e)}catch(s){throw await me.unlink(o).catch(()=>{}),s}}var Ro=()=>process.env.BOSTRAT_STATE_DIR||qe.join(process.env.HOME||Oo.tmpdir(),".bostrat"),vo="harness-shapes.json",No=12,jo=8,Do=80,Po=e=>Ue(String(e||"").replace(/\s+/g," ").trim().slice(0,Do));function Mo({file:e=null,deps:t={},log:n=console}={}){let o={appendEvent:Ht,now:()=>Date.now(),...t},s=()=>e||qe.join(Ro(),vo),r=null,a=null,u=Promise.resolve();async function l(){return r||(a||(a=Ft.readFile(s(),"utf8").then(h=>{let g=JSON.parse(h);return g&&typeof g.shapes=="object"&&g.shapes?{version:1,shapes:g.shapes}:{version:1,shapes:{}}}).catch(()=>({version:1,shapes:{}})).then(h=>r=h)),a)}function i(){let h=JSON.stringify(r);return u=u.then(async()=>{await Ft.mkdir(qe.dirname(s()),{recursive:!0}),await Bt(s(),JSON.parse(h))}).catch(g=>n.warn?.(`[harness-shapes] write failed: ${g?.message||g}`)),u}async function d(h,g,S){if(!S||S.kind!=="harness"||!S.key)return null;let j=await l(),b=o.now(),x=String(S.key).slice(0,200),T=g?.agent||null,v=typeof g?.cliVersion=="string"?g.cliVersion:null,k=j.shapes[x],D=!k;D&&(k=j.shapes[x]={key:x,tags:Array.isArray(S.tags)?S.tags.slice(0,20):[],known:!!S.known,head:Po(S.head||g?.text),firstSeen:b,lastSeen:b,count:0,tracks:[],providers:{},versions:[],paged:!1}),k.lastSeen=b,k.count++,S.known&&!k.known&&(k.known=!0),h?.id&&!k.tracks.includes(h.id)&&(k.tracks.push(h.id),k.tracks.length>No&&k.tracks.shift()),T&&(k.providers[T]=(k.providers[T]||0)+1),v&&!k.versions.includes(v)&&(k.versions.push(v),k.versions.length>jo&&k.versions.shift());let O=!1;if(D&&h?.id){try{await o.appendEvent(h,{type:"harness.shape.seen",actor:"system",source:"transcript",boxId:g?.box??null,provider:T,payload:{key:x,tags:k.tags,known:k.known,head:k.head,provider:T,cliVersion:v,box:g?.box??null,count:1,ts:b}})}catch(F){n.warn?.(`[harness-shapes] harness.shape.seen append failed (${h.id}): ${F?.message||F}`)}if(!k.known&&!k.paged){k.paged=!0,O=!0;let F=k.tags.length?`<${k.tags.join("> <")}>`:`"${k.head}"`;try{await o.appendEvent(h,{type:"notify.raised",actor:"system",source:"transcript",boxId:g?.box??null,provider:T,payload:{title:"New Claude Code message shape hidden",body:`${T||"The CLI"}${v?` ${v}`:""} wrote a harness turn Bostrat had not seen before \u2014 ${F} \u2014 into ${h.name||h.id}. It was hidden from chat and recorded; run bostrat-audit --harness to review, and add the tag to HARNESS_TAGS once it is understood.`,urgency:"normal",trackName:h.name||null,ts:b}})}catch(c){n.warn?.(`[harness-shapes] notify.raised append failed (${h.id}): ${c?.message||c}`)}}n.log?.(`[harness-shapes] new shape ${x}${k.known?"":" (NOT in HARNESS_TAGS \u2014 paged)"} on ${h.id}${v?` \xB7 ${T} ${v}`:""}`)}return await i(),{first:D,paged:O,record:k}}async function m(){let h=await l();return Object.values(h.shapes).sort((g,S)=>S.lastSeen-g.lastSeen)}return{observe:d,list:m,flush:()=>u,reset(){r=null,a=null}}}var We=null;function Co(){return We||(We=Mo()),We}var qt=()=>Co().list();var Wt=e=>Number.isFinite(e)?new Date(e).toISOString().slice(0,16).replace("T"," "):"?";function Kt(e,{knownTags:t=[]}={}){let n=[],o=Array.isArray(e)?e:[],s=o.filter(r=>!r.known);n.push(`HARNESS SHAPES \xB7 ${o.length} shape(s) seen on this node \xB7 ${s.length} not in HARNESS_TAGS`),n.push("A harness-made user turn (Claude Code's own isMeta / tag-block turns) is hidden from chat and counted here by shape; a shape outside the table paged once when first seen."),o.length||n.push("(none yet \u2014 the registry fills as Tracks ingest harness-made turns)");for(let r of o){let a=r.versions?.length?` \xB7 ${Object.keys(r.providers||{}).join("/")||"cli"} ${r.versions.join(", ")}`:"";n.push(""),n.push(`${r.key} [${r.known?"known":"NEW"}] \xB7 ${r.count}\xD7 \xB7 ${r.tracks?.length||0} Track(s) \xB7 first ${Wt(r.firstSeen)} \xB7 last ${Wt(r.lastSeen)}${a}${r.paged?" \xB7 paged":""}`),r.head&&n.push(` ${r.head}`)}return t.length&&(n.push(""),n.push(`table (chat-notes.js HARNESS_TAGS): ${t.join(", ")}`)),n.join(`
@@ -1,14 +1,17 @@
1
1
  #!/usr/bin/env node
2
- var k=process.env.BOSTRAT_AGENT_URL||`http://127.0.0.1:${process.env.BOSTRAT_AGENT_PORT||3362}`,p=["usage: bostrat-replay census [--rows] [--json] [--budget <ms>] [--once]"," bostrat-replay spec frame <source> [--json]",' bostrat-replay spec draft <source> (--statement "<text>" | --statement-file <path>) [--suite "<cmd>"] [--note "<why>"]',' bostrat-replay spec revise <spec> (--statement "<text>" | --statement-file <path>) [--suite "<cmd>"] [--note "<what changed>"]'," bostrat-replay spec ls [--status drafted|approved|dismissed] [--json]"," bostrat-replay spec show <spec> [--json]"].join(`
3
- `);function c(e){console.error(`[bostrat-replay] ${e}`),process.exit(1)}async function m(e,o,s){let t=await fetch(`${k}${o}`,{method:e,headers:s?{"content-type":"application/json"}:void 0,body:s?JSON.stringify(s):void 0}),n=await t.json().catch(()=>({}));if(!t.ok){let r=new Error(n.error||`HTTP ${t.status}`);throw r.status=t.status,r.data=n,r}return n}var $=e=>m("GET",e),j=new Set(["rows","json","once"]),O=new Set(["budget","statement","statement-file","suite","note","status"]);function w(e){let o={_:[]};for(let s=0;s<e.length;s++){let t=e[s];if(t.startsWith("--")){let n=t.slice(2);j.has(n)?o[n]=!0:O.has(n)?(s+1>=e.length&&c(`${t} needs a value
4
- ${p}`),o[n]=e[++s]):c(`unknown flag ${t}
5
- ${p}`)}else o._.push(t)}return o}var g=e=>{let o=Math.round((Number(e)||0)/6e4);return o>=60?`${(o/60).toFixed(1)}h`:`${o}m`},N=(e,o)=>o?`${Math.round(100*e/o)}%`:"\u2013",h=e=>String(e||"").slice(0,8)||"\u2013",R=e=>e?new Date(e).toISOString().slice(0,10):"\u2013",A=(e,o=96)=>{let s=String(e||"").replace(/\s+/g," ").trim();return s.length>o?`${s.slice(0,o-1)}\u2026`:s};async function E(e){let o=Number.isFinite(Number(e.budget))&&Number(e.budget)>0?Number(e.budget):8e3,s=e.rows?"1":"0",t;for(let a=0;a<120&&(t=await $(`/api/usage/replay-census?budgetMs=${o}&rows=${s}`),!(!t.partial||e.once));a++)process.stderr.write(`[bostrat-replay] census in progress \u2014 ${t.pending} still pending (${t.judged} judged)\r`);if(t||c("no answer from the agent"),e.json){console.log(JSON.stringify(t,null,2));return}let n=t.tracks,r=t.criteria,l=t.excluded;console.log(`[bostrat-replay] ${t.label}${t.partial?` \u2014 PARTIAL, ${t.pending} pending (run again)`:""}`),console.log(` eligible: ${t.eligible} of ${t.merged} merged archived Tracks (${N(t.eligible,t.merged)}) \u2014 ${n.archived} archived on this node, ${n.open} open, ${n.loops} loop runs excluded, ${n.unreadable} unreadable`),console.log(` funnel (each criterion counted on its own, over the ${t.judged} judged):`),console.log(` merged PR ${r.mergedPr}`),console.log(` recoverable base ${r.recoverableBase} (not: ${l.baseNotRecoverable}${Object.keys(t.baseReasons).length?" \u2014 "+Object.entries(t.baseReasons).map(([a,i])=>`${a} ${i}`).join(", "):""})`),console.log(` tests touched ${r.testsTouched} (not: ${l.noTestsTouched} of those with a base)`),console.log(` no ops/deploy step ${r.noOpsStep} (not: ${l.opsStep}${Object.keys(t.opsRules).length?" \u2014 "+Object.entries(t.opsRules).map(([a,i])=>`${a} ${i}`).join(", "):""})`),console.log(` not merged (archived without a merged PR): ${l.notMerged}`);let d=Object.entries(t.byRepo);if(d.length){console.log(" by repo:");for(let[a,i]of d)console.log(` ${a.padEnd(32)} merged ${String(i.merged).padStart(4)} eligible ${String(i.eligible).padStart(4)} (base ${i.baseNotRecoverable} \xB7 tests ${i.noTestsTouched} \xB7 ops ${i.opsStep})`)}let v=Object.entries(t.byCategory);v.length&&console.log(` eligible by category: ${v.map(([a,i])=>`${a} ${i}`).join(" \xB7 ")}`);let y=Object.entries(t.byModel);if(y.length&&console.log(` eligible by model: ${y.map(([a,i])=>`${a} ${i}`).join(" \xB7 ")}`),e.rows&&Array.isArray(t.rows)){console.log(` eligible Tracks (${t.rows.length}):`);for(let a of t.rows)console.log(` ${a.repo}#${a.pr} ${String(a.name||a.trackId).slice(0,48).padEnd(48)} ${a.category||"\u2013"} ${a.model||a.provider||"\u2013"} active ${g(a.activeMs)} tests ${a.tests}/${a.files} base ${h(a.base)} ${a.trackId}`)}console.log(` basis: ${t.basis.label}; ${t.basis.scope}`),console.log(` no ops/deploy step: ${t.basis.noOpsStep}`)}async function I(e){let o;for(let s=0;s<40&&(o=await $(`/api/replay/frame?source=${encodeURIComponent(e)}&budgetMs=15000`),!!o.partial);s++)process.stderr.write(`[bostrat-replay] reading the archived logs \u2014 ${o.pending} still pending\r`);return(!o||o.partial)&&c("the archived logs are still being read \u2014 run again"),o}function f(e,o=" "){console.log(`${o}source: ${e.repo}#${e.pr} \u2014 Track \u201C${e.trackName||e.trackId}\u201D (${e.trackId})`),console.log(`${o} merged ${R(e.mergedAt)} at ${h(e.mergeCommit)} \xB7 base ${h(e.base)} (the commit a sealed clone is cut at)`),console.log(`${o} ${e.category||"uncategorized"} \xB7 ${e.model||e.provider||"\u2013"} \xB7 agent-active ${g(e.activeMs)} \xB7 wall ${g(e.wallMs)} \xB7 ${e.prompts} operator prompt${e.prompts===1?"":"s"} \xB7 $${(Number(e.usd)||0).toFixed(2)} notional`)}async function x(e){let o=e._[0];o||c(`spec frame needs a <source>
6
- ${p}`);let s=await I(o);if(e.json){console.log(JSON.stringify(s,null,2));return}if(console.log(`[bostrat-replay] ${s.label||"replay task spec"} \u2014 frame for ${o}`),!s.eligible){console.log(` NOT replay-eligible: ${s.reasons.join(", ")}`),s.source&&f(s.source),console.log(" a spec cannot be drafted from this Track (R11: no acceptance tests, or an ops step a sealed clone cannot replay)");return}f(s.source),console.log(` acceptance: ${s.acceptance.tests.length} test path${s.acceptance.tests.length===1?"":"s"} the PR touched (of ${s.acceptance.files} files):`);for(let n of s.acceptance.tests)console.log(` ${n}`);let t=s.promptNotes||{};console.log(` operator prompts, verbatim and in order (${s.prompts.length}${t.echoesDropped?`; ${t.echoesDropped} transcript echo${t.echoesDropped===1?"":"es"} dropped`:""}${t.truncated?`; ${t.truncated} cut at 16 KB`:""}${t.omitted?`; ${t.omitted} beyond the first 200 omitted`:""}):`),s.prompts.forEach((n,r)=>{console.log(` \u2500\u2500 ${r+1}${r===0?" (the opening ask)":" (follow-up \u2014 NOT replayed)"} \xB7 ${new Date(n.at).toISOString()} \xB7 ${n.box||"\u2013"}${n.truncated?" \xB7 truncated":""}`),console.log(n.text.split(`
7
- `).map(l=>` \u2502 ${l}`).join(`
8
- `))}),console.log(" next: write the STATEMENT \u2014 the standalone task a replay box gets instead of this conversation (fold what the follow-ups settled into it; name the outcome the merged PR delivered, never the conversation) \u2014 and hand it in:"),console.log(` bostrat-replay spec draft ${o} --statement-file <path> [--suite "<the repo's suite command>"]`)}async function T(e){if(e.statement&&e["statement-file"]&&c("give --statement OR --statement-file, not both"),e["statement-file"]){let{readFile:o}=await import("node:fs/promises");try{return await o(e["statement-file"],"utf8")}catch(s){c(`cannot read ${e["statement-file"]}: ${s?.message||s}`)}}return e.statement||c(`a statement is required: --statement "<text>" or --statement-file <path>
9
- ${p}`),e.statement}function b(e){let o=e.versions[e.versions.length-1],s=e.approvedVersion!=null?`approved v${e.approvedVersion}`:"not approved";return console.log(`[bostrat-replay] spec ${e.id} v${e.version} \u2014 ${e.status} (${s}) \u2014 ${e.source.repo}#${e.source.pr} \u201C${e.source.trackName||e.source.trackId}\u201D`),o}async function M(e){let o=e._[0];o||c(`spec draft needs a <source>
10
- ${p}`);let s=await T(e),t;try{t=await m("POST","/api/replay/specs",{cwd:process.cwd(),source:o,statement:s,suite:e.suite??null,note:e.note??null})}catch(r){r.status===503&&r.data?.partial&&c(`${r.message}`),c(r.message)}let n=t.spec;b(n),console.log(` v1 drafted \u2014 the approval card is in this Track's chat (${n.acceptance.tests.length} acceptance test path${n.acceptance.tests.length===1?"":"s"}, ${n.prompts.length} original prompt${n.prompts.length===1?"":"s"} stored verbatim).`),console.log(" This is a BLOCKING prompt: stop and end your turn. The spec enters the bench only when the operator approves this version; to change it, `bostrat-replay spec revise "+n.id+" \u2026` (a new version, a fresh card).")}async function _(e){let o=e._[0];o||c(`spec revise needs a <spec>
11
- ${p}`);let s=await $(`/api/replay/specs/${encodeURIComponent(o)}`).catch(d=>c(d.message)),t=await T(e),n={cwd:process.cwd(),statement:t,note:e.note??null};e.suite!==void 0&&(n.suite=e.suite);let r;try{r=await m("POST",`/api/replay/specs/${encodeURIComponent(s.spec.id)}/revise`,n)}catch(d){c(d.message)}let l=r.spec;b(l),console.log(` v${l.version} drafted \u2014 a fresh approval card is in this Track's chat${l.approvedVersion!=null?`; v${l.approvedVersion} stays the bench entry until this one is approved`:""}.`),console.log(" This is a BLOCKING prompt: stop and end your turn.")}async function P(e){let{specs:o}=await $(`/api/replay/specs${e.status?`?status=${encodeURIComponent(e.status)}`:""}`);if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log("[bostrat-replay] no task specs on this node yet \u2014 `bostrat-replay census --rows` lists the eligible sources");return}let s={drafted:0,approved:0,dismissed:0};for(let t of o)s[t.status]=(s[t.status]||0)+1;console.log(`[bostrat-replay] ${o.length} task spec${o.length===1?"":"s"} on this node \u2014 ${s.approved} approved (the bench) \xB7 ${s.drafted} awaiting approval \xB7 ${s.dismissed} dismissed`);for(let t of o){let n=t.versions[t.versions.length-1],r=t.status==="approved"?"+":t.status==="drafted"?"?":"-";console.log(`${r} ${t.id} v${t.version}${t.approvedVersion!=null&&t.approvedVersion!==t.version?` (approved v${t.approvedVersion})`:""} ${`${t.source.repo}#${t.source.pr}`.padEnd(28)} ${(t.source.category||"\u2013").padEnd(14)} ${(t.source.model||t.source.provider||"\u2013").padEnd(20)} active ${g(t.source.activeMs).padStart(5)} tests ${String(t.acceptance.tests.length).padStart(2)} ${A(n.statement,60)}`)}}async function C(e){let o=e._[0];o||c(`spec show needs a <spec>
12
- ${p}`);let{spec:s}=await $(`/api/replay/specs/${encodeURIComponent(o)}`).catch(t=>c(t.message));if(e.json){console.log(JSON.stringify(s,null,2));return}b(s),f(s.source),console.log(` acceptance: ${s.acceptance.tests.length} test path${s.acceptance.tests.length===1?"":"s"} (of ${s.acceptance.files} files the PR changed)${s.versions[s.versions.length-1].suite?` \xB7 suite: ${s.versions[s.versions.length-1].suite}`:""}`);for(let t of s.acceptance.tests)console.log(` ${t}`);console.log(` versions (${s.versions.length}):`);for(let t of s.versions)console.log(` \u2500\u2500 v${t.v} \xB7 ${t.outcome}${t.v===s.approvedVersion?" \xB7 THE BENCH ENTRY":""} \xB7 ${new Date(t.createdAt).toISOString()} \xB7 by ${t.by?.agent||"the lead"} on Track \u201C${t.by?.trackName||t.by?.trackId||"\u2013"}\u201D${t.note?` \xB7 ${t.note}`:""}${t.suite?` \xB7 suite: ${t.suite}`:""}`),console.log(t.statement.split(`
13
- `).map(n=>` \u2502 ${n}`).join(`
14
- `));console.log(` original prompts stored verbatim: ${s.prompts.length} (the opening ask is what the statement replaces; follow-ups are not replayed) \u2014 \`spec show ${s.id} --json\` prints them`)}var u=process.argv.slice(2),S=u.shift();try{if(S==="census")await E(w(u));else if(S==="spec"){let e=u.shift(),o=w(u);e==="frame"?await x(o):e==="draft"?await M(o):e==="revise"?await _(o):e==="ls"?await P(o):e==="show"?await C(o):c(p)}else c(p)}catch(e){c(e?.message||String(e))}
2
+ var I=process.env.BOSTRAT_AGENT_URL||`http://127.0.0.1:${process.env.BOSTRAT_AGENT_PORT||3362}`,d=["usage: bostrat-replay census [--rows] [--json] [--budget <ms>] [--once]"," bostrat-replay spec frame <source> [--json]",' bostrat-replay spec draft <source> (--statement "<text>" | --statement-file <path>) [--suite "<cmd>"] [--note "<why>"]',' bostrat-replay spec revise <spec> (--statement "<text>" | --statement-file <path>) [--suite "<cmd>"] [--note "<what changed>"]'," bostrat-replay spec ls [--status drafted|approved|dismissed] [--json]"," bostrat-replay spec show <spec> [--json]"," bostrat-replay run <spec> [--provider claude|codex|cursor] [--model <id>] [--cap-usd 30] [--cap-active 75m] [--cap-wall 3h] [--keep] [--no-wait] [--json]"," bostrat-replay runs [--status running|finished] [--json]"," bostrat-replay runs show <run> [--json]"," bostrat-replay runs stop <run>"].join(`
3
+ `);function r(e){console.error(`[bostrat-replay] ${e}`),process.exit(1)}async function h(e,o,s){let t=await fetch(`${I}${o}`,{method:e,headers:s?{"content-type":"application/json"}:void 0,body:s?JSON.stringify(s):void 0}),a=await t.json().catch(()=>({}));if(!t.ok){let n=new Error(a.error||`HTTP ${t.status}`);throw n.status=t.status,n.data=a,n}return a}var $=e=>h("GET",e),E=new Set(["rows","json","once","keep","no-wait"]),M=new Set(["budget","statement","statement-file","suite","note","status","provider","model","cap-usd","cap-active","cap-wall"]);function f(e){let o={_:[]};for(let s=0;s<e.length;s++){let t=e[s];if(t.startsWith("--")){let a=t.slice(2);E.has(a)?o[a]=!0:M.has(a)?(s+1>=e.length&&r(`${t} needs a value
4
+ ${d}`),o[a]=e[++s]):r(`unknown flag ${t}
5
+ ${d}`)}else o._.push(t)}return o}var p=e=>{let o=Math.round((Number(e)||0)/6e4);return o>=60?`${(o/60).toFixed(1)}h`:`${o}m`},A=(e,o)=>o?`${Math.round(100*e/o)}%`:"\u2013",v=e=>String(e||"").slice(0,8)||"\u2013",O=e=>e?new Date(e).toISOString().slice(0,10):"\u2013",C=(e,o=96)=>{let s=String(e||"").replace(/\s+/g," ").trim();return s.length>o?`${s.slice(0,o-1)}\u2026`:s};async function x(e){let o=Number.isFinite(Number(e.budget))&&Number(e.budget)>0?Number(e.budget):8e3,s=e.rows?"1":"0",t;for(let i=0;i<120&&(t=await $(`/api/usage/replay-census?budgetMs=${o}&rows=${s}`),!(!t.partial||e.once));i++)process.stderr.write(`[bostrat-replay] census in progress \u2014 ${t.pending} still pending (${t.judged} judged)\r`);if(t||r("no answer from the agent"),e.json){console.log(JSON.stringify(t,null,2));return}let a=t.tracks,n=t.criteria,c=t.excluded;console.log(`[bostrat-replay] ${t.label}${t.partial?` \u2014 PARTIAL, ${t.pending} pending (run again)`:""}`),console.log(` eligible: ${t.eligible} of ${t.merged} merged archived Tracks (${A(t.eligible,t.merged)}) \u2014 ${a.archived} archived on this node, ${a.open} open, ${a.loops} loop runs excluded, ${a.unreadable} unreadable`),console.log(` funnel (each criterion counted on its own, over the ${t.judged} judged):`),console.log(` merged PR ${n.mergedPr}`),console.log(` recoverable base ${n.recoverableBase} (not: ${c.baseNotRecoverable}${Object.keys(t.baseReasons).length?" \u2014 "+Object.entries(t.baseReasons).map(([i,l])=>`${i} ${l}`).join(", "):""})`),console.log(` tests touched ${n.testsTouched} (not: ${c.noTestsTouched} of those with a base)`),console.log(` no ops/deploy step ${n.noOpsStep} (not: ${c.opsStep}${Object.keys(t.opsRules).length?" \u2014 "+Object.entries(t.opsRules).map(([i,l])=>`${i} ${l}`).join(", "):""})`),console.log(` not merged (archived without a merged PR): ${c.notMerged}`);let u=Object.entries(t.byRepo);if(u.length){console.log(" by repo:");for(let[i,l]of u)console.log(` ${i.padEnd(32)} merged ${String(l.merged).padStart(4)} eligible ${String(l.eligible).padStart(4)} (base ${l.baseNotRecoverable} \xB7 tests ${l.noTestsTouched} \xB7 ops ${l.opsStep})`)}let S=Object.entries(t.byCategory);S.length&&console.log(` eligible by category: ${S.map(([i,l])=>`${i} ${l}`).join(" \xB7 ")}`);let j=Object.entries(t.byModel);if(j.length&&console.log(` eligible by model: ${j.map(([i,l])=>`${i} ${l}`).join(" \xB7 ")}`),e.rows&&Array.isArray(t.rows)){console.log(` eligible Tracks (${t.rows.length}):`);for(let i of t.rows)console.log(` ${i.repo}#${i.pr} ${String(i.name||i.trackId).slice(0,48).padEnd(48)} ${i.category||"\u2013"} ${i.model||i.provider||"\u2013"} active ${p(i.activeMs)} tests ${i.tests}/${i.files} base ${v(i.base)} ${i.trackId}`)}console.log(` basis: ${t.basis.label}; ${t.basis.scope}`),console.log(` no ops/deploy step: ${t.basis.noOpsStep}`)}async function P(e){let o;for(let s=0;s<40&&(o=await $(`/api/replay/frame?source=${encodeURIComponent(e)}&budgetMs=15000`),!!o.partial);s++)process.stderr.write(`[bostrat-replay] reading the archived logs \u2014 ${o.pending} still pending\r`);return(!o||o.partial)&&r("the archived logs are still being read \u2014 run again"),o}function y(e,o=" "){console.log(`${o}source: ${e.repo}#${e.pr} \u2014 Track \u201C${e.trackName||e.trackId}\u201D (${e.trackId})`),console.log(`${o} merged ${O(e.mergedAt)} at ${v(e.mergeCommit)} \xB7 base ${v(e.base)} (the commit a sealed clone is cut at)`),console.log(`${o} ${e.category||"uncategorized"} \xB7 ${e.model||e.provider||"\u2013"} \xB7 agent-active ${p(e.activeMs)} \xB7 wall ${p(e.wallMs)} \xB7 ${e.prompts} operator prompt${e.prompts===1?"":"s"} \xB7 $${(Number(e.usd)||0).toFixed(2)} notional`)}async function _(e){let o=e._[0];o||r(`spec frame needs a <source>
6
+ ${d}`);let s=await P(o);if(e.json){console.log(JSON.stringify(s,null,2));return}if(console.log(`[bostrat-replay] ${s.label||"replay task spec"} \u2014 frame for ${o}`),!s.eligible){console.log(` NOT replay-eligible: ${s.reasons.join(", ")}`),s.source&&y(s.source),console.log(" a spec cannot be drafted from this Track (R11: no acceptance tests, or an ops step a sealed clone cannot replay)");return}y(s.source),console.log(` acceptance: ${s.acceptance.tests.length} test path${s.acceptance.tests.length===1?"":"s"} the PR touched (of ${s.acceptance.files} files):`);for(let a of s.acceptance.tests)console.log(` ${a}`);let t=s.promptNotes||{};console.log(` operator prompts, verbatim and in order (${s.prompts.length}${t.echoesDropped?`; ${t.echoesDropped} transcript echo${t.echoesDropped===1?"":"es"} dropped`:""}${t.truncated?`; ${t.truncated} cut at 16 KB`:""}${t.omitted?`; ${t.omitted} beyond the first 200 omitted`:""}):`),s.prompts.forEach((a,n)=>{console.log(` \u2500\u2500 ${n+1}${n===0?" (the opening ask)":" (follow-up \u2014 NOT replayed)"} \xB7 ${new Date(a.at).toISOString()} \xB7 ${a.box||"\u2013"}${a.truncated?" \xB7 truncated":""}`),console.log(a.text.split(`
7
+ `).map(c=>` \u2502 ${c}`).join(`
8
+ `))}),console.log(" next: write the STATEMENT \u2014 the standalone task a replay box gets instead of this conversation (fold what the follow-ups settled into it; name the outcome the merged PR delivered, never the conversation) \u2014 and hand it in:"),console.log(` bostrat-replay spec draft ${o} --statement-file <path> [--suite "<the repo's suite command>"]`)}async function N(e){if(e.statement&&e["statement-file"]&&r("give --statement OR --statement-file, not both"),e["statement-file"]){let{readFile:o}=await import("node:fs/promises");try{return await o(e["statement-file"],"utf8")}catch(s){r(`cannot read ${e["statement-file"]}: ${s?.message||s}`)}}return e.statement||r(`a statement is required: --statement "<text>" or --statement-file <path>
9
+ ${d}`),e.statement}function k(e){let o=e.versions[e.versions.length-1],s=e.approvedVersion!=null?`approved v${e.approvedVersion}`:"not approved";return console.log(`[bostrat-replay] spec ${e.id} v${e.version} \u2014 ${e.status} (${s}) \u2014 ${e.source.repo}#${e.source.pr} \u201C${e.source.trackName||e.source.trackId}\u201D`),o}async function L(e){let o=e._[0];o||r(`spec draft needs a <source>
10
+ ${d}`);let s=await N(e),t;try{t=await h("POST","/api/replay/specs",{cwd:process.cwd(),source:o,statement:s,suite:e.suite??null,note:e.note??null})}catch(n){n.status===503&&n.data?.partial&&r(`${n.message}`),r(n.message)}let a=t.spec;k(a),console.log(` v1 drafted \u2014 the approval card is in this Track's chat (${a.acceptance.tests.length} acceptance test path${a.acceptance.tests.length===1?"":"s"}, ${a.prompts.length} original prompt${a.prompts.length===1?"":"s"} stored verbatim).`),console.log(" This is a BLOCKING prompt: stop and end your turn. The spec enters the bench only when the operator approves this version; to change it, `bostrat-replay spec revise "+a.id+" \u2026` (a new version, a fresh card).")}async function U(e){let o=e._[0];o||r(`spec revise needs a <spec>
11
+ ${d}`);let s=await $(`/api/replay/specs/${encodeURIComponent(o)}`).catch(u=>r(u.message)),t=await N(e),a={cwd:process.cwd(),statement:t,note:e.note??null};e.suite!==void 0&&(a.suite=e.suite);let n;try{n=await h("POST",`/api/replay/specs/${encodeURIComponent(s.spec.id)}/revise`,a)}catch(u){r(u.message)}let c=n.spec;k(c),console.log(` v${c.version} drafted \u2014 a fresh approval card is in this Track's chat${c.approvedVersion!=null?`; v${c.approvedVersion} stays the bench entry until this one is approved`:""}.`),console.log(" This is a BLOCKING prompt: stop and end your turn.")}async function B(e){let{specs:o}=await $(`/api/replay/specs${e.status?`?status=${encodeURIComponent(e.status)}`:""}`);if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log("[bostrat-replay] no task specs on this node yet \u2014 `bostrat-replay census --rows` lists the eligible sources");return}let s={drafted:0,approved:0,dismissed:0};for(let t of o)s[t.status]=(s[t.status]||0)+1;console.log(`[bostrat-replay] ${o.length} task spec${o.length===1?"":"s"} on this node \u2014 ${s.approved} approved (the bench) \xB7 ${s.drafted} awaiting approval \xB7 ${s.dismissed} dismissed`);for(let t of o){let a=t.versions[t.versions.length-1],n=t.status==="approved"?"+":t.status==="drafted"?"?":"-";console.log(`${n} ${t.id} v${t.version}${t.approvedVersion!=null&&t.approvedVersion!==t.version?` (approved v${t.approvedVersion})`:""} ${`${t.source.repo}#${t.source.pr}`.padEnd(28)} ${(t.source.category||"\u2013").padEnd(14)} ${(t.source.model||t.source.provider||"\u2013").padEnd(20)} active ${p(t.source.activeMs).padStart(5)} tests ${String(t.acceptance.tests.length).padStart(2)} ${C(a.statement,60)}`)}}async function q(e){let o=e._[0];o||r(`spec show needs a <spec>
12
+ ${d}`);let{spec:s}=await $(`/api/replay/specs/${encodeURIComponent(o)}`).catch(t=>r(t.message));if(e.json){console.log(JSON.stringify(s,null,2));return}k(s),y(s.source),console.log(` acceptance: ${s.acceptance.tests.length} test path${s.acceptance.tests.length===1?"":"s"} (of ${s.acceptance.files} files the PR changed)${s.versions[s.versions.length-1].suite?` \xB7 suite: ${s.versions[s.versions.length-1].suite}`:""}`);for(let t of s.acceptance.tests)console.log(` ${t}`);console.log(` versions (${s.versions.length}):`);for(let t of s.versions)console.log(` \u2500\u2500 v${t.v} \xB7 ${t.outcome}${t.v===s.approvedVersion?" \xB7 THE BENCH ENTRY":""} \xB7 ${new Date(t.createdAt).toISOString()} \xB7 by ${t.by?.agent||"the lead"} on Track \u201C${t.by?.trackName||t.by?.trackId||"\u2013"}\u201D${t.note?` \xB7 ${t.note}`:""}${t.suite?` \xB7 suite: ${t.suite}`:""}`),console.log(t.statement.split(`
13
+ `).map(a=>` \u2502 ${a}`).join(`
14
+ `));console.log(` original prompts stored verbatim: ${s.prompts.length} (the opening ask is what the statement replaces; follow-ups are not replayed) \u2014 \`spec show ${s.id} --json\` prints them`)}function T(e,o){let s=String(e??"").trim().match(/^(\d+(?:\.\d+)?)\s*(m|min|mins|minutes?|h|hr|hrs|hours?|d|days?)?$/i);s||r(`${o} wants a duration like 75m, 1.5h or 1d (got "${e}")`);let t=Number(s[1]),a=(s[2]||"m").toLowerCase(),n=a.startsWith("h")?t*36e5:a.startsWith("d")?t*8*36e5:t*6e4;return n>0||r(`${o} must be positive`),n}var b=e=>`$${(Number(e)||0).toFixed(2)}`,R={sealing:"sealing the clone",starting:"starting the box",running:"the agent is working",checking:"running the acceptance tests",done:"done"};function w(e,{head:o=!0}={}){if(o&&console.log(`[bostrat-replay] run ${e.id} \u2014 ${e.status==="running"?`${e.status} \xB7 ${R[e.phase]||e.phase}`:e.outcome} \u2014 ${e.source.repo}#${e.source.pr} \xB7 spec ${e.specId} v${e.version} \xB7 ${e.model||e.provider}${e.trackId?` \xB7 Track ${e.trackId}`:""}`),console.log(` agent-active ${p(e.activeMs)} \xB7 wall ${p(e.wallMs)} \xB7 ${b(e.usd)} notional \xB7 ${e.turns} turn${e.turns===1?"":"s"} \xB7 ${e.toolCalls} tool call${e.toolCalls===1?"":"s"} \xB7 ${e.questions} question${e.questions===1?"":"s"} answered "use your judgment"`),e.source.activeMs!=null&&console.log(` the source Track took agent-active ${p(e.source.activeMs)} \xB7 ${b(e.source.usd)} on ${e.source.model||"\u2013"} (conversational actuals \u2014 a different quantity from this single-shot run, D7)`),e.cappedBy&&console.log(` CAPPED by ${e.cappedBy} (caps: ${b(e.caps.usd)} \xB7 active ${p(e.caps.activeMs)} \xB7 wall ${p(e.caps.wallMs)} \xB7 ${e.caps.questions} questions) \u2014 partial time and cost recorded (R24)`),e.error&&console.log(` error: ${e.error}`),e.acceptance){let s=e.check?.tests||[];console.log(` acceptance: ${e.acceptance.toUpperCase()} \u2014 ${s.filter(t=>t.status==="pass").length}/${s.length} test path${s.length===1?"":"s"} pass${e.acceptance==="unverified"?" (no test could run: excluded from pass-rate figures, R11)":""}`);for(let t of s)console.log(` ${t.status.padEnd(7)} ${t.path}${t.runner?` (${t.runner}, ${p(t.ms)})`:""}${t.reason?` \u2014 ${t.reason}`:""}`);e.check?.suite&&console.log(` suite: ${e.check.suite.status} \u2014 ${e.check.suite.cmd} (${p(e.check.suite.ms)})`);for(let t of e.check?.deps||[])console.log(` deps: ${t.status} \u2014 ${t.cmd} in ${t.dir} (${p(t.ms)})`)}e.status==="finished"&&console.log(` record: ${e.dir}/result.json${e.patchBytes!=null?` \xB7 result.patch (${e.patchBytes} bytes)`:""}${e.cloneRemoved?" \xB7 clone removed":" \xB7 clone kept"}`),console.log(` ${e.label}`)}async function D(e){let o=e._[0];o||r(`run needs a <spec>
15
+ ${d}`);let s={};e["cap-usd"]!=null&&(s.usd=Number(e["cap-usd"]),s.usd>0||r("--cap-usd wants a positive dollar figure")),e["cap-active"]!=null&&(s.activeMs=T(e["cap-active"],"--cap-active")),e["cap-wall"]!=null&&(s.wallMs=T(e["cap-wall"],"--cap-wall"));let t;try{t=await h("POST","/api/replay/runs",{spec:o,provider:e.provider||"claude",model:e.model||null,caps:s,keep:!!e.keep})}catch(c){r(c.status===409?`${c.message} \u2014 \`bostrat-replay runs stop ${c.data?.runId||"<run>"}\` ends it`:c.message)}let a=t.run;if(e["no-wait"]){e.json?console.log(JSON.stringify(a,null,2)):(w(a),console.log(` running in the background \u2014 \`bostrat-replay runs show ${a.id}\` reads it`));return}let n=null;for(;a.status==="running";)!e.json&&a.phase!==n&&(n=a.phase,process.stderr.write(`[bostrat-replay] run ${a.id}: ${R[n]||n}${a.trackId?` (Track ${a.trackId})`:""}
16
+ `)),await new Promise(c=>setTimeout(c,1e4)),a=(await $(`/api/replay/runs/${encodeURIComponent(a.id)}`)).run;e.json?console.log(JSON.stringify(a,null,2)):w(a)}async function F(e){let o=e._[0];if(o==="show"||o==="stop"){let n=e._[1];if(n||r(`runs ${o} needs a <run>
17
+ ${d}`),o==="stop"){await h("POST",`/api/replay/runs/${encodeURIComponent(n)}/stop`).catch(u=>r(u.message)),console.log(`[bostrat-replay] run ${n}: stop requested \u2014 it is recorded as capped (stop) once the turn closes, then checked`);return}let{run:c}=await $(`/api/replay/runs/${encodeURIComponent(n)}`).catch(u=>r(u.message));e.json?console.log(JSON.stringify(c,null,2)):w(c);return}o&&r(d);let{runs:s,live:t}=await $(`/api/replay/runs${e.status?`?status=${encodeURIComponent(e.status)}`:""}`);if(e.json){console.log(JSON.stringify({runs:s,live:t},null,2));return}if(!s.length){console.log("[bostrat-replay] no replay runs on this node yet \u2014 `bostrat-replay run <spec>` starts one (spec ls lists the approved specs)");return}let a={};for(let n of s)a[n.status==="running"?"running":n.outcome]=(a[n.status==="running"?"running":n.outcome]||0)+1;console.log(`[bostrat-replay] ${s.length} replay run${s.length===1?"":"s"} on this node \u2014 ${Object.entries(a).map(([n,c])=>`${n} ${c}`).join(" \xB7 ")}${t?` \xB7 live: ${t.id}`:""}`);for(let n of s){let c=n.status==="running"?"~":n.outcome==="passed"?"+":n.outcome==="failed"?"-":n.outcome==="capped"?"c":n.outcome==="unverified"?"?":"!";console.log(`${c} ${n.id} ${O(n.startedAt)} ${(n.status==="running"?`running/${n.phase}`:n.outcome).padEnd(11)} ${`${n.source.repo}#${n.source.pr}`.padEnd(28)} spec ${n.specId} v${n.version} ${(n.model||n.provider).padEnd(16)} active ${p(n.activeMs).padStart(5)} ${b(n.usd).padStart(7)} q ${n.questions} ${n.acceptance||"\u2013"}`)}console.log(` ${s[0].label}`)}var g=process.argv.slice(2),m=g.shift();try{if(m==="census")await x(f(g));else if(m==="spec"){let e=g.shift(),o=f(g);e==="frame"?await _(o):e==="draft"?await L(o):e==="revise"?await U(o):e==="ls"?await B(o):e==="show"?await q(o):r(d)}else m==="run"?await D(f(g)):m==="runs"?await F(f(g)):r(d)}catch(e){r(e?.message||String(e))}