bostrat-node 1.17.7 → 1.17.9

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 Bo 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 xn}from"node:util";var Ne=xn(ct),rt="BOSTRAT_BOX_USER",Tn="bostrat-box",lt=Object.freeze(["root","sudo","wheel","admin","docker","lxd","libvirt","disk"]);var An=/^[a-z_][a-z0-9_-]{0,31}$/,In=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(In.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(!An.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 On(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?On(e):e.BOSTRAT_BOX_HOME_VIEW||A.join(ut(e),"box-home")}function Rn(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]=Rn(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 vn(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 Nn(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 Pn(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 Dn():!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: ${jn(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 Nn(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(", ")}`)}vn(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 jn=e=>String(e?.stderr||e?.message||e).trim().split(`
5
5
  `)[0].slice(0,160);async function Dn(){try{return await Ne("sudo",["-n","true"],{timeout:3e3}),!0}catch{return!1}}async function Pn(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=${Tn}`)}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 Mn="BP-AU-R4",xt=160,gt={high:0,medium:1,low:2},yt=200,bt=5,wt=8,St=5,kt=10*6e4,Cn=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"]),Ln=5e3,Pe=new Set(["tool.called","tool.failed"]),je=new Set(["Write","Edit","NotebookEdit"]),Un=e=>String(e??"").replace(/\s+/g," ").trim(),L=(e,t=120)=>Un(e).slice(0,t);function Hn(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/"']+)`,Bn=new RegExp(`${Me}/\\.ssh(?:/|\\b)`),Fn=new RegExp(`${Me}/(?:\\.claude\\.json\\b|\\.claude/\\.credentials\\.json|\\.codex/auth\\.json|\\.cursor(?:/|\\b))`),Wn=/(?:^|[\s/"'=(])(\.env(?:\.[A-Za-z0-9_.-]+)?)(?=$|[\s"'|;&)])/g,qn=/^\.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"']*)?)`),Kn=/^(?: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)$/,Gn=/^\/tmp\/|\/\.bostrat\/tmp\//,Xn=/^(?:refs\/heads\/)?(?:main|master|develop|development|trunk|production|prod|staging|release(?:\/|$)|v\d)/,Vn=/(?:^|\/)track\/|^HEAD$|^refs\/bostrat\//,zn=/https?:\/\/([a-z0-9.-]+\.[a-z]{2,}|localhost|\d+\.\d+\.\d+\.\d+)(?::\d+)?/gi,$t=e=>Bn.test(e)||Fn.test(e),_t=e=>[...String(e??"").matchAll(Wn)].some(t=>!qn.test(t[1])),Yn=e=>At.test(e),Jn=e=>It.test(e),Zn=e=>(e.startsWith("/")||e.startsWith("~"))&&!Gn.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 Qn=e=>Rt(e,At);function eo(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&&Kn.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 to(e){let t=new Set;for(let n of String(e??"").matchAll(zn))t.add(n[1].toLowerCase());return[...t]}function no({knownHosts:e=[]}={}){return{known:new Set([...Cn,...[...e].map(t=>String(t).toLowerCase()).filter(Boolean)]),hosts:new Set,tracks:new Map}}function oo(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:Mn,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 Hn(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&&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}),"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&&Jn(r.path)&&(n++,o??=L(`${r.tool} ${r.path}`));let s=Q(t,r=>{let a=eo(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=>Xn.test(s)||!Vn.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&&Zn(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 to(s.head))t.state.known.has(r)||t.state.hosts.has(r)||(t.state.hosts.add(r),t.state.hosts.size>Ln&&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)),so=new Set([...Pe,"cost.recorded","peer.message","turn.user","audit.procs","harness.shape.seen"]);function ro(e,t,{rules:n=null,headCap:o=xt}={}){if(!t||!so.has(t.type)||t.source==="plane")return[];let s=oo(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=no(),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 ro(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 io=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 ${io(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 Ro from"node:os";import qe from"node:path";import He from"node:fs/promises";import Y from"node:path";import go from"node:os";import{EventEmitter as yo}from"node:events";import{randomUUID as bo}from"node:crypto";import ce from"node:fs";import ue from"node:path";import ao from"node:os";var co=()=>process.env.BOSTRAT_STATE_DIR||ue.join(process.env.HOME||ao.tmpdir(),".bostrat"),lo="secure-inputs",Pt=()=>ue.join(co(),lo),uo=/^[A-Z][A-Z0-9_]{0,63}$/,po=/^[A-Za-z0-9_-]{1,80}$/,fo=16*1024;var Ce=8;function ho(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")>fo?"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 mo(){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()||!po.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()||!uo.test(s.name)))try{let r=ue.join(Dt(t.name),s.name),a=ce.readFileSync(r,"utf8");if(ho(a))continue;n.set(s.name,{value:a,addedAt:ce.statSync(r).mtimeMs})}catch{}n.size&&Le.set(t.name,n)}mo()}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 wo=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","blueprint.status.offered","blueprint.merge.unlocked","blueprint.gate.met","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"]),So=new Set(["user","agent","orchestrator","system","peer"]),ko=new Set(["hook","otel","statusline","transcript","pane","orchestrator","vendor","cli","auditd","proc","plane"]),Be=new yo;Be.setMaxListeners(0);var Fe=process.env.BOSTRAT_STATE_DIR||Y.join(process.env.HOME||go.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 Eo(e,t){if(te.has(t))return;let n=await To(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 $o(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||!wo.has(t.type))throw new Error(`appendEvent: unknown event type "${t?.type}"`);if(t.actor&&!So.has(t.actor))throw new Error(`appendEvent: bad actor "${t.actor}"`);if(t.source&&!ko.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 $o(n,async()=>{await Eo(o,n);let r=te.get(n)+1;te.set(n,r);let a=pe.get(n)??null,u={id:t.id||bo(),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 Ro from"node:os";import qe from"node:path";import He from"node:fs/promises";import Y from"node:path";import go from"node:os";import{EventEmitter as yo}from"node:events";import{randomUUID as bo}from"node:crypto";import ce from"node:fs";import ue from"node:path";import ao from"node:os";var co=()=>process.env.BOSTRAT_STATE_DIR||ue.join(process.env.HOME||ao.tmpdir(),".bostrat"),lo="secure-inputs",Pt=()=>ue.join(co(),lo),uo=/^[A-Z][A-Z0-9_]{0,63}$/,po=/^[A-Za-z0-9_-]{1,80}$/,fo=16*1024;var Ce=8;function ho(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")>fo?"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 mo(){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()||!po.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()||!uo.test(s.name)))try{let r=ue.join(Dt(t.name),s.name),a=ce.readFileSync(r,"utf8");if(ho(a))continue;n.set(s.name,{value:a,addedAt:ce.statSync(r).mtimeMs})}catch{}n.size&&Le.set(t.name,n)}mo()}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 wo=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","replay.run.stubbed","standing.eval.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","blueprint.status.offered","blueprint.merge.unlocked","blueprint.gate.met","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"]),So=new Set(["user","agent","orchestrator","system","peer"]),ko=new Set(["hook","otel","statusline","transcript","pane","orchestrator","vendor","cli","auditd","proc","plane"]),Be=new yo;Be.setMaxListeners(0);var Fe=process.env.BOSTRAT_STATE_DIR||Y.join(process.env.HOME||go.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 Eo(e,t){if(te.has(t))return;let n=await To(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 $o(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||!wo.has(t.type))throw new Error(`appendEvent: unknown event type "${t?.type}"`);if(t.actor&&!So.has(t.actor))throw new Error(`appendEvent: bad actor "${t.actor}"`);if(t.source&&!ko.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 $o(n,async()=>{await Eo(o,n);let r=te.get(n)+1;te.set(n,r);let a=pe.get(n)??null,u={id:t.id||bo(),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 xo=/(?<!\\)((?:\\\\)*)\\u0000/g,fe=e=>e.includes("\\u0000"),he=e=>e.replace(xo,"$1\\ufffd");async function To(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 Ao(s)}function Ao(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 Io from"node:path";var Oo=0;async function Bt(e,t,{mode:n}={}){await me.mkdir(Io.dirname(e),{recursive:!0});let o=`${e}.${process.pid}.${++Oo}.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 vo=()=>process.env.BOSTRAT_STATE_DIR||qe.join(process.env.HOME||Ro.tmpdir(),".bostrat"),No="harness-shapes.json",jo=12,Do=8,Po=80,Mo=e=>Ue(String(e||"").replace(/\s+/g," ").trim().slice(0,Po));function Co({file:e=null,deps:t={},log:n=console}={}){let o={appendEvent:Ht,now:()=>Date.now(),...t},s=()=>e||qe.join(vo(),No),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:Mo(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>jo&&k.tracks.shift()),T&&(k.providers[T]=(k.providers[T]||0)+1),v&&!k.versions.includes(v)&&(k.versions.push(v),k.versions.length>Do&&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 Lo(){return We||(We=Co()),We}var qt=()=>Lo().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,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- var y=process.env.BOSTRAT_AGENT_URL||`http://127.0.0.1:${process.env.BOSTRAT_AGENT_PORT||3362}`;async function f(e,a,o){let i=await fetch(`${y}${a}`,{method:e,headers:o?{"content-type":"application/json"}:void 0,body:o?JSON.stringify(o):void 0}),s=await i.json().catch(()=>({}));if(!i.ok)throw Object.assign(new Error(s.error||`HTTP ${i.status}`),{status:i.status,data:s});return s}function u(e){console.error(`[bostrat-blueprint] ${e}`),process.exit(1)}function v(e,a){if(console.error(`[bostrat-blueprint] refused: ${e.error}`),e.code==="stale-base"){if(console.error(` plane holds v${e.current}; this copy was built on v${e.yourBase}.`),e.drift?.length){console.error(" item-level difference:");for(let o of e.drift)console.error(` ${String(o.itemId).padEnd(12)} plane: ${String(o.plane).padEnd(7)} file: ${o.file}`)}else console.error(" no item differs \u2014 the newer version changed prose only.");console.error(" Bring this copy up to date, then republish:"),console.error(" git fetch origin && git merge origin/main # siblings' ticks land on main with their PRs"),console.error(" (copy any ticked item you still lack VERBATIM \u2014 never invent a sibling's note)"),console.error(` bostrat-blueprint show && bostrat-blueprint update ${a}`),console.error(` Or, once the file carries everything above: bostrat-blueprint update --base ${e.current} ${a}`)}else e.code==="untick"&&(console.error(` would un-tick: ${e.untick.join(", ")} (plane v${e.current} has them [x]).`),console.error(" Copy their ticks + status notes into the file (merge origin/main first), then republish."));console.error(" --force publishes the file exactly as it is (un-ticking the items above). Only when that is the intent."),process.exit(1)}function w(e){if(e){console.log(` parsed: ${e.sections.recognized} recognized section(s), ${e.items.total} item(s) (${e.items.bindable} bindable)`);for(let a of e.issues??[])console.log(` \u26A0 ${a.message}`)}}var r=process.argv.slice(2),g=r.shift();if(g==="add"||g==="update"){let e=null,a=null,o=null,i=null,s=null,l=!1;for(let n=0;n<r.length;n++)r[n]==="--circuit"?e=r[++n]:r[n]==="--new-circuit"?a=r[++n]:r[n]==="--name"?o=r[++n]:r[n]==="--base"?s=r[++n]:r[n]==="--force"?l=!0:i=r[n];i||u(`usage: bostrat-blueprint ${g} [--circuit <name-or-id>] [--new-circuit "<name>"] [--name "<title>"] [--base <v>] [--force] <file.md>`),s!=null&&!/^[1-9]\d*$/.test(String(s))&&u(`--base takes a version number (what \`show\` prints), got "${s}"`);try{let n=await(await import("node:fs/promises")).readFile(i,"utf8"),h=null,m=null;try{let{execFileSync:t}=await import("node:child_process"),p=await import("node:path"),c=p.resolve(i),b=t("git",["rev-parse","--show-toplevel"],{cwd:p.dirname(c),encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),$=p.relative(b,c);$&&!$.startsWith("..")&&(h=$.split(p.sep).join("/"),m=b)}catch{}let d=await f("POST","/api/blueprints/publish",{cwd:process.cwd(),circuit:e,newCircuit:a,name:o,markdown:n,base:s==null?null:Number(s),force:l,path:h,root:m});console.log(`[bostrat-blueprint] published \u201C${d.blueprint.name}\u201D v${d.blueprint.version} on circuit \u201C${d.circuit.name}\u201D${d.base?` (on v${d.base})`:""}${l?" (forced)":""}`),w(d.report),d.linked&&console.log(` This Track is now in circuit \u201C${d.circuit.name}\u201D (it was in none) \u2014 the blueprint's item ids in a closing message are launch controls from here.`),d.blueprint.version===1&&console.log(" The circuit page now carries this blueprint; PRs/commits mentioning BP ids show as evidence \u2014 tick [x] + a *(done \u2026)* note in the same PR as the item's work.")}catch(n){n.status===409&&n.data?.code&&v(n.data,i),u(n.message)}}else if(g==="show"||g==="report")try{let e=await f("GET",`/api/blueprints/show?cwd=${encodeURIComponent(process.cwd())}${r[0]?`&circuit=${encodeURIComponent(r[0])}`:""}`);if(console.log(`[bostrat-blueprint] \u201C${e.blueprint.name}\u201D v${e.blueprint.version} (circuit ${e.blueprint.circuitId})`),w(e.report),g==="show"){let a=!!e.graph?.edges,o=e.readyAt||"merged",i=new Set,s=t=>{let p=Array.isArray(t.waits)&&t.waits.length?t.waits:null;return p?p.map(c=>c.gate&&c.gate!==o?(i.add(c.gate),`${c.itemId} ${c.gate}`):c.itemId).join(", "):(t.waitsOn??[]).join(", ")},l=t=>t.bindable?t.done?"done":a?t.ready?`ready${t.seam?" \xB7 seam":""}`:`waits on ${s(t)}`:"":"",n=e.items.some(t=>t.bindable&&t.stageLine),h=e.items.map(t=>({i:t,id:t.bindable?t.itemId:"(no id)",pose:l(t)})),m=Math.max(8,...h.map(t=>t.id.length)),d=n?Math.max(0,...h.map(t=>t.pose?t.pose.length+2:0)):0;for(let{i:t,id:p,pose:c}of h){if(!n){console.log(` ${p.padEnd(8)} ${t.sectionKind.padEnd(14)} ${c?`[${c}] `:""}${t.text}`);continue}let b=t.bindable&&t.stageLine?t.stageLine:"";console.log(` ${p.padEnd(m)} ${t.sectionKind.padEnd(14)} ${(c?`[${c}]`:"").padEnd(d)}${d?" ":""}${b}`.trimEnd()),t.text&&console.log(` ${"".padEnd(m)} ${t.text}`)}n&&console.log(" (stage = what the plane observed, with its evidence. merged or higher is a fact \u2014 do not re-verify it; copy it as printed)"),a&&(console.log(e.readyAt?` (readiness = every \`after\` item is at ${e.readyAt} or higher \u2014 this blueprint's ready-at; a What-remains list bolds only ready items)`:" (readiness = every `after` item presents as done; a What-remains list bolds only ready items)"),i.size&&console.log(" (gate words: merged = the dependency's code is on main; released = it is in a cut release; live = it is running on the repo's deploy surfaces. A word beside an id is that edge's own gate; an edge with no word waits at ready-at)"))}}catch(e){u(e.message)}else if(g==="remains"){let e='usage: bostrat-blueprint remains [--brief <BP-id>="<one sentence>"]\u2026',a={};for(let o=0;o<r.length;o++){r[o]!=="--brief"&&u(`unknown argument "${r[o]}" \u2014 ${e}`);let i=r[++o];i==null&&u(e);let s=i.indexOf("="),l=(s>0?i.slice(0,s):i).trim(),n=s>0?i.slice(s+1):r[++o];(!/^BP-[A-Z0-9]+(?:-[A-Z0-9]+)*$/i.test(l)||!String(n??"").trim())&&u(`--brief takes <BP-id>="<one sentence>", got "${i}" \u2014 ${e}`),a[l.toUpperCase()]=String(n).trim()}try{let o=await f("POST","/api/blueprints/remains",{cwd:process.cwd(),briefs:a}),i=o.counts;console.log(`[bostrat-blueprint] status card posted for \u201C${o.name??"blueprint"}\u201D v${o.version} \u2014 ${i.done} of ${i.total} merged \xB7 ${i.ready} ready \xB7 ${i.waiting} waiting`),o.mine?.length&&console.log(` this Track: ${o.mine.map(s=>`${s.itemId} (${s.stageLine??s.stage??"open"})`).join(", ")}`);for(let s of o.ready??[])console.log(` ready ${s.itemId} ${s.text}${o.briefs?.[s.itemId]?` \u2014 brief: ${o.briefs[s.itemId]}`:""}`);for(let s of o.waiting??[])console.log(` waiting ${s.itemId} ${s.text} \u2014 waits on ${(s.waits??[]).map(l=>`${l.itemId}${l.gate?` ${l.gate}`:""}`).join(", ")||"(unmet)"}`);!i.ready&&!i.waiting&&console.log(" nothing open \u2014 every item presents done."),console.log(" The card carries these rows under your closing message. Do not repeat them in your message \u2014 close by saying what you did and end your turn.")}catch(o){console.error(`[bostrat-blueprint] no status card posted: ${o.message}`),console.error(' Fall back to prose: end your message with a short "What remains" list \u2014 "Ready now" items with the FULL id in bold first (**BP-X-I3**: what it still needs), then "Waiting" items (id not bold) with what each waits on.'),process.exit(1)}}else if(g==="tag"){r.length||u("usage: bostrat-blueprint tag <BP-id> [<BP-id>\u2026]");try{let e=await f("POST","/api/blueprints/tag",{cwd:process.cwd(),itemIds:r});console.log(`[bostrat-blueprint] tagged this Track onto ${e.itemIds.join(", ")}`),console.log(" (association + cost attribution \u2014 completion still comes from merged PRs or a manual tick)")}catch(e){u(e.message)}}else if(g==="hubs")try{let e=await f("GET",`/api/blueprints/hubs?cwd=${encodeURIComponent(process.cwd())}${r[0]?`&repo=${encodeURIComponent(r[0])}`:""}`);if(!e.hubs?.length)console.log(`[bostrat-blueprint] ${e.repo}: no hub files yet (${e.tracks??0} Track(s) with observed edits)`);else{console.log(`[bostrat-blueprint] ${e.repo}: hub files \u2014 share of ${e.tracks} Track(s) with observed edits that wrote each`);for(let a of e.hubs)console.log(` ${String(Math.round(a.share*100)).padStart(3)}% ${a.path}`);console.log(" (route edits to these through the seam item, or order the items that touch them with `after`)")}}catch(e){u(e.message)}else u("usage: bostrat-blueprint <add|update|show|report|tag|hubs|remains> \u2026 (add [--circuit <ref>] <file.md>)");
2
+ var y=process.env.BOSTRAT_AGENT_URL||`http://127.0.0.1:${process.env.BOSTRAT_AGENT_PORT||3362}`;async function f(e,r,a){let o=await fetch(`${y}${r}`,{method:e,headers:a?{"content-type":"application/json"}:void 0,body:a?JSON.stringify(a):void 0}),i=await o.json().catch(()=>({}));if(!o.ok)throw Object.assign(new Error(i.error||`HTTP ${o.status}`),{status:o.status,data:i});return i}function h(e){console.error(`[bostrat-blueprint] ${e}`),process.exit(1)}function v(e,r){if(console.error(`[bostrat-blueprint] refused: ${e.error}`),e.code==="stale-base"){if(console.error(` plane holds v${e.current}; this copy was built on v${e.yourBase}.`),e.drift?.length){console.error(" item-level difference:");for(let a of e.drift)console.error(` ${String(a.itemId).padEnd(12)} plane: ${String(a.plane).padEnd(7)} file: ${a.file}`)}else console.error(" no item differs \u2014 the newer version changed prose only.");console.error(" Bring this copy up to date, then republish:"),console.error(" git fetch origin && git merge origin/main # siblings' ticks land on main with their PRs"),console.error(" (copy any ticked item you still lack VERBATIM \u2014 never invent a sibling's note)"),console.error(` bostrat-blueprint show && bostrat-blueprint update ${r}`),console.error(` Or, once the file carries everything above: bostrat-blueprint update --base ${e.current} ${r}`)}else e.code==="untick"&&(console.error(` would un-tick: ${e.untick.join(", ")} (plane v${e.current} has them [x]).`),console.error(" Copy their ticks + status notes into the file (merge origin/main first), then republish."));console.error(" --force publishes the file exactly as it is (un-ticking the items above). Only when that is the intent."),process.exit(1)}function $(e){if(e){console.log(` parsed: ${e.sections.recognized} recognized section(s), ${e.items.total} item(s) (${e.items.bindable} bindable)`);for(let r of e.issues??[])console.log(` \u26A0 ${r.message}`)}}var n=process.argv.slice(2),g=n.shift();if(g==="add"||g==="update"){let e=null,r=null,a=null,o=null,i=null,l=!1;for(let t=0;t<n.length;t++)n[t]==="--circuit"?e=n[++t]:n[t]==="--new-circuit"?r=n[++t]:n[t]==="--name"?a=n[++t]:n[t]==="--base"?i=n[++t]:n[t]==="--force"?l=!0:o=n[t];o||h(`usage: bostrat-blueprint ${g} [--circuit <name-or-id>] [--new-circuit "<name>"] [--name "<title>"] [--base <v>] [--force] <file.md>`),i!=null&&!/^[1-9]\d*$/.test(String(i))&&h(`--base takes a version number (what \`show\` prints), got "${i}"`);try{let t=await(await import("node:fs/promises")).readFile(o,"utf8"),d=null,m=null;try{let{execFileSync:s}=await import("node:child_process"),p=await import("node:path"),c=p.resolve(o),b=s("git",["rev-parse","--show-toplevel"],{cwd:p.dirname(c),encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),w=p.relative(b,c);w&&!w.startsWith("..")&&(d=w.split(p.sep).join("/"),m=b)}catch{}let u=await f("POST","/api/blueprints/publish",{cwd:process.cwd(),circuit:e,newCircuit:r,name:a,markdown:t,base:i==null?null:Number(i),force:l,path:d,root:m});console.log(`[bostrat-blueprint] published \u201C${u.blueprint.name}\u201D v${u.blueprint.version} on circuit \u201C${u.circuit.name}\u201D${u.base?` (on v${u.base})`:""}${l?" (forced)":""}`),$(u.report),u.linked&&console.log(` This Track is now in circuit \u201C${u.circuit.name}\u201D (it was in none) \u2014 the blueprint's item ids in a closing message are launch controls from here.`),u.blueprint.version===1&&console.log(" The circuit page now carries this blueprint; PRs/commits mentioning BP ids show as evidence \u2014 tick [x] + a *(done \u2026)* note in the same PR as the item's work.")}catch(t){t.status===409&&t.data?.code&&v(t.data,o),h(t.message)}}else if(g==="show"||g==="report")try{let e=await f("GET",`/api/blueprints/show?cwd=${encodeURIComponent(process.cwd())}${n[0]?`&circuit=${encodeURIComponent(n[0])}`:""}`);if(console.log(`[bostrat-blueprint] \u201C${e.blueprint.name}\u201D v${e.blueprint.version} (circuit ${e.blueprint.circuitId})`),$(e.report),g==="show"){let r=!!e.graph?.edges,a=e.readyAt||"merged",o=new Set,i=s=>{let p=Array.isArray(s.waits)&&s.waits.length?s.waits:null;return p?p.map(c=>c.gate&&c.gate!==a?(o.add(c.gate),`${c.itemId} ${c.gate}`):c.itemId).join(", "):(s.waitsOn??[]).join(", ")},l=s=>s.bindable?s.done?"done":r?s.ready?`ready${s.seam?" \xB7 seam":""}`:`waits on ${i(s)}`:"":"",t=e.items.some(s=>s.bindable&&s.stageLine),d=e.items.map(s=>({i:s,id:s.bindable?s.itemId:"(no id)",pose:l(s)})),m=Math.max(8,...d.map(s=>s.id.length)),u=t?Math.max(0,...d.map(s=>s.pose?s.pose.length+2:0)):0;for(let{i:s,id:p,pose:c}of d){if(!t){console.log(` ${p.padEnd(8)} ${s.sectionKind.padEnd(14)} ${c?`[${c}] `:""}${s.text}`);continue}let b=s.bindable&&s.stageLine?s.stageLine:"";console.log(` ${p.padEnd(m)} ${s.sectionKind.padEnd(14)} ${(c?`[${c}]`:"").padEnd(u)}${u?" ":""}${b}`.trimEnd()),s.text&&console.log(` ${"".padEnd(m)} ${s.text}`)}t&&console.log(" (stage = what the plane observed, with its evidence. merged or higher is a fact \u2014 do not re-verify it; copy it as printed)"),r&&(console.log(e.readyAt?` (readiness = every \`after\` item is at ${e.readyAt} or higher \u2014 this blueprint's ready-at; a What-remains list bolds only ready items)`:" (readiness = every `after` item presents as done; a What-remains list bolds only ready items)"),o.size&&console.log(" (gate words: merged = the dependency's code is on main; released = it is in a cut release; live = it is running on the repo's deploy surfaces. A word beside an id is that edge's own gate; an edge with no word waits at ready-at)"))}}catch(e){h(e.message)}else if(g==="remains"){let e='usage: bostrat-blueprint remains [--asked] [--brief <BP-id>="<one sentence>"]\u2026',r={},a=!1;for(let o=0;o<n.length;o++){if(n[o]==="--asked"){a=!0;continue}n[o]!=="--brief"&&h(`unknown argument "${n[o]}" \u2014 ${e}`);let i=n[++o];i==null&&h(e);let l=i.indexOf("="),t=(l>0?i.slice(0,l):i).trim(),d=l>0?i.slice(l+1):n[++o];(!/^BP-[A-Z0-9]+(?:-[A-Z0-9]+)*$/i.test(t)||!String(d??"").trim())&&h(`--brief takes <BP-id>="<one sentence>", got "${i}" \u2014 ${e}`),r[t.toUpperCase()]=String(d).trim()}try{let o=await f("POST","/api/blueprints/remains",{cwd:process.cwd(),briefs:r,asked:a}),i=o.counts,l=o.show==="now"||o.show==="published";console.log(`[bostrat-blueprint] status card ${l?"posted":"recorded"} for \u201C${o.name??"blueprint"}\u201D v${o.version} \u2014 ${i.done} of ${i.total} merged \xB7 ${i.ready} ready \xB7 ${i.waiting} waiting`),o.mine?.length&&console.log(` this Track: ${o.mine.map(t=>`${t.itemId} (${t.stageLine??t.stage??"open"})`).join(", ")}`);for(let t of o.ready??[])console.log(` ready ${t.itemId} ${t.text}${o.briefs?.[t.itemId]?` \u2014 brief: ${o.briefs[t.itemId]}`:""}`);for(let t of o.waiting??[])console.log(` waiting ${t.itemId} ${t.text} \u2014 waits on ${(t.waits??[]).map(d=>`${d.itemId}${d.gate?` ${d.gate}`:""}`).join(", ")||"(unmet)"}`);!i.ready&&!i.waiting&&console.log(" nothing open \u2014 every item presents done."),console.log(l?o.show==="now"?" The card carries these rows under your closing message (the operator asked). Do not repeat them in your message \u2014 close by saying what you did and end your turn.":" The card carries these rows under your closing message while this Track has no pull request to wait for (this turn published the blueprint). Do not repeat them in your message \u2014 close by saying what you did and end your turn.":" The card shows under the Merged record once this Track's pull request has merged, with your briefs \u2014 not before. Do not list these rows in your message \u2014 close by saying what you did and end your turn.")}catch(o){console.error(`[bostrat-blueprint] no status card recorded: ${o.message}`),console.error(' Fall back to prose: end your message with a short "What remains" list \u2014 "Ready now" items with the FULL id in bold first (**BP-X-I3**: what it still needs), then "Waiting" items (id not bold) with what each waits on.'),process.exit(1)}}else if(g==="tag"){n.length||h("usage: bostrat-blueprint tag <BP-id> [<BP-id>\u2026]");try{let e=await f("POST","/api/blueprints/tag",{cwd:process.cwd(),itemIds:n});console.log(`[bostrat-blueprint] tagged this Track onto ${e.itemIds.join(", ")}`),console.log(" (association + cost attribution \u2014 completion still comes from merged PRs or a manual tick)")}catch(e){h(e.message)}}else if(g==="hubs")try{let e=await f("GET",`/api/blueprints/hubs?cwd=${encodeURIComponent(process.cwd())}${n[0]?`&repo=${encodeURIComponent(n[0])}`:""}`);if(!e.hubs?.length)console.log(`[bostrat-blueprint] ${e.repo}: no hub files yet (${e.tracks??0} Track(s) with observed edits)`);else{console.log(`[bostrat-blueprint] ${e.repo}: hub files \u2014 share of ${e.tracks} Track(s) with observed edits that wrote each`);for(let r of e.hubs)console.log(` ${String(Math.round(r.share*100)).padStart(3)}% ${r.path}`);console.log(" (route edits to these through the seam item, or order the items that touch them with `after`)")}}catch(e){h(e.message)}else h("usage: bostrat-blueprint <add|update|show|report|tag|hubs|remains> \u2026 (add [--circuit <ref>] <file.md>)");
package/bin/bostrat-mock CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import f from"node:fs/promises";import w from"node:path";var g=process.env.BOSTRAT_AGENT_URL||`http://127.0.0.1:${process.env.BOSTRAT_AGENT_PORT||3362}`;async function r(e,a,o,s){let t=await fetch(`${g}${a}`,{method:e,headers:o?{"content-type":s||"application/json"}:void 0,body:o?s?o:JSON.stringify(o):void 0}),c=await t.json().catch(()=>({}));if(!t.ok)throw new Error(c.error||`HTTP ${t.status}`);return c}function i(e){console.error(`[bostrat-mock] ${e}`),process.exit(1)}async function m(e){let a=(await r("GET",`/api/mocks/${e}`)).mock;for(let o=0;o<60&&(a.state==="queued"||a.state==="rendering");o++)await new Promise(s=>setTimeout(s,2e3)),a=(await r("GET",`/api/mocks/${e}`)).mock;return a}function p(e,a){e.state==="error"&&i(`render failed:
3
- ${e.error||"(no detail)"}`),e.state!=="ready"&&i(`render still ${e.state} \u2014 check the gallery later (mock:${e.id})`);let o=e.version>1?` v${e.version}`:"",s=e.versions?.[e.versions.length-1],t=e.width&&e.height?` ${e.width}\xD7${e.height}`:"",c=s?.durationS?` \xB7 ${s.durationS}s`:"";console.log(`[bostrat-mock] ${a}: "${e.name}"${o}${t}${e.dpr>1?` @${e.dpr}x`:""}${c} (mock:${e.id})`),console.log(e.kind==="video"?"The operator plays it in the Track chat and the gallery \u2014 no need to upload or link it anywhere.":"The operator sees it as an image in the Track chat and the gallery \u2014 no need to screenshot or link it.")}var k={".png":"image/png",".mp4":"video/mp4",".webm":"video/webm"};async function h(e){let a=k[w.extname(e).toLowerCase()]||null,o=await f.readFile(e).catch(()=>i(`cannot read ${e}`));return a?{raw:o,type:a}:{html:o.toString("utf8")}}var n=process.argv.slice(2),l=n.shift();if(l==="add"){let e=null,a,o,s=null;for(let t=0;t<n.length;t++)n[t]==="--name"?e=n[++t]:n[t]==="--group"?a=n[++t]:n[t]==="--width"?o=Number(n[++t]):n[t].startsWith("--")||(s=n[t]);(!e||!s)&&i('usage: bostrat-mock add --name "<name>" [--group <id>] [--width N] <file.html|file.png|file.mp4|file.webm>');try{let t=await h(s),c=t.raw?(await r("POST",`/api/mocks?${new URLSearchParams({name:e,cwd:process.cwd(),...a?{group:a}:{}})}`,t.raw,t.type)).mock:(await r("POST","/api/mocks",{name:e,html:t.html,group:a,width:o,cwd:process.cwd()})).mock;p(await m(c.id),"ready")}catch(t){i(t.message)}}else if(l==="update"){let[e,a]=n.filter(o=>!o.startsWith("--"));(!e||!a)&&i("usage: bostrat-mock update <name|id> <file.html|file.png|file.mp4|file.webm>");try{let{mocks:o}=await r("GET","/api/mocks"),s=o.find(d=>d.id===e||d.name===e);s||i(`no mock matching "${e}" \u2014 use \`bostrat-mock ls\`, or \`add\` for a new comp`);let t=await h(a),c=t.raw?(await r("POST",`/api/mocks/${s.id}/update`,t.raw,t.type)).mock:(await r("POST",`/api/mocks/${s.id}/update`,{html:t.html})).mock;p(await m(c.id),"updated")}catch(o){i(o.message)}}else if(l==="ls"){let{mocks:e}=await r("GET","/api/mocks").catch(a=>i(a.message));e.length||console.log("no mocks");for(let a of e){let o=a.readyVersion?` ${a.width}\xD7${a.height}`:"",s=a.version>1?` v${a.version}`:"";console.log(`${a.state.padEnd(9)} ${a.name}${s}${a.group?` [${a.group}]`:""}${o} (mock:${a.id})`)}}else if(l==="rm"){let e=n[0];e||i("usage: bostrat-mock rm <name|id>");let{mocks:a}=await r("GET","/api/mocks").catch(t=>i(t.message)),o=a.find(t=>t.id===e||t.name===e);o||i(`no mock matching "${e}"`);let s=await r("DELETE",`/api/mocks/${o.id}`).catch(t=>i(t.message));console.log(`[bostrat-mock] deleted: ${o.name}`),s.danglingFlows?.length&&console.log(`\u26A0 flows now missing this step \u2014 revise them with \`bostrat-flow update\`: ${s.danglingFlows.map(t=>`"${t.name}" (flow:${t.id})`).join(", ")}`)}else i('usage: bostrat-mock <add|update|ls|rm> \u2026 (add --name "<name>" <file>; update <name|id> <file>)');
2
+ import h from"node:fs/promises";import w from"node:path";var g=process.env.BOSTRAT_AGENT_URL||`http://127.0.0.1:${process.env.BOSTRAT_AGENT_PORT||3362}`;async function c(e,a,o,s){let t=await fetch(`${g}${a}`,{method:e,headers:o?{"content-type":s||"application/json"}:void 0,body:o?s?o:JSON.stringify(o):void 0}),r=await t.json().catch(()=>({}));if(!t.ok)throw new Error(r.error||`HTTP ${t.status}`);return r}function i(e){console.error(`[bostrat-mock] ${e}`),process.exit(1)}async function m(e){let a=(await c("GET",`/api/mocks/${e}`)).mock;for(let o=0;o<60&&(a.state==="queued"||a.state==="rendering");o++)await new Promise(s=>setTimeout(s,2e3)),a=(await c("GET",`/api/mocks/${e}`)).mock;return a}function p(e,a){e.state==="error"&&i(`render failed:
3
+ ${e.error||"(no detail)"}`),e.state!=="ready"&&i(`render still ${e.state} \u2014 check the gallery later (mock:${e.id})`);let o=e.version>1?` v${e.version}`:"",s=e.versions?.[e.versions.length-1],t=e.width&&e.height?` ${e.width}\xD7${e.height}`:"",r=s?.durationS?` \xB7 ${s.durationS}s`:"";console.log(`[bostrat-mock] ${a}: "${e.name}"${o}${t}${e.dpr>1?` @${e.dpr}x`:""}${r} (mock:${e.id})`),console.log(e.kind==="video"?"The operator plays it in the Track chat and the gallery \u2014 no need to upload or link it anywhere.":"The operator sees it as an image in the Track chat and the gallery \u2014 no need to screenshot or link it.")}var k={".png":"image/png",".mp4":"video/mp4",".webm":"video/webm"};async function f(e){let a=k[w.extname(e).toLowerCase()]||null;if(a?.startsWith("video/")){let s=await c("GET","/api/mocks/video-state").catch(()=>null);s&&s.ok===!1&&i(s.reason||"Video mocks are off on this plane.")}let o=await h.readFile(e).catch(()=>i(`cannot read ${e}`));return a?{raw:o,type:a}:{html:o.toString("utf8")}}var n=process.argv.slice(2),l=n.shift();if(l==="add"){let e=null,a,o,s=null;for(let t=0;t<n.length;t++)n[t]==="--name"?e=n[++t]:n[t]==="--group"?a=n[++t]:n[t]==="--width"?o=Number(n[++t]):n[t].startsWith("--")||(s=n[t]);(!e||!s)&&i('usage: bostrat-mock add --name "<name>" [--group <id>] [--width N] <file.html|file.png|file.mp4|file.webm>');try{let t=await f(s),r=t.raw?(await c("POST",`/api/mocks?${new URLSearchParams({name:e,cwd:process.cwd(),...a?{group:a}:{}})}`,t.raw,t.type)).mock:(await c("POST","/api/mocks",{name:e,html:t.html,group:a,width:o,cwd:process.cwd()})).mock;p(await m(r.id),"ready")}catch(t){i(t.message)}}else if(l==="update"){let[e,a]=n.filter(o=>!o.startsWith("--"));(!e||!a)&&i("usage: bostrat-mock update <name|id> <file.html|file.png|file.mp4|file.webm>");try{let{mocks:o}=await c("GET","/api/mocks"),s=o.find(d=>d.id===e||d.name===e);s||i(`no mock matching "${e}" \u2014 use \`bostrat-mock ls\`, or \`add\` for a new comp`);let t=await f(a),r=t.raw?(await c("POST",`/api/mocks/${s.id}/update`,t.raw,t.type)).mock:(await c("POST",`/api/mocks/${s.id}/update`,{html:t.html})).mock;p(await m(r.id),"updated")}catch(o){i(o.message)}}else if(l==="ls"){let{mocks:e}=await c("GET","/api/mocks").catch(a=>i(a.message));e.length||console.log("no mocks");for(let a of e){let o=a.readyVersion?` ${a.width}\xD7${a.height}`:"",s=a.version>1?` v${a.version}`:"";console.log(`${a.state.padEnd(9)} ${a.name}${s}${a.group?` [${a.group}]`:""}${o} (mock:${a.id})`)}}else if(l==="rm"){let e=n[0];e||i("usage: bostrat-mock rm <name|id>");let{mocks:a}=await c("GET","/api/mocks").catch(t=>i(t.message)),o=a.find(t=>t.id===e||t.name===e);o||i(`no mock matching "${e}"`);let s=await c("DELETE",`/api/mocks/${o.id}`).catch(t=>i(t.message));console.log(`[bostrat-mock] deleted: ${o.name}`),s.danglingFlows?.length&&console.log(`\u26A0 flows now missing this step \u2014 revise them with \`bostrat-flow update\`: ${s.danglingFlows.map(t=>`"${t.name}" (flow:${t.id})`).join(", ")}`)}else i('usage: bostrat-mock <add|update|ls|rm> \u2026 (add --name "<name>" <file>; update <name|id> <file>)');
package/bin/bostrat-view CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- var v=process.env.BOSTRAT_AGENT_URL||`http://127.0.0.1:${process.env.BOSTRAT_AGENT_PORT||3362}`;async function r(s,e,i){let t=await fetch(`${v}${e}`,{method:s,headers:i?{"content-type":"application/json"}:void 0,body:i?JSON.stringify(i):void 0}),w=await t.json().catch(()=>({}));if(!t.ok)throw new Error(w.error||`HTTP ${t.status}`);return w}function n(s){console.error(`[bostrat-view] ${s}`),process.exit(1)}var l=process.argv.slice(2),c=l.shift();if(c==="up"){let s=l.indexOf("--");(s===-1||s===l.length-1)&&n('usage: bostrat-view up --name "<name>" [--port N] -- <serve command>');let e=l.slice(0,s),i=l.slice(s+1).join(" "),t=null,w;for(let o=0;o<e.length;o++)e[o]==="--name"?t=e[++o]:e[o]==="--port"&&(w=Number(e[++o]));t||n("--name is required");try{let{view:o}=await r("POST","/api/views",{name:t,cmd:i,port:w,cwd:process.cwd()});o.reused&&console.log(`[bostrat-view] reusing existing view "${o.name}" \u2014 same URL, no new server needed`);let a=o;for(let d=0;d<60&&a.state==="starting";d++)await new Promise(p=>setTimeout(p,2e3)),a=(await r("GET",`/api/views/${o.id}`)).view;a.state==="error"&&n(`server failed to start:
3
- ${a.error||"(no output captured)"}`),console.log(`[bostrat-view] ${a.state}: ${a.url} (view:${a.id})`),a.serveCwd&&console.log(`[bostrat-view] running \`${a.cmd}\` in ${a.serveCwd}`),console.log("Share this URL \u2014 it works from the operator's phone. Do NOT share a localhost URL."),a.state==="starting"&&console.log("(still starting \u2014 the URL shows a holding page until it's up)")}catch(o){n(o.message)}}else if(c==="ls"){let{views:s}=await r("GET","/api/views").catch(e=>n(e.message));s.length||console.log("no views");for(let e of s)console.log(`${e.state.padEnd(9)} ${e.name} \u2014 ${e.url||"(no public URL on this node \u2014 see `bostrat-node doctor`)"} (view:${e.id}, port ${e.port})`),e.cmd&&console.log(`${" ".repeat(10)}\`${e.cmd}\` in ${e.serveCwd||e.cwd}`)}else if(c==="stop"||c==="rm"){let s=l[0];s||n(`usage: bostrat-view ${c} <name|slug|id>`);let{views:e}=await r("GET","/api/views").catch(t=>n(t.message)),i=e.find(t=>t.id===s||t.slug===s||t.name===s);i||n(`no view matching "${s}"`),c==="stop"?(await r("POST",`/api/views/${i.id}/stop`).catch(t=>n(t.message)),console.log(`[bostrat-view] stopped: ${i.name}`)):(await r("DELETE",`/api/views/${i.id}`).catch(t=>n(t.message)),console.log(`[bostrat-view] removed: ${i.name}`))}else n('usage: bostrat-view <up|ls|stop|rm> \u2026 (up --name "<name>" -- <serve command>)');
2
+ var m=process.env.BOSTRAT_AGENT_URL||`http://127.0.0.1:${process.env.BOSTRAT_AGENT_PORT||3362}`;async function r(s,e,a){let t=await fetch(`${m}${e}`,{method:s,headers:a?{"content-type":"application/json"}:void 0,body:a?JSON.stringify(a):void 0}),w=await t.json().catch(()=>({}));if(!t.ok)throw new Error(w.error||`HTTP ${t.status}`);return w}function i(s){console.error(`[bostrat-view] ${s}`),process.exit(1)}var l=process.argv.slice(2),c=l.shift();if(c==="up"){let s=l.indexOf("--");(s===-1||s===l.length-1)&&i('usage: bostrat-view up --name "<name>" [--port N] -- <serve command>');let e=l.slice(0,s),a=l.slice(s+1).join(" "),t=null,w;for(let o=0;o<e.length;o++)e[o]==="--name"?t=e[++o]:e[o]==="--port"&&(w=Number(e[++o]));t||i("--name is required");try{let{view:o,shareOff:d}=await r("POST","/api/views",{name:t,cmd:a,port:w,cwd:process.cwd()});o.reused&&console.log(`[bostrat-view] reusing existing view "${o.name}" \u2014 same URL, no new server needed`);let n=o;for(let p=0;p<60&&n.state==="starting";p++)await new Promise(v=>setTimeout(v,2e3)),n=(await r("GET",`/api/views/${o.id}`)).view;n.state==="error"&&i(`server failed to start:
3
+ ${n.error||"(no output captured)"}`),console.log(`[bostrat-view] ${n.state}: ${n.url} (view:${n.id})`),n.serveCwd&&console.log(`[bostrat-view] running \`${n.cmd}\` in ${n.serveCwd}`),console.log(d?`This URL opens on this machine only. ${d}`:"Share this URL \u2014 it works from the operator's phone. Do NOT share a localhost URL."),n.state==="starting"&&console.log("(still starting \u2014 the URL shows a holding page until it's up)")}catch(o){i(o.message)}}else if(c==="ls"){let{views:s}=await r("GET","/api/views").catch(e=>i(e.message));s.length||console.log("no views");for(let e of s)console.log(`${e.state.padEnd(9)} ${e.name} \u2014 ${e.url||"(no public URL on this node \u2014 see `bostrat-node doctor`)"} (view:${e.id}, port ${e.port})`),e.cmd&&console.log(`${" ".repeat(10)}\`${e.cmd}\` in ${e.serveCwd||e.cwd}`)}else if(c==="stop"||c==="rm"){let s=l[0];s||i(`usage: bostrat-view ${c} <name|slug|id>`);let{views:e}=await r("GET","/api/views").catch(t=>i(t.message)),a=e.find(t=>t.id===s||t.slug===s||t.name===s);a||i(`no view matching "${s}"`),c==="stop"?(await r("POST",`/api/views/${a.id}/stop`).catch(t=>i(t.message)),console.log(`[bostrat-view] stopped: ${a.name}`)):(await r("DELETE",`/api/views/${a.id}`).catch(t=>i(t.message)),console.log(`[bostrat-view] removed: ${a.name}`))}else c==="share"?(await r("POST","/api/views/share").catch(s=>i(s.message)),i("no share link was minted")):i('usage: bostrat-view <up|ls|stop|rm|share> \u2026 (up --name "<name>" -- <serve command>)');