@team-semicolon/semicolony-cli 4.18.109 → 4.18.111

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.
Files changed (2) hide show
  1. package/dist/bundle.js +3 -3
  2. package/package.json +1 -1
package/dist/bundle.js CHANGED
@@ -1524,17 +1524,17 @@ ${o}
1524
1524
  `),we.fsyncSync(r)}finally{we.closeSync(r)}return()=>{try{let n=we.lstatSync(t.updateLock);if(!n.isFile()||n.isSymbolicLink())throw new Error("Worker-agent update lock became unsafe");we.unlinkSync(t.updateLock)}catch(n){if(n.code!=="ENOENT")throw n}}}function O7n(t){let e={};for(let r of t)e[`profile:${r.actor_id}:context`]=r.context.sha256,e[`profile:${r.actor_id}:skills`]=Azt(r),e[`profile:${r.actor_id}:tools`]=ba(sTe(r)),e[`profile:${r.actor_id}:mcp`]=ba(rTe(r.actor_id));return e}function UE(t,e,r=384){we.mkdirSync(Rt.dirname(t),{recursive:!0});let n=`${t}.${process.pid}.tmp`;we.writeFileSync(n,e,{mode:r}),we.chmodSync(n,r),we.renameSync(n,t)}function mzt(t,e){let r=oTe(t,e);for(let c of[r.root,r.soul,r.skills,r.tools,r.config])tc(t,c);let n=we.lstatSync(r.soul),i=we.lstatSync(r.tools),s=we.lstatSync(r.config);if(!n.isFile()||n.isSymbolicLink()||(n.mode&511)!==384)throw new Error(`Worker-agent ${e.actor_id} staged context mode is invalid`);if(!i.isFile()||i.isSymbolicLink()||(i.mode&511)!==384)throw new Error(`Worker-agent ${e.actor_id} staged tools mode is invalid`);if(!s.isFile()||s.isSymbolicLink()||(s.mode&511)!==384)throw new Error(`Worker-agent ${e.actor_id} staged config mode is invalid`);let o=q7(we.readFileSync(r.soul,"utf8"),e.actor_id);if(o===null||ba(`${o}
1525
1525
  `)!==e.context.sha256)throw new Error(`Worker-agent ${e.actor_id} staged context digest mismatch`);let a=e.skills.map(c=>{let l=Rt.join(r.skills,c.name,"SKILL.md");tc(t,l);let u=we.lstatSync(l);if(!u.isFile()||u.isSymbolicLink()||(u.mode&511)!==420)throw new Error(`Worker-agent ${e.actor_id} staged skill mode is invalid`);let d=we.readFileSync(l);return RI(d,`Worker-agent ${e.actor_id} staged skill`),{name:c.name,sha256:ba(d)}});if(ba(Gs(a))!==Azt(e))throw new Error(`Worker-agent ${e.actor_id} staged skill digest mismatch`);if(ba(we.readFileSync(r.tools))!==ba(sTe(e)))throw new Error(`Worker-agent ${e.actor_id} staged tools digest mismatch`);if(ba(F7(we.readFileSync(r.config,"utf8"),e.actor_id)??"")!==ba(rTe(e.actor_id)))throw new Error(`Worker-agent ${e.actor_id} staged MCP projection mismatch`);RI(we.readFileSync(r.soul),"Worker-agent staged context"),RI(we.readFileSync(r.tools),"Worker-agent staged tools"),RI(we.readFileSync(r.config),"Worker-agent staged config")}function P7n(t,e,r){let n=Rt.join(t.stagingRoot,r.releaseId),i=Rt.dirname(Rt.dirname(t.stagingRoot));tc(i,n),we.mkdirSync(t.stagingRoot,{recursive:!0,mode:448});try{we.mkdirSync(n,{mode:448})}catch(s){throw s.code==="EEXIST"?new Error(`Worker-agent staging path already exists: ${n}`):s}try{for(let s of r.profiles){QL(e.hermes_home,s);let o=iR(e.hermes_home,s),a=oTe(n,s);UE(a.soul,pzt(we.readFileSync(o.soul,"utf8"),s.actor_id,s.context.content)),we.mkdirSync(a.skills,{recursive:!0,mode:448});for(let c of s.skills){let l=Rt.join(a.skills,c.name,"SKILL.md");we.mkdirSync(Rt.dirname(l),{recursive:!0,mode:448}),we.writeFileSync(l,c.content,{mode:420})}UE(a.tools,sTe(s)),UE(a.config,azt(we.readFileSync(o.config,"utf8"),s.actor_id)),mzt(n,s)}return n}catch(s){throw we.rmSync(n,{recursive:!0,force:!0}),s}}function yzt(t){let e=[],r=n=>{for(let i of we.readdirSync(n).sort()){let s=Rt.join(n,i),o=Rt.relative(t,s),a=we.lstatSync(s);if(a.isSymbolicLink())throw new Error("Worker-agent backup must not contain symlinks");if(a.isDirectory())r(s);else if(a.isFile())e.push({path:o,sha256:ba(we.readFileSync(s)),mode:a.mode&511});else throw new Error("Worker-agent backup contains an unsupported file type")}};return r(t),e}function N7n(t,e,r,n){let i=Rt.join(t.backups,`${r.releaseId}-${n.toISOString().replace(/[:.]/g,"-")}`);tc(t.root,i),we.mkdirSync(t.backups,{recursive:!0,mode:448});try{we.mkdirSync(i,{mode:448})}catch(s){throw s.code==="EEXIST"?new Error(`Worker-agent backup receipt already exists: ${i}`):s}try{let s={schema_version:1,installation_id:lg,release_id:r.releaseId,release_version:r.version,manifest_sha256:r.manifestSha256,created_at:n.toISOString(),actors:[],had_release_state:we.existsSync(t.releaseState),files:[]};for(let a of r.profiles){let c=iR(e.hermes_home,a);QL(e.hermes_home,a);let l=Rt.join(i,a.actor_id);we.mkdirSync(l),we.copyFileSync(c.soul,Rt.join(l,"SOUL.md"));let u=we.existsSync(c.skills),d=we.existsSync(c.tools);u&&we.cpSync(c.skills,Rt.join(l,"skills"),{recursive:!0}),d&&we.copyFileSync(c.tools,Rt.join(l,"tools.json")),we.copyFileSync(c.config,Rt.join(l,"config.yaml")),s.actors.push({actor_id:a.actor_id,runtime_profile:a.runtime_profile,had_skills:u,had_tools:d})}s.had_release_state&&we.copyFileSync(t.releaseState,Rt.join(i,"release-state.json")),s.files=yzt(i);let o={...s,receipt_sha256:ba(Gs(s))};return dy(Rt.join(i,"receipt.json"),o),i}catch(s){throw we.rmSync(i,{recursive:!0,force:!0}),s}}function bzt(t){let e=Rt.join(t,"receipt.json");tc(t,e);let r=we.lstatSync(e);if(!r.isFile()||r.isSymbolicLink()||(r.mode&511)!==384)throw new Error("Worker-agent backup receipt file is unsafe");let n=JSON.parse(we.readFileSync(e,"utf8"));if(!nTe(n))throw new Error("Worker-agent backup receipt must be an object");if(iTe(n,["schema_version","installation_id","release_id","release_version","manifest_sha256","created_at","actors","had_release_state","files","receipt_sha256"],"Worker-agent backup receipt"),n.schema_version!==1||n.installation_id!==lg||typeof n.release_id!="string"||typeof n.release_version!="string"||typeof n.manifest_sha256!="string"||!/^[a-f0-9]{64}$/i.test(n.manifest_sha256)||typeof n.created_at!="string"||!Number.isFinite(Date.parse(n.created_at))||typeof n.had_release_state!="boolean"||!Array.isArray(n.actors)||!Array.isArray(n.files)||typeof n.receipt_sha256!="string")throw new Error("Worker-agent backup receipt fields are invalid");let i=n.actors;if(i.length!==dd.length)throw new Error("Worker-agent backup actor set is invalid");for(let[l,u]of dd.entries()){let d=i[l];if(!nTe(d))throw new Error("Worker-agent backup actor entry is invalid");if(iTe(d,["actor_id","runtime_profile","had_skills","had_tools"],"Worker-agent backup actor"),d.actor_id!==u.actor_id||d.runtime_profile!==u.runtime_profile||typeof d.had_skills!="boolean"||typeof d.had_tools!="boolean")throw new Error("Worker-agent backup actor binding is invalid")}let s=n.files;for(let l of s){if(!nTe(l))throw new Error("Worker-agent backup file entry is invalid");if(iTe(l,["path","sha256","mode"],"Worker-agent backup file"),typeof l.path!="string"||Rt.isAbsolute(l.path)||Rt.normalize(l.path)!==l.path||l.path.startsWith("..")||typeof l.sha256!="string"||!/^[a-f0-9]{64}$/i.test(l.sha256)||typeof l.mode!="number")throw new Error("Worker-agent backup file entry is invalid")}let{receipt_sha256:o,...a}=n;if(o!==ba(Gs(a)))throw new Error("Worker-agent backup receipt digest mismatch");let c=yzt(t).filter(l=>l.path!=="receipt.json");if(Gs(c)!==Gs(s))throw new Error("Worker-agent backup file digest mismatch");return n}function Ezt(t,e,r,n){let i=bzt(t);for(let s of r){let o=iR(e.hermes_home,s);QL(e.hermes_home,s);let a=Rt.join(t,s.actor_id),c=i.actors.find(d=>d.actor_id===s.actor_id);if(!c||c.runtime_profile!==s.runtime_profile)throw new Error("Worker-agent backup actor binding does not match restore target");let l=i.files.find(d=>d.path===`${s.actor_id}/SOUL.md`);if(!l)throw new Error("Worker-agent backup is missing the profile context");UE(o.soul,we.readFileSync(Rt.join(a,"SOUL.md"),"utf8"),l.mode),we.rmSync(o.skills,{recursive:!0,force:!0}),c.had_skills&&we.cpSync(Rt.join(a,"skills"),o.skills,{recursive:!0}),we.rmSync(o.tools,{force:!0}),c.had_tools&&we.copyFileSync(Rt.join(a,"tools.json"),o.tools);let u=i.files.find(d=>d.path===`${s.actor_id}/config.yaml`);if(!u)throw new Error("Worker-agent backup is missing the profile config");UE(o.config,we.readFileSync(Rt.join(a,"config.yaml"),"utf8"),u.mode)}tc(Rt.dirname(n),n),we.rmSync(n,{force:!0}),i.had_release_state&&we.copyFileSync(Rt.join(t,"release-state.json"),n)}function L7n(t,e,r,n){for(let i of r){let s=iR(t,i),o=oTe(e,i);QL(t,i),mzt(e,i);let a=we.lstatSync(s.soul).mode&511;UE(s.soul,we.readFileSync(o.soul,"utf8"),a),n?.(`profile:${i.actor_id}:context`);let c=`${s.skills}.${process.pid}.new`;we.rmSync(c,{recursive:!0,force:!0}),we.cpSync(o.skills,c,{recursive:!0}),we.rmSync(s.skills,{recursive:!0,force:!0}),we.mkdirSync(Rt.dirname(s.skills),{recursive:!0}),we.renameSync(c,s.skills),n?.(`profile:${i.actor_id}:skills`),UE(s.tools,we.readFileSync(o.tools,"utf8")),n?.(`profile:${i.actor_id}:tools`);let l=we.lstatSync(s.config).mode&511;UE(s.config,we.readFileSync(o.config,"utf8"),l),n?.(`profile:${i.actor_id}:mcp`)}}async function wzt(t={}){let e=t.env??process.env,r=Rt.resolve(t.homeDir??e.HOME??hzt.homedir()),n=FE(r),i=tR(n.installationState);if(!i)throw new Error("Worker-agent installation state is missing");let s=t.client??lp({env:e,surface:t.surface}),o=lzt(await s.fetchActiveRelease()),a=dzt(i.hermes_home,o.profiles),c=O7n(o.profiles),l=Object.keys(c).map(h=>({id:h,current_digest:a[h]??null,desired_digest:c[h],action:a[h]===c[h]?"unchanged":a[h]===null?"create":"update"})),u=rR(n.releaseState)?.applied_release_version??null;if(t.check)return{mode:"check",status:l.every(h=>h.action==="unchanged")?"pass":"available",release_id:o.releaseId,manifest_sha256:o.manifestSha256,installed:u,target:o.version,targets:l};let d=(t.now??(()=>new Date))(),f=gzt(n,d);try{let h=lzt(await s.fetchActiveRelease());if(h.releaseId!==o.releaseId||h.version!==o.version||h.manifestSha256!==o.manifestSha256)throw new Error("Worker-agent active release changed between plan and apply");let A=dzt(i.hermes_home,h.profiles),g=Object.keys(c).map(b=>({id:b,current_digest:A[b]??null,desired_digest:c[b],action:A[b]===c[b]?"unchanged":A[b]===null?"create":"update"})),m=P7n(n,i,h),y;try{y=N7n(n,i,h,d)}catch(b){throw we.rmSync(m,{recursive:!0,force:!0}),b}try{L7n(i.hermes_home,m,h.profiles,t.afterTargetApply);let b={schema_version:2,profile_id:"semo-ops-worker-agent",installation_id:"hermes-principals@hermes",applied_release_id:h.releaseId,applied_release_version:h.version,manifest_sha256:h.manifestSha256,managed_target_digests:c,backup_receipt:y,applied_at:d.toISOString(),last_doctor_status:"pass",last_doctor_at:d.toISOString(),required_doctor_checks:[...h.requiredChecks]},E=await(t.doctor??(async()=>{let{runWorkerAgentDoctor:I}=await Promise.resolve().then(()=>(aTe(),Czt));return I({homeDir:r,requiredChecks:h.requiredChecks,expectedReleaseState:b})}))();if(E.status!=="pass")throw new Error("Worker-agent doctor did not pass after apply");dy(n.releaseState,b);let _=await s.reportUpdate({release_id:h.releaseId,manifest_sha256:h.manifestSha256,doctor_status:"pass",doctor_summary:{checks:E.checks.map(({id:I,status:Q})=>({id:I,status:Q}))},applied_at:d.toISOString()});if(!_.reported||!_.applied)throw new Error("Worker-agent release report was not applied");return we.rmSync(m,{recursive:!0,force:!0}),{mode:"update",status:"pass",release_id:h.releaseId,manifest_sha256:h.manifestSha256,installed:h.version,target:h.version,targets:g.map(I=>({...I,current_digest:I.desired_digest,action:"unchanged"}))}}catch(b){let w=!1;try{Ezt(y,i,h.profiles,n.releaseState),w=!0,we.rmSync(m,{recursive:!0,force:!0})}catch{throw dy(n.rollbackFailure,{schema_version:1,release_id:h.releaseId,installation_id:lg,staging_path:m,backup_receipt:y,rollback_status:"fail",failed_at:d.toISOString()}),new Error(`Worker-agent restore failed; preserved staging=${m} backup=${y}`)}dy(n.rollbackFailure,{schema_version:1,release_id:h.releaseId,installation_id:lg,rollback_status:"restored",failed_at:d.toISOString()});try{await s.reportUpdate({release_id:h.releaseId,manifest_sha256:h.manifestSha256,doctor_status:"fail",doctor_summary:{phase:"apply",rollback:w?"restored":"fail"}})}catch{}throw b}}finally{f()}}function _zt(t){return[`SEMO Ops Worker-agent ${t.mode}: ${t.status}`,` release=${t.release_id} manifest_sha256=${t.manifest_sha256}`,` installed=${t.installed??"none"} target=${t.target}`,...t.targets.map(e=>` ${e.action} ${e.id}`)].join(`
1526
1526
  `)}var fzt,we,hzt,Rt,U7,ba,Azt,sTe,TI,j7=H(()=>{"use strict";fzt=require("node:crypto"),we=v(require("node:fs")),hzt=v(require("node:os")),Rt=v(require("node:path"));bB();Mh();D7();SL();czt();U7=(t,e)=>`<!-- SEMO_OPS_WORKER_AGENT_RELEASE:${t}:${e} -->`,ba=t=>(0,fzt.createHash)("sha256").update(t).digest("hex"),Azt=t=>ba(Gs(t.skills.map(({name:e,sha256:r})=>({name:e,sha256:r})))),sTe=t=>`${JSON.stringify({tools:t.tools},null,2)}
1527
- `;TI={extractManaged:q7,replaceManaged:pzt,restoreBackup:Ezt,validateWorkerAgentBackupReceipt:bzt,acquireUpdateLock:gzt,extractWorkerAgentMcp:F7}});function DL(t){return new Error(t?`Worker-agent KB request failed with HTTP ${t}`:"Worker-agent KB request failed")}function vzt(t,e){let r=sR.join(t,`${e}.token`),n=$7.lstatSync(r);if(!n.isFile()||n.isSymbolicLink()||n.mode&63)throw new Error(`${e} credential file must be a private regular file`);let i=$7.readFileSync(r,"utf8").trim();if(!new RegExp(`^wck_${e}_[A-Za-z0-9_-]{32,}$`).test(i))throw new Error(`${e} credential has an invalid format`);return i}function kzt(t){if(!sR.isAbsolute(t)||sR.normalize(t)!==t)throw new Error("credentials directory must be a normalized absolute path");let e=vzt(t,"semi"),r=vzt(t,"colony");if((0,RL.createHash)("sha256").update(e).digest("hex")===(0,RL.createHash)("sha256").update(r).digest("hex"))throw new Error("actor credentials must be distinct");return{semi:e,colony:r}}function zl(t){let e=new URL(t),r=e.protocol==="http:"&&["127.0.0.1","::1","localhost"].includes(e.hostname);if(e.username||e.password||e.search||e.hash||e.protocol!=="https:"&&!r)throw new Error("Gateway URL must be HTTPS or loopback HTTP without credentials/query/fragment");return e.toString().replace(/\/$/,"")}async function xzt(t){let e=Date.now(),r=(0,RL.randomUUID)(),n=new AbortController,i=setTimeout(()=>n.abort(),t.timeoutMs??5e3);try{let s=await(t.fetchImpl??fetch)(`${zl(t.baseUrl)}${t.operation==="kb_get"?"/kb/get":"/kb/search"}`,{method:"POST",headers:{authorization:`Bearer ${t.tokens[t.actor]}`,"content-type":"application/json","x-correlation-id":r},body:JSON.stringify(t.args),signal:n.signal});if(Number(s.headers.get("content-length")??0)>Izt)throw DL();let a=await s.text();if(!s.ok)throw DL(s.status);if(Buffer.byteLength(a)>Izt||F7n.test(a))throw DL();let c;try{c=JSON.parse(a)}catch{throw DL()}return{correlation_id:r,actor:t.actor,operation:t.operation,status:"success",latency_ms:Date.now()-e,result:c}}catch(s){throw s instanceof Error&&/^Worker-agent KB request failed/.test(s.message)?s:DL()}finally{clearTimeout(i)}}var RL,$7,sR,F7n,Izt,oR=H(()=>{"use strict";RL=require("node:crypto"),$7=v(require("node:fs")),sR=v(require("node:path")),F7n=/\bwck_[A-Za-z0-9_-]{20,}\b|\bAuthorization\b|postgres(?:ql)?:\/\//i,Izt=1024*1024});function fy(t,e){return new Error(e?`Worker-agent ${t} request failed with HTTP ${e}`:`Worker-agent ${t} request failed`)}async function Szt(t,e,r,n,i){let s=new AbortController,o=setTimeout(()=>s.abort(),r.timeoutMs??5e3);try{let a=await(r.fetchImpl??fetch)(`${zl(r.baseUrl)}${e}`,{method:"POST",headers:{authorization:`Bearer ${r.tokens[r.actor]}`,"content-type":"application/json","x-correlation-id":i},body:JSON.stringify(n),signal:s.signal});if(Number(a.headers.get("content-length")??0)>Bzt)throw fy(t);let c=await a.text();if(!a.ok)throw fy(t,a.status);if(Buffer.byteLength(c)>Bzt||U7n.test(c))throw fy(t);let l;try{l=JSON.parse(c)}catch{throw fy(t)}if(!l||typeof l!="object"||Array.isArray(l))throw fy(t);return l}finally{clearTimeout(o)}}async function Qzt(t){let e=Date.now(),r=(0,cTe.randomUUID)();try{let n=await Szt("action_list","/action/list",t,t.payload,r);if(!Array.isArray(n.items))throw fy("action_list");return{correlation_id:r,actor:t.actor,operation:"action_list",status:"success",latency_ms:Date.now()-e,items:n.items}}catch(n){throw n instanceof Error&&/^Worker-agent action_list request failed/.test(n.message)?n:fy("action_list")}}async function Dzt(t){let e=Date.now(),r=(0,cTe.randomUUID)();try{let i=(await Szt("action_create","/action/create",t,t.payload,r)).action_item_id;if(typeof i!="string"||i.length<36)throw fy("action_create");return{correlation_id:r,actor:t.actor,operation:"action_create",status:"success",latency_ms:Date.now()-e,action_item_id:i}}catch(n){throw n instanceof Error&&/^Worker-agent action_create request failed/.test(n.message)?n:fy("action_create")}}var cTe,Bzt,U7n,Rzt=H(()=>{"use strict";cTe=require("node:crypto");oR();Bzt=256*1024,U7n=/\bwck_[A-Za-z0-9_-]{20,}\b|\bAuthorization\b|postgres(?:ql)?:\/\/|\bDATABASE_URL\b|\bSEMO_OPS_WORKER_KB_TOKEN\b/i});function aR(t){if(!qE.isAbsolute(t)||qE.normalize(t)!==t)throw new Error("feedback spool root must be a normalized absolute path");return t}function uTe(t){let e=aR(t);ct.existsSync(e)||ct.mkdirSync(e,{recursive:!0,mode:448});let r=ct.lstatSync(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("feedback spool root is unsafe");return ct.chmodSync(e,448),e}function H7(t,e){return qE.join(aR(t),`${e}.jsonl`)}function Mzt(t){return qE.join(aR(t),".replay.lock")}function dTe(t){let e=ct.lstatSync(t);if(!e.isFile()||e.isSymbolicLink())throw new Error("feedback spool file is unsafe");if(e.mode&63)throw new Error("feedback spool file is not private")}function j7n(t){ct.existsSync(t)&&dTe(t);let e=ct.constants.O_WRONLY|ct.constants.O_CREAT|ct.constants.O_APPEND|(ct.constants.O_NOFOLLOW??0),r=ct.openSync(t,e,384);if(!ct.fstatSync(r).isFile())throw ct.closeSync(r),new Error("feedback spool file is unsafe");return ct.fchmodSync(r,384),r}function $7n(t,e){let r=uTe(t),n=H7(r,e.actor),i=JSON.stringify(e);if(MI.test(i))throw new Error("feedback spool record is unsafe");let s=j7n(n);try{ct.writeSync(s,`${i}
1527
+ `;TI={extractManaged:q7,replaceManaged:pzt,restoreBackup:Ezt,validateWorkerAgentBackupReceipt:bzt,acquireUpdateLock:gzt,extractWorkerAgentMcp:F7}});function DL(t){return new Error(t?`Worker-agent KB request failed with HTTP ${t}`:"Worker-agent KB request failed")}function vzt(t,e){let r=sR.join(t,`${e}.token`),n=$7.lstatSync(r);if(!n.isFile()||n.isSymbolicLink()||n.mode&63)throw new Error(`${e} credential file must be a private regular file`);let i=$7.readFileSync(r,"utf8").trim();if(!new RegExp(`^wck_${e}_[A-Za-z0-9_-]{32,}$`).test(i))throw new Error(`${e} credential has an invalid format`);return i}function kzt(t){if(!sR.isAbsolute(t)||sR.normalize(t)!==t)throw new Error("credentials directory must be a normalized absolute path");let e=vzt(t,"semi"),r=vzt(t,"colony");if((0,RL.createHash)("sha256").update(e).digest("hex")===(0,RL.createHash)("sha256").update(r).digest("hex"))throw new Error("actor credentials must be distinct");return{semi:e,colony:r}}function zl(t){let e=new URL(t),r=e.protocol==="http:"&&["127.0.0.1","::1","localhost"].includes(e.hostname);if(e.username||e.password||e.search||e.hash||e.protocol!=="https:"&&!r)throw new Error("Gateway URL must be HTTPS or loopback HTTP without credentials/query/fragment");return e.toString().replace(/\/$/,"")}async function xzt(t){let e=Date.now(),r=(0,RL.randomUUID)(),n=new AbortController,i=setTimeout(()=>n.abort(),t.timeoutMs??5e3);try{let s=await(t.fetchImpl??fetch)(`${zl(t.baseUrl)}${t.operation==="kb_get"?"/kb/get":"/kb/search"}`,{method:"POST",headers:{authorization:`Bearer ${t.tokens[t.actor]}`,"content-type":"application/json","x-correlation-id":r},body:JSON.stringify(t.args),signal:n.signal});if(Number(s.headers.get("content-length")??0)>Izt)throw DL();let a=await s.text();if(!s.ok)throw DL(s.status);if(Buffer.byteLength(a)>Izt||F7n.test(a))throw DL();let c;try{c=JSON.parse(a)}catch{throw DL()}return{correlation_id:r,actor:t.actor,operation:t.operation,status:"success",latency_ms:Date.now()-e,result:c}}catch(s){throw s instanceof Error&&/^Worker-agent KB request failed/.test(s.message)?s:DL()}finally{clearTimeout(i)}}var RL,$7,sR,F7n,Izt,oR=H(()=>{"use strict";RL=require("node:crypto"),$7=v(require("node:fs")),sR=v(require("node:path")),F7n=/\bwck_[A-Za-z0-9_-]{20,}\b|\bAuthorization\b|postgres(?:ql)?:\/\//i,Izt=1024*1024});function fy(t,e){return new Error(e?`Worker-agent ${t} request failed with HTTP ${e}`:`Worker-agent ${t} request failed`)}async function Szt(t,e,r,n,i){let s=new AbortController,o=setTimeout(()=>s.abort(),r.timeoutMs??5e3);try{let a=await(r.fetchImpl??fetch)(`${zl(r.baseUrl)}${e}`,{method:"POST",headers:{authorization:`Bearer ${r.tokens[r.actor]}`,"content-type":"application/json","x-correlation-id":i},body:JSON.stringify(n),signal:s.signal});if(Number(a.headers.get("content-length")??0)>Bzt)throw fy(t);let c=await a.text();if(!a.ok)throw fy(t,a.status);if(Buffer.byteLength(c)>Bzt||U7n.test(c))throw fy(t);let l;try{l=JSON.parse(c)}catch{throw fy(t)}if(!l||typeof l!="object"||Array.isArray(l))throw fy(t);return l}finally{clearTimeout(o)}}async function Qzt(t){let e=Date.now(),r=(0,cTe.randomUUID)();try{let n=await Szt("action_list","/action/list",t,t.payload,r);if(!Array.isArray(n.items))throw fy("action_list");return{correlation_id:r,actor:t.actor,operation:"action_list",status:"success",latency_ms:Date.now()-e,items:n.items}}catch(n){throw n instanceof Error&&/^Worker-agent action_list request failed/.test(n.message)?n:fy("action_list")}}async function Dzt(t){let e=Date.now(),r=(0,cTe.randomUUID)();try{let{project:n,...i}=t.payload,s={...i,project_domain:n},a=(await Szt("action_create","/action/create",t,s,r)).action_item_id;if(typeof a!="string"||a.length<36)throw fy("action_create");return{correlation_id:r,actor:t.actor,operation:"action_create",status:"success",latency_ms:Date.now()-e,action_item_id:a}}catch(n){throw n instanceof Error&&/^Worker-agent action_create request failed/.test(n.message)?n:fy("action_create")}}var cTe,Bzt,U7n,Rzt=H(()=>{"use strict";cTe=require("node:crypto");oR();Bzt=256*1024,U7n=/\bwck_[A-Za-z0-9_-]{20,}\b|\bAuthorization\b|postgres(?:ql)?:\/\/|\bDATABASE_URL\b|\bSEMO_OPS_WORKER_KB_TOKEN\b/i});function aR(t){if(!qE.isAbsolute(t)||qE.normalize(t)!==t)throw new Error("feedback spool root must be a normalized absolute path");return t}function uTe(t){let e=aR(t);ct.existsSync(e)||ct.mkdirSync(e,{recursive:!0,mode:448});let r=ct.lstatSync(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("feedback spool root is unsafe");return ct.chmodSync(e,448),e}function H7(t,e){return qE.join(aR(t),`${e}.jsonl`)}function Mzt(t){return qE.join(aR(t),".replay.lock")}function dTe(t){let e=ct.lstatSync(t);if(!e.isFile()||e.isSymbolicLink())throw new Error("feedback spool file is unsafe");if(e.mode&63)throw new Error("feedback spool file is not private")}function j7n(t){ct.existsSync(t)&&dTe(t);let e=ct.constants.O_WRONLY|ct.constants.O_CREAT|ct.constants.O_APPEND|(ct.constants.O_NOFOLLOW??0),r=ct.openSync(t,e,384);if(!ct.fstatSync(r).isFile())throw ct.closeSync(r),new Error("feedback spool file is unsafe");return ct.fchmodSync(r,384),r}function $7n(t,e){let r=uTe(t),n=H7(r,e.actor),i=JSON.stringify(e);if(MI.test(i))throw new Error("feedback spool record is unsafe");let s=j7n(n);try{ct.writeSync(s,`${i}
1528
1528
  `),ct.fsyncSync(s)}finally{ct.closeSync(s)}return fTe(r,e.actor).length}function Ozt(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t,r=new Set(["category","summary","failed_rule","severity","evidence","proposed_fix"]);if(Object.keys(e).some(i=>!r.has(i))||!["context-failure","env-drift","policy-gap","tooling"].includes(String(e.category)))return!1;let n=(i,s,o)=>typeof i=="string"&&i.length>=s&&i.length<=o&&i.trim()===i&&![...i].some(a=>a.charCodeAt(0)<32)&&!MI.test(i);return!n(e.summary,8,500)||e.severity!=null&&!["low","normal","high","urgent"].includes(String(e.severity))||e.failed_rule!=null&&!n(e.failed_rule,1,500)||e.evidence!=null&&!n(e.evidence,1,1e4)||e.proposed_fix!=null&&!n(e.proposed_fix,1,1e4)?!1:!MI.test(JSON.stringify(e))}function W7n(t,e){if(!t||typeof t!="object"||Array.isArray(t))return!1;let r=t;return Object.keys(r).sort().join(",")===["actor","attempts","payload","queued_at","schema_version"].sort().join(",")&&r.schema_version===1&&r.actor===e&&typeof r.queued_at=="string"&&!Number.isNaN(Date.parse(r.queued_at))&&Number.isInteger(r.attempts)&&r.attempts>=1&&r.attempts<=Number.MAX_SAFE_INTEGER&&Ozt(r.payload)}function fTe(t,e){let r=aR(t),n=H7(r,e);if(!ct.existsSync(n))return[];dTe(n);let i=ct.readFileSync(n,"utf8");if(!i)return[];if(MI.test(i))throw new Error("feedback spool file is unsafe");return(i.endsWith(`
1529
1529
  `)?i.slice(0,-1).split(`
1530
1530
  `):i.split(`
1531
1531
  `)).map(o=>{let a;try{a=JSON.parse(o)}catch{throw new Error("feedback spool record is invalid")}if(!W7n(a,e))throw new Error("feedback spool record is invalid");return a})}function Pzt(t,e){if(aR(t),!ct.existsSync(t))return 0;let r=ct.lstatSync(t);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("feedback spool root is unsafe");return fTe(t,e).length}function G7n(t,e,r){let n=uTe(t),i=H7(n,e);ct.existsSync(i)&&dTe(i);let s=qE.join(n,`.${e}.${(0,W7.randomUUID)()}.tmp`),o=r.length?`${r.map(c=>JSON.stringify(c)).join(`
1532
1532
  `)}
1533
- `:"";if(MI.test(o))throw new Error("feedback spool record is unsafe");let a;try{a=ct.openSync(s,ct.constants.O_WRONLY|ct.constants.O_CREAT|ct.constants.O_EXCL|(ct.constants.O_NOFOLLOW??0),384),ct.writeSync(a,o),ct.fsyncSync(a),ct.closeSync(a),a=void 0,ct.renameSync(s,i),ct.chmodSync(i,384)}finally{a!==void 0&&ct.closeSync(a),ct.existsSync(s)&&ct.rmSync(s)}}function H7n(t){if(Buffer.byteLength(t)>G7||MI.test(t))return null;let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object"||Array.isArray(e))return null;let r=e;return r.ok!==!0||typeof r.slug!="string"||!/^[a-z0-9][a-z0-9-]{0,239}$/.test(r.slug)||typeof r.action_item_id!="string"||!q7n.test(r.action_item_id)||typeof r.duplicate!="boolean"?null:{slug:r.slug,action_item_id:r.action_item_id,duplicate:r.duplicate}}async function Nzt(t){let e=Date.now(),r=(0,W7.randomUUID)(),n=new AbortController,i=setTimeout(()=>n.abort(),t.timeoutMs??5e3);try{let s=await(t.fetchImpl??fetch)(`${zl(t.baseUrl)}/feedback/capture`,{method:"POST",headers:{authorization:`Bearer ${t.tokens[t.actor]}`,"content-type":"application/json","x-correlation-id":r},body:JSON.stringify(t.payload),signal:n.signal});if(Number(s.headers.get("content-length")??0)>G7)return{correlationId:r,latencyMs:Date.now()-e,response:null};let a=await s.text();if(!s.ok)return{correlationId:r,latencyMs:Date.now()-e,response:null};let c=H7n(a);return{correlationId:r,latencyMs:Date.now()-e,response:c}}catch{return{correlationId:r,latencyMs:Date.now()-e,response:null}}finally{clearTimeout(i)}}async function Lzt(t){let e=Date.now();if(!Ozt(t.payload))throw new Error("feedback payload is invalid");aR(t.spoolRoot);let r=await Nzt(t);if(r.response)return{correlation_id:r.correlationId,actor:t.actor,operation:"feedback_capture",status:"success",latency_ms:r.latencyMs,...r.response,spooled:!1,pending_count:Pzt(t.spoolRoot,t.actor)};let n=$7n(t.spoolRoot,{schema_version:1,actor:t.actor,payload:t.payload,queued_at:(t.now?.()??new Date).toISOString(),attempts:1});return{correlation_id:r.correlationId,actor:t.actor,operation:"feedback_capture",status:"spooled",latency_ms:Date.now()-e,spooled:!0,pending_count:n}}async function Tzt(t,e){let r=fTe(e.spoolRoot,t),n=r.slice(0,e.limitPerActor),i=0,s=0,o=0,a=-1;for(let l=0;l<n.length;l+=1){o+=1;let u=await Nzt({actor:t,payload:n[l].payload,baseUrl:e.baseUrl,tokens:e.tokens,timeoutMs:e.timeoutMs,fetchImpl:e.fetchImpl});if(!u.response){a=l;break}i+=1,u.response.duplicate&&(s+=1)}let c=a>=0?[{...n[a],attempts:n[a].attempts+1},...r.slice(a+1)]:r.slice(n.length);return G7n(e.spoolRoot,t,c),{attempted:o,acknowledged:i,duplicates:s,pending:c.length}}async function Fzt(t){let e=uTe(t.spoolRoot),r=t.limitPerActor??lTe;if(!Number.isInteger(r)||r<1||r>lTe)throw new Error("feedback replay limit is invalid");let n=Mzt(e),i;try{i=ct.openSync(n,ct.constants.O_WRONLY|ct.constants.O_CREAT|ct.constants.O_EXCL|(ct.constants.O_NOFOLLOW??0),384)}catch(s){throw s.code==="EEXIST"?new Error("feedback replay is already in progress"):new Error("feedback replay lock is unsafe")}ct.closeSync(i);try{let s={semi:await Tzt("semi",{...t,spoolRoot:e,limitPerActor:r}),colony:await Tzt("colony",{...t,spoolRoot:e,limitPerActor:r})};return{attempted:s.semi.attempted+s.colony.attempted,acknowledged:s.semi.acknowledged+s.colony.acknowledged,duplicates:s.semi.duplicates+s.colony.duplicates,pending:s.semi.pending+s.colony.pending,actors:s}}finally{ct.rmSync(n,{force:!0})}}async function Uzt(t,e,r=fetch){let n={};for(let i of["semi","colony"]){let s=(0,W7.randomUUID)();try{let o=await r(`${zl(t)}/feedback/doctor`,{method:"POST",headers:{authorization:`Bearer ${e[i]}`,"content-type":"application/json","x-correlation-id":s},body:"{}"}),a=await o.text();if(!o.ok||Buffer.byteLength(a)>G7||MI.test(a))throw new Error("invalid response");let c=JSON.parse(a);if(c.ok!==!0||c.actor!==i||c.installation_id!=="hermes-principals@hermes"||c.runtime_kind!=="hermes-cli"||c.profile_id!=="semo-ops-worker-agent"||c.correlation_id!==s)throw new Error("identity mismatch");n[i]={actor:i,correlation_id:s}}catch{throw new Error("Worker-agent feedback authorization probe failed")}}return n}var W7,ct,qE,G7,lTe,MI,q7n,hTe,qzt=H(()=>{"use strict";W7=require("node:crypto"),ct=v(require("node:fs")),qE=v(require("node:path"));oR();G7=1024*1024,lTe=100,MI=/\bwck_[A-Za-z0-9_-]{20,}\b|\bAuthorization\b|postgres(?:ql)?:\/\/|\bDATABASE_URL\b|\bSEMO_OPS_WORKER_KB_TOKEN\b/i,q7n=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;hTe={MAX_RESPONSE_BYTES:G7,MAX_REPLAY_BATCH:lTe,lockPath:Mzt,pendingCount:Pzt,spoolPath:H7}});function AA(t){return new Error(t?`Worker-agent decision request failed with HTTP ${t}`:"Worker-agent decision request failed")}async function $zt(t){let e=Date.now(),r=(0,pTe.randomUUID)(),n=new AbortController,i=setTimeout(()=>n.abort(),t.timeoutMs??5e3);try{let s=await(t.fetchImpl??fetch)(`${zl(t.baseUrl)}/decision/record`,{method:"POST",headers:{authorization:`Bearer ${t.tokens[t.actor]}`,"content-type":"application/json","x-correlation-id":r},body:JSON.stringify(t.payload),signal:n.signal});if(Number(s.headers.get("content-length")??0)>ATe||s.headers.get("x-correlation-id")!==r)throw AA();let o=await s.text();if(!s.ok)throw AA(s.status);if(Buffer.byteLength(o)>ATe||jzt.test(o))throw AA();let a;try{a=JSON.parse(o)}catch{throw AA()}if(!a||typeof a!="object"||Array.isArray(a))throw AA();let c=a;if(c.ok!==!0||c.actor!==t.actor||c.domain!==t.payload.domain||c.slug!==t.payload.slug||c.decision_ref!==t.payload.decision_ref||typeof c.duplicate!="boolean"||!Number.isInteger(c.kb_id))throw AA();return{correlation_id:r,actor:t.actor,operation:"decision_record",status:"success",latency_ms:Date.now()-e,domain:t.payload.domain,slug:t.payload.slug,decision_ref:t.payload.decision_ref,duplicate:c.duplicate}}catch(s){throw s instanceof Error&&/^Worker-agent decision request failed/.test(s.message)?s:AA()}finally{clearTimeout(i)}}async function Wzt(t,e,r=fetch){let n={};for(let i of["semi","colony"]){let s=(0,pTe.randomUUID)(),o=await r(`${zl(t)}/decision/doctor`,{method:"POST",headers:{authorization:`Bearer ${e[i]}`,"content-type":"application/json","x-correlation-id":s},body:"{}"}),a=await o.text();if(!o.ok||Buffer.byteLength(a)>ATe||jzt.test(a))throw AA(o.status);let c;try{c=JSON.parse(a)}catch{throw AA()}if(c.ok!==!0||c.actor!==i||c.installation_id!=="hermes-principals@hermes"||c.runtime_kind!=="hermes-cli"||c.profile_id!=="semo-ops-worker-agent"||c.correlation_id!==s)throw AA();n[i]={actor:i,correlation_id:s}}return n}var pTe,ATe,jzt,Gzt=H(()=>{"use strict";pTe=require("node:crypto");oR();ATe=64*1024,jzt=/\bwck_[A-Za-z0-9_-]{20,}\b|\bAuthorization\b|postgres(?:ql)?:\/\/|\bDATABASE_URL\b|\bSEMO_OPS_WORKER_KB_TOKEN\b/i});function pA(t){return new Error(t?`Worker-agent note request failed with HTTP ${t}`:"Worker-agent note request failed")}async function Vzt(t){let e=Date.now(),r=(0,mTe.randomUUID)(),n=new AbortController,i=setTimeout(()=>n.abort(),t.timeoutMs??5e3);try{let s=await(t.fetchImpl??fetch)(`${zl(t.baseUrl)}/note/record`,{method:"POST",headers:{authorization:`Bearer ${t.tokens[t.actor]}`,"content-type":"application/json","x-correlation-id":r},body:JSON.stringify(t.payload),signal:n.signal});if(Number(s.headers.get("content-length")??0)>gTe||s.headers.get("x-correlation-id")!==r)throw pA();let o=await s.text();if(!s.ok)throw pA(s.status);if(Buffer.byteLength(o)>gTe||Hzt.test(o))throw pA();let a;try{a=JSON.parse(o)}catch{throw pA()}if(!a||typeof a!="object"||Array.isArray(a))throw pA();let c=a;if(c.ok!==!0||c.actor!==t.actor||c.domain!==t.payload.domain||c.slug!==t.payload.slug||!Number.isInteger(c.kb_id)||!Number.isInteger(c.quota_remaining))throw pA();return{correlation_id:r,actor:t.actor,operation:"kb_note",status:"success",latency_ms:Date.now()-e,domain:t.payload.domain,slug:t.payload.slug,kb_id:c.kb_id,quota_remaining:c.quota_remaining}}catch(s){throw s instanceof Error&&/^Worker-agent note request failed/.test(s.message)?s:pA()}finally{clearTimeout(i)}}async function Yzt(t,e,r=fetch){let n={};for(let i of["semi","colony"]){let s=(0,mTe.randomUUID)(),o=await r(`${zl(t)}/note/doctor`,{method:"POST",headers:{authorization:`Bearer ${e[i]}`,"content-type":"application/json","x-correlation-id":s},body:"{}"}),a=await o.text();if(!o.ok||Buffer.byteLength(a)>gTe||Hzt.test(a))throw pA(o.status);let c;try{c=JSON.parse(a)}catch{throw pA()}if(c.ok!==!0||c.actor!==i||c.installation_id!=="hermes-principals@hermes"||c.runtime_kind!=="hermes-cli"||c.profile_id!=="semo-ops-worker-agent"||c.correlation_id!==s)throw pA();n[i]={actor:i,correlation_id:s}}return n}var mTe,gTe,Hzt,Jzt=H(()=>{"use strict";mTe=require("node:crypto");oR();gTe=64*1024,Hzt=/\bwck_[A-Za-z0-9_-]{20,}\b|\bAuthorization\b|postgres(?:ql)?:\/\/|\bDATABASE_URL\b|\bSEMO_OPS_WORKER_KB_TOKEN\b/i});function Wi(t,e,r,n=!0){let i=t[e];if(!(i==null&&!n)){if(typeof i!="string"||!i.trim()||i.length>r||[...i].some(s=>s.charCodeAt(0)<32)||rZn.test(i))throw new Error("invalid tool arguments");return i.trim()}}function nZn(t,e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("invalid tool arguments");let r=e,n=t==="kb_get"?new Set(["domain","key"]):t==="kb_search"?new Set(["query","domain","top_k","min_score"]):t==="feedback_capture"?new Set(["category","summary","failed_rule","severity","evidence","proposed_fix"]):t==="decision_record"?new Set(["domain","slug","content","decision_ref"]):t==="kb_note"?new Set(["domain","slug","content"]):t==="action_list"?new Set(["status","project","limit"]):t==="action_create"?new Set(["description","project","deadline","priority","assignee_member"]):new Set;for(let i of Object.keys(r))if(J7n.has(i.toLowerCase())||!n.has(i))throw new Error("invalid tool arguments");if(t==="kb_get")return{domain:Wi(r,"domain",100),key:Wi(r,"key",240)};if(t==="kb_search"){let i=r.top_k,s=r.min_score;if(i!=null&&(!Number.isInteger(i)||i<1||i>20))throw new Error("invalid tool arguments");if(s!=null&&(typeof s!="number"||s<0||s>1))throw new Error("invalid tool arguments");return{query:Wi(r,"query",500),...r.domain==null?{}:{domain:Wi(r,"domain",100,!1)},...i==null?{}:{top_k:i},...s==null?{}:{min_score:s}}}if(t==="feedback_capture"){let i=Wi(r,"category",32);if(!eZn.has(i))throw new Error("invalid tool arguments");let s=r.severity==null?void 0:Wi(r,"severity",16,!1);if(s&&!tZn.has(s))throw new Error("invalid tool arguments");let o=Wi(r,"summary",500);if(!o||o.length<8)throw new Error("invalid tool arguments");return{category:i,summary:o,...r.failed_rule==null?{}:{failed_rule:Wi(r,"failed_rule",500,!1)},...s?{severity:s}:{},...r.evidence==null?{}:{evidence:Wi(r,"evidence",1e4,!1)},...r.proposed_fix==null?{}:{proposed_fix:Wi(r,"proposed_fix",1e4,!1)}}}if(t==="decision_record"){let i=Wi(r,"domain",63),s=Wi(r,"slug",100),o=Wi(r,"content",1e4),a=Wi(r,"decision_ref",36);if(!i||!/^[a-z][a-z0-9-]{1,62}$/.test(i)||i==="semo"||i.startsWith("t-")||!s||!/^[a-z0-9][a-z0-9-]{2,99}$/.test(s)||!o||o.length<30||!a||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(a))throw new Error("invalid tool arguments");return{domain:i,slug:s,content:o,decision_ref:a}}if(t==="kb_note"){let i=Wi(r,"domain",63),s=Wi(r,"slug",100),o=Wi(r,"content",1e4);if(!i||!/^[a-z][a-z0-9-]{1,62}$/.test(i)||i==="semo"||i.startsWith("t-")||!s||!/^[a-z0-9][a-z0-9-]{2,99}$/.test(s)||!o||o.length<30)throw new Error("invalid tool arguments");return{domain:i,slug:s,content:o}}if(t==="action_list"){let i=r.limit;if(i!=null&&(!Number.isInteger(i)||i<1||i>50))throw new Error("invalid tool arguments");let s=r.status==null?void 0:Wi(r,"status",16,!1);if(s&&!Z7n.has(s))throw new Error("invalid tool arguments");return{...s?{status:s}:{},...r.project==null?{}:{project:Wi(r,"project",63,!1)},...i==null?{}:{limit:i}}}if(t==="action_create"){let i=Wi(r,"description",2e3);if(!i||i.length<5)throw new Error("invalid tool arguments");let s=Wi(r,"project",63);if(!s||s.length<2)throw new Error("invalid tool arguments");let o=Wi(r,"deadline",10);if(!o||!X7n.test(o))throw new Error("invalid tool arguments");let a=r.priority==null?void 0:Wi(r,"priority",16,!1);if(a&&!z7n.has(a))throw new Error("invalid tool arguments");return{description:i,project:s,deadline:o,...a?{priority:a}:{},...r.assignee_member==null?{}:{assignee_member:Wi(r,"assignee_member",63,!1)}}}throw new Error("unknown tool")}async function iZn(t,e,r){let n=e.id??null;try{if(e.method==="initialize")return{jsonrpc:"2.0",id:n,result:{protocolVersion:"2024-11-05",capabilities:{tools:{}},serverInfo:{name:`semo-worker-agent-${t}`,version:"1.0.0"}}};if(e.method==="notifications/initialized"||e.method==="initialized")return null;if(e.method==="ping")return{jsonrpc:"2.0",id:n,result:{}};if(e.method==="tools/list")return{jsonrpc:"2.0",id:n,result:{tools:K7n}};if(e.method!=="tools/call")return{jsonrpc:"2.0",id:n,error:{code:-32601,message:"method not found"}};let i=e.params??{},s=i.name;if(s!=="kb_get"&&s!=="kb_search"&&s!=="feedback_capture"&&s!=="decision_record"&&s!=="kb_note"&&s!=="action_list"&&s!=="action_create")throw new Error("unknown tool");let o=nZn(s,i.arguments);if(s==="feedback_capture"){let c=await Lzt({actor:t,payload:o,baseUrl:r.baseUrl,tokens:r.tokens,spoolRoot:r.spoolRoot,fetchImpl:r.fetchImpl});return r.logger?.(JSON.stringify({correlation_id:c.correlation_id,actor:c.actor,operation:c.operation,status:c.status,latency_ms:c.latency_ms,pending_count:c.pending_count})),{jsonrpc:"2.0",id:n,result:{content:[{type:"text",text:JSON.stringify(c)}]}}}if(s==="decision_record"){let c=await $zt({actor:t,payload:o,baseUrl:r.baseUrl,tokens:r.tokens,fetchImpl:r.fetchImpl});return r.logger?.(JSON.stringify({correlation_id:c.correlation_id,actor:c.actor,operation:c.operation,status:c.status,latency_ms:c.latency_ms})),{jsonrpc:"2.0",id:n,result:{content:[{type:"text",text:JSON.stringify(c)}]}}}if(s==="kb_note"){let c=await Vzt({actor:t,payload:o,baseUrl:r.baseUrl,tokens:r.tokens,fetchImpl:r.fetchImpl});return r.logger?.(JSON.stringify({correlation_id:c.correlation_id,actor:c.actor,operation:c.operation,status:c.status,latency_ms:c.latency_ms,quota_remaining:c.quota_remaining})),{jsonrpc:"2.0",id:n,result:{content:[{type:"text",text:JSON.stringify(c)}]}}}if(s==="action_list"){let c=await Qzt({actor:t,payload:o,baseUrl:r.baseUrl,tokens:r.tokens,fetchImpl:r.fetchImpl});return r.logger?.(JSON.stringify({correlation_id:c.correlation_id,actor:c.actor,operation:c.operation,status:c.status,latency_ms:c.latency_ms,count:c.items.length})),{jsonrpc:"2.0",id:n,result:{content:[{type:"text",text:JSON.stringify(c)}]}}}if(s==="action_create"){let c=await Dzt({actor:t,payload:o,baseUrl:r.baseUrl,tokens:r.tokens,fetchImpl:r.fetchImpl});return r.logger?.(JSON.stringify({correlation_id:c.correlation_id,actor:c.actor,operation:c.operation,status:c.status,latency_ms:c.latency_ms,action_item_id:c.action_item_id})),{jsonrpc:"2.0",id:n,result:{content:[{type:"text",text:JSON.stringify(c)}]}}}let a=await xzt({actor:t,operation:s,args:o,baseUrl:r.baseUrl,tokens:r.tokens,fetchImpl:r.fetchImpl});if(s==="kb_get"){let c=a.result;if(typeof c?.content!="string"||c.content.trim()==="")throw new Error("empty KB content")}return r.logger?.(JSON.stringify({correlation_id:a.correlation_id,actor:a.actor,operation:a.operation,status:a.status,latency_ms:a.latency_ms})),{jsonrpc:"2.0",id:n,result:{content:[{type:"text",text:JSON.stringify({result:a.result,correlation_id:a.correlation_id,actor:a.actor})}]}}}catch{return{jsonrpc:"2.0",id:n,result:{content:[{type:"text",text:"Worker-agent tool request failed"}],isError:!0}}}}async function zzt(t){let e=[],r=0;for await(let n of t){let i=Buffer.from(n);if(r+=i.length,r>Y7n)throw new Error("request too large");e.push(i)}return Buffer.concat(e).toString("utf8")}function sZn(t){return t==="/mcp/semi"?"semi":t==="/mcp/colony"?"colony":null}function oZn(t){let e=new Map;for(let r of t.split(/\r?\n/)){let n=r.indexOf("=");n>0&&e.set(r.slice(0,n),r.slice(n+1))}return e}async function aZn(t={}){let e=t.execFileImpl??(async(s,o)=>{let a=await V7n(s,o,{encoding:"utf8"});return{stdout:a.stdout,stderr:a.stderr}}),r=t.fetchImpl??fetch,n={};for(let s of Object.keys(Kzt)){let o=Kzt[s],a=await e("/usr/bin/systemctl",["show",o,"--property=ActiveState","--property=SubState","--property=MainPID","--property=ExecMainStatus","--no-pager"]),c=await e("/usr/bin/systemctl",["is-enabled",o]),l=oZn(a.stdout),u=Number(l.get("MainPID")),d=Number(l.get("ExecMainStatus"));if(l.get("ActiveState")!=="active"||l.get("SubState")!=="running"||c.stdout.trim()!=="enabled"||!Number.isSafeInteger(u)||u<=0||d!==0)throw new Error("fixed host service probe failed");n[s]={service:s,unit:o,status:"pass",active_state:"active",enabled_state:"enabled",sub_state:"running",main_pid:u,exec_main_status:0}}if((await r("http://127.0.0.1:18810/health")).status!==200)throw new Error("fixed host service probe failed");return n["kb-gateway"].protocol={name:"http",destination:"http://127.0.0.1:18810/health",status:200},n}async function cZn(t,e,r=fetch){let n={};for(let i of["semi","colony"]){let s=await r(`${t.replace(/\/$/,"")}/worker/release/get`,{method:"POST",headers:{authorization:`Bearer ${e[i]}`,"content-type":"application/json"},body:"{}"});n[i]=s.status}if(n.semi!==403||n.colony!==403)throw new Error("actor release denial probe failed");return n}function lZn(t){let e=kzt(t.credentialsDir),r=zl(t.baseUrl),n=t.port??fd;if(!Number.isInteger(n)||n<0||n>65535)throw new Error("broker port is invalid");let i=(0,Xzt.createServer)(async(s,o)=>{o.setHeader("cache-control","no-store");let a=sZn(s.url);if(s.method==="POST"&&s.url==="/doctor/services"&&!s.headers.authorization&&(s.headers["content-length"]===void 0||s.headers["content-length"]==="0")&&!s.headers["transfer-encoding"]){try{let c=await(t.serviceProbe??aZn)();o.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify(c))}catch{o.writeHead(503,{"content-type":"application/json"}).end(JSON.stringify({error:"host service probe failed"}))}return}if(s.method==="POST"&&s.url==="/doctor/release-deny"&&!s.headers.authorization){try{let c=await cZn(r,e,t.fetchImpl);o.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify(c))}catch{o.writeHead(503,{"content-type":"application/json"}).end(JSON.stringify({error:"release denial probe failed"}))}return}if(s.method==="POST"&&s.url==="/doctor/feedback-auth"&&!s.headers.authorization){try{let c=await Uzt(r,e,t.fetchImpl);o.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify(c))}catch{o.writeHead(503,{"content-type":"application/json"}).end(JSON.stringify({error:"feedback authorization probe failed"}))}return}if(s.method==="POST"&&s.url==="/doctor/decision-auth"&&!s.headers.authorization){try{let c=await Wzt(r,e,t.fetchImpl);o.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify(c))}catch{o.writeHead(503,{"content-type":"application/json"}).end(JSON.stringify({error:"decision authorization probe failed"}))}return}if(s.method==="POST"&&s.url==="/doctor/note-auth"&&!s.headers.authorization){try{let c=await Yzt(r,e,t.fetchImpl);o.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify(c))}catch{o.writeHead(503,{"content-type":"application/json"}).end(JSON.stringify({error:"note authorization probe failed"}))}return}if(s.method==="POST"&&s.url==="/doctor/feedback-status"&&!s.headers.authorization){try{let c={semi:hTe.pendingCount(t.spoolRoot,"semi"),colony:hTe.pendingCount(t.spoolRoot,"colony")};o.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify(c))}catch{o.writeHead(503,{"content-type":"application/json"}).end(JSON.stringify({error:"feedback spool status failed"}))}return}if(s.method==="POST"&&s.url==="/admin/feedback-replay"&&!s.headers.authorization){try{let c=JSON.parse(await zzt(s));if(!c||Array.isArray(c)||Object.keys(c).length!==0)throw new Error("invalid replay request");let l=await Fzt({baseUrl:r,tokens:e,spoolRoot:t.spoolRoot,fetchImpl:t.fetchImpl});o.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify(l))}catch{o.writeHead(503,{"content-type":"application/json"}).end(JSON.stringify({error:"feedback replay failed"}))}return}if(s.method!=="POST"||!a||s.headers.authorization){o.writeHead(404).end();return}try{let c=JSON.parse(await zzt(s)),l=await iZn(a,c,{baseUrl:r,tokens:e,spoolRoot:t.spoolRoot,fetchImpl:t.fetchImpl,logger:t.logger});if(l===null){o.writeHead(204).end();return}o.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify(l))}catch{o.writeHead(400,{"content-type":"application/json"}).end(JSON.stringify({error:"invalid request"}))}});return i.listen(n,"127.0.0.1"),i}async function V7(t,e,r=fetch){let n;try{n=JSON.parse(e)}catch{return null}let i=await r(`http://127.0.0.1:${fd}/mcp/${t}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)});return i.status===204?null:i.ok?i.text():JSON.stringify({jsonrpc:"2.0",id:n.id??null,error:{code:-32e3,message:"local Worker-agent broker unavailable"}})}function Zzt(t){let e="",r=Promise.resolve();process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{e+=n;let i;for(;(i=e.indexOf(`
1533
+ `:"";if(MI.test(o))throw new Error("feedback spool record is unsafe");let a;try{a=ct.openSync(s,ct.constants.O_WRONLY|ct.constants.O_CREAT|ct.constants.O_EXCL|(ct.constants.O_NOFOLLOW??0),384),ct.writeSync(a,o),ct.fsyncSync(a),ct.closeSync(a),a=void 0,ct.renameSync(s,i),ct.chmodSync(i,384)}finally{a!==void 0&&ct.closeSync(a),ct.existsSync(s)&&ct.rmSync(s)}}function H7n(t){if(Buffer.byteLength(t)>G7||MI.test(t))return null;let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object"||Array.isArray(e))return null;let r=e;return r.ok!==!0||typeof r.slug!="string"||!/^[a-z0-9][a-z0-9-]{0,239}$/.test(r.slug)||typeof r.action_item_id!="string"||!q7n.test(r.action_item_id)||typeof r.duplicate!="boolean"?null:{slug:r.slug,action_item_id:r.action_item_id,duplicate:r.duplicate}}async function Nzt(t){let e=Date.now(),r=(0,W7.randomUUID)(),n=new AbortController,i=setTimeout(()=>n.abort(),t.timeoutMs??5e3);try{let s=await(t.fetchImpl??fetch)(`${zl(t.baseUrl)}/feedback/capture`,{method:"POST",headers:{authorization:`Bearer ${t.tokens[t.actor]}`,"content-type":"application/json","x-correlation-id":r},body:JSON.stringify(t.payload),signal:n.signal});if(Number(s.headers.get("content-length")??0)>G7)return{correlationId:r,latencyMs:Date.now()-e,response:null};let a=await s.text();if(!s.ok)return{correlationId:r,latencyMs:Date.now()-e,response:null};let c=H7n(a);return{correlationId:r,latencyMs:Date.now()-e,response:c}}catch{return{correlationId:r,latencyMs:Date.now()-e,response:null}}finally{clearTimeout(i)}}async function Lzt(t){let e=Date.now();if(!Ozt(t.payload))throw new Error("feedback payload is invalid");aR(t.spoolRoot);let r=await Nzt(t);if(r.response)return{correlation_id:r.correlationId,actor:t.actor,operation:"feedback_capture",status:"success",latency_ms:r.latencyMs,...r.response,spooled:!1,pending_count:Pzt(t.spoolRoot,t.actor)};let n=$7n(t.spoolRoot,{schema_version:1,actor:t.actor,payload:t.payload,queued_at:(t.now?.()??new Date).toISOString(),attempts:1});return{correlation_id:r.correlationId,actor:t.actor,operation:"feedback_capture",status:"spooled",latency_ms:Date.now()-e,spooled:!0,pending_count:n}}async function Tzt(t,e){let r=fTe(e.spoolRoot,t),n=r.slice(0,e.limitPerActor),i=0,s=0,o=0,a=-1;for(let l=0;l<n.length;l+=1){o+=1;let u=await Nzt({actor:t,payload:n[l].payload,baseUrl:e.baseUrl,tokens:e.tokens,timeoutMs:e.timeoutMs,fetchImpl:e.fetchImpl});if(!u.response){a=l;break}i+=1,u.response.duplicate&&(s+=1)}let c=a>=0?[{...n[a],attempts:n[a].attempts+1},...r.slice(a+1)]:r.slice(n.length);return G7n(e.spoolRoot,t,c),{attempted:o,acknowledged:i,duplicates:s,pending:c.length}}async function Fzt(t){let e=uTe(t.spoolRoot),r=t.limitPerActor??lTe;if(!Number.isInteger(r)||r<1||r>lTe)throw new Error("feedback replay limit is invalid");let n=Mzt(e),i;try{i=ct.openSync(n,ct.constants.O_WRONLY|ct.constants.O_CREAT|ct.constants.O_EXCL|(ct.constants.O_NOFOLLOW??0),384)}catch(s){throw s.code==="EEXIST"?new Error("feedback replay is already in progress"):new Error("feedback replay lock is unsafe")}ct.closeSync(i);try{let s={semi:await Tzt("semi",{...t,spoolRoot:e,limitPerActor:r}),colony:await Tzt("colony",{...t,spoolRoot:e,limitPerActor:r})};return{attempted:s.semi.attempted+s.colony.attempted,acknowledged:s.semi.acknowledged+s.colony.acknowledged,duplicates:s.semi.duplicates+s.colony.duplicates,pending:s.semi.pending+s.colony.pending,actors:s}}finally{ct.rmSync(n,{force:!0})}}async function Uzt(t,e,r=fetch){let n={};for(let i of["semi","colony"]){let s=(0,W7.randomUUID)();try{let o=await r(`${zl(t)}/feedback/doctor`,{method:"POST",headers:{authorization:`Bearer ${e[i]}`,"content-type":"application/json","x-correlation-id":s},body:"{}"}),a=await o.text();if(!o.ok||Buffer.byteLength(a)>G7||MI.test(a))throw new Error("invalid response");let c=JSON.parse(a);if(c.ok!==!0||c.actor!==i||c.installation_id!=="hermes-principals@hermes"||c.runtime_kind!=="hermes-cli"||c.profile_id!=="semo-ops-worker-agent"||c.correlation_id!==s)throw new Error("identity mismatch");n[i]={actor:i,correlation_id:s}}catch{throw new Error("Worker-agent feedback authorization probe failed")}}return n}var W7,ct,qE,G7,lTe,MI,q7n,hTe,qzt=H(()=>{"use strict";W7=require("node:crypto"),ct=v(require("node:fs")),qE=v(require("node:path"));oR();G7=1024*1024,lTe=100,MI=/\bwck_[A-Za-z0-9_-]{20,}\b|\bAuthorization\b|postgres(?:ql)?:\/\/|\bDATABASE_URL\b|\bSEMO_OPS_WORKER_KB_TOKEN\b/i,q7n=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;hTe={MAX_RESPONSE_BYTES:G7,MAX_REPLAY_BATCH:lTe,lockPath:Mzt,pendingCount:Pzt,spoolPath:H7}});function AA(t){return new Error(t?`Worker-agent decision request failed with HTTP ${t}`:"Worker-agent decision request failed")}async function $zt(t){let e=Date.now(),r=(0,pTe.randomUUID)(),n=new AbortController,i=setTimeout(()=>n.abort(),t.timeoutMs??5e3);try{let s=await(t.fetchImpl??fetch)(`${zl(t.baseUrl)}/decision/record`,{method:"POST",headers:{authorization:`Bearer ${t.tokens[t.actor]}`,"content-type":"application/json","x-correlation-id":r},body:JSON.stringify(t.payload),signal:n.signal});if(Number(s.headers.get("content-length")??0)>ATe||s.headers.get("x-correlation-id")!==r)throw AA();let o=await s.text();if(!s.ok)throw AA(s.status);if(Buffer.byteLength(o)>ATe||jzt.test(o))throw AA();let a;try{a=JSON.parse(o)}catch{throw AA()}if(!a||typeof a!="object"||Array.isArray(a))throw AA();let c=a;if(c.ok!==!0||c.actor!==t.actor||c.domain!==t.payload.domain||c.slug!==t.payload.slug||c.decision_ref!==t.payload.decision_ref||typeof c.duplicate!="boolean"||!Number.isInteger(c.kb_id))throw AA();return{correlation_id:r,actor:t.actor,operation:"decision_record",status:"success",latency_ms:Date.now()-e,domain:t.payload.domain,slug:t.payload.slug,decision_ref:t.payload.decision_ref,duplicate:c.duplicate}}catch(s){throw s instanceof Error&&/^Worker-agent decision request failed/.test(s.message)?s:AA()}finally{clearTimeout(i)}}async function Wzt(t,e,r=fetch){let n={};for(let i of["semi","colony"]){let s=(0,pTe.randomUUID)(),o=await r(`${zl(t)}/decision/doctor`,{method:"POST",headers:{authorization:`Bearer ${e[i]}`,"content-type":"application/json","x-correlation-id":s},body:"{}"}),a=await o.text();if(!o.ok||Buffer.byteLength(a)>ATe||jzt.test(a))throw AA(o.status);let c;try{c=JSON.parse(a)}catch{throw AA()}if(c.ok!==!0||c.actor!==i||c.installation_id!=="hermes-principals@hermes"||c.runtime_kind!=="hermes-cli"||c.profile_id!=="semo-ops-worker-agent"||c.correlation_id!==s)throw AA();n[i]={actor:i,correlation_id:s}}return n}var pTe,ATe,jzt,Gzt=H(()=>{"use strict";pTe=require("node:crypto");oR();ATe=64*1024,jzt=/\bwck_[A-Za-z0-9_-]{20,}\b|\bAuthorization\b|postgres(?:ql)?:\/\/|\bDATABASE_URL\b|\bSEMO_OPS_WORKER_KB_TOKEN\b/i});function pA(t){return new Error(t?`Worker-agent note request failed with HTTP ${t}`:"Worker-agent note request failed")}async function Vzt(t){let e=Date.now(),r=(0,mTe.randomUUID)(),n=new AbortController,i=setTimeout(()=>n.abort(),t.timeoutMs??5e3);try{let s=await(t.fetchImpl??fetch)(`${zl(t.baseUrl)}/note/record`,{method:"POST",headers:{authorization:`Bearer ${t.tokens[t.actor]}`,"content-type":"application/json","x-correlation-id":r},body:JSON.stringify(t.payload),signal:n.signal});if(Number(s.headers.get("content-length")??0)>gTe||s.headers.get("x-correlation-id")!==r)throw pA();let o=await s.text();if(!s.ok)throw pA(s.status);if(Buffer.byteLength(o)>gTe||Hzt.test(o))throw pA();let a;try{a=JSON.parse(o)}catch{throw pA()}if(!a||typeof a!="object"||Array.isArray(a))throw pA();let c=a;if(c.ok!==!0||c.actor!==t.actor||c.domain!==t.payload.domain||c.slug!==t.payload.slug||!Number.isInteger(c.kb_id)||!Number.isInteger(c.quota_remaining))throw pA();return{correlation_id:r,actor:t.actor,operation:"kb_note",status:"success",latency_ms:Date.now()-e,domain:t.payload.domain,slug:t.payload.slug,kb_id:c.kb_id,quota_remaining:c.quota_remaining}}catch(s){throw s instanceof Error&&/^Worker-agent note request failed/.test(s.message)?s:pA()}finally{clearTimeout(i)}}async function Yzt(t,e,r=fetch){let n={};for(let i of["semi","colony"]){let s=(0,mTe.randomUUID)(),o=await r(`${zl(t)}/note/doctor`,{method:"POST",headers:{authorization:`Bearer ${e[i]}`,"content-type":"application/json","x-correlation-id":s},body:"{}"}),a=await o.text();if(!o.ok||Buffer.byteLength(a)>gTe||Hzt.test(a))throw pA(o.status);let c;try{c=JSON.parse(a)}catch{throw pA()}if(c.ok!==!0||c.actor!==i||c.installation_id!=="hermes-principals@hermes"||c.runtime_kind!=="hermes-cli"||c.profile_id!=="semo-ops-worker-agent"||c.correlation_id!==s)throw pA();n[i]={actor:i,correlation_id:s}}return n}var mTe,gTe,Hzt,Jzt=H(()=>{"use strict";mTe=require("node:crypto");oR();gTe=64*1024,Hzt=/\bwck_[A-Za-z0-9_-]{20,}\b|\bAuthorization\b|postgres(?:ql)?:\/\/|\bDATABASE_URL\b|\bSEMO_OPS_WORKER_KB_TOKEN\b/i});function Wi(t,e,r,n=!0){let i=t[e];if(!(i==null&&!n)){if(typeof i!="string"||!i.trim()||i.length>r||[...i].some(s=>s.charCodeAt(0)<32)||rZn.test(i))throw new Error("invalid tool arguments");return i.trim()}}function nZn(t,e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("invalid tool arguments");let r=e,n=t==="kb_get"?new Set(["domain","key"]):t==="kb_search"?new Set(["query","domain","top_k","min_score"]):t==="feedback_capture"?new Set(["category","summary","failed_rule","severity","evidence","proposed_fix"]):t==="decision_record"?new Set(["domain","slug","content","decision_ref"]):t==="kb_note"?new Set(["domain","slug","content"]):t==="action_list"?new Set(["status","project","limit"]):t==="action_create"?new Set(["description","project","deadline","priority","assignee_member"]):new Set;for(let i of Object.keys(r))if(J7n.has(i.toLowerCase())||!n.has(i))throw new Error("invalid tool arguments");if(t==="kb_get")return{domain:Wi(r,"domain",100),key:Wi(r,"key",240)};if(t==="kb_search"){let i=r.top_k,s=r.min_score;if(i!=null&&(!Number.isInteger(i)||i<1||i>20))throw new Error("invalid tool arguments");if(s!=null&&(typeof s!="number"||s<0||s>1))throw new Error("invalid tool arguments");return{query:Wi(r,"query",500),...r.domain==null?{}:{domain:Wi(r,"domain",100,!1)},...i==null?{}:{top_k:i},...s==null?{}:{min_score:s}}}if(t==="feedback_capture"){let i=Wi(r,"category",32);if(!eZn.has(i))throw new Error("invalid tool arguments");let s=r.severity==null?void 0:Wi(r,"severity",16,!1);if(s&&!tZn.has(s))throw new Error("invalid tool arguments");let o=Wi(r,"summary",500);if(!o||o.length<8)throw new Error("invalid tool arguments");return{category:i,summary:o,...r.failed_rule==null?{}:{failed_rule:Wi(r,"failed_rule",500,!1)},...s?{severity:s}:{},...r.evidence==null?{}:{evidence:Wi(r,"evidence",1e4,!1)},...r.proposed_fix==null?{}:{proposed_fix:Wi(r,"proposed_fix",1e4,!1)}}}if(t==="decision_record"){let i=Wi(r,"domain",63),s=Wi(r,"slug",100),o=Wi(r,"content",1e4),a=Wi(r,"decision_ref",36);if(!i||!/^[a-z][a-z0-9-]{1,62}$/.test(i)||i==="semo"||i.startsWith("t-")||!s||!/^[a-z0-9][a-z0-9-]{2,99}$/.test(s)||!o||o.length<30||!a||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(a))throw new Error("invalid tool arguments");return{domain:i,slug:s,content:o,decision_ref:a}}if(t==="kb_note"){let i=Wi(r,"domain",63),s=Wi(r,"slug",100),o=Wi(r,"content",1e4);if(!i||!/^[a-z][a-z0-9-]{1,62}$/.test(i)||i==="semo"||i.startsWith("t-")||!s||!/^[a-z0-9][a-z0-9-]{2,99}$/.test(s)||!o||o.length<30)throw new Error("invalid tool arguments");return{domain:i,slug:s,content:o}}if(t==="action_list"){let i=r.limit;if(i!=null&&(!Number.isInteger(i)||i<1||i>50))throw new Error("invalid tool arguments");let s=r.status==null?void 0:Wi(r,"status",16,!1);if(s&&!Z7n.has(s))throw new Error("invalid tool arguments");return{...s?{status:s}:{},...r.project==null?{}:{project:Wi(r,"project",63,!1)},...i==null?{}:{limit:i}}}if(t==="action_create"){let i=Wi(r,"description",2e3);if(!i||i.length<5)throw new Error("invalid tool arguments");let s=Wi(r,"project",63);if(!s||s.length<2)throw new Error("invalid tool arguments");let o=Wi(r,"deadline",10);if(!o||!X7n.test(o))throw new Error("invalid tool arguments");let a=r.priority==null?void 0:Wi(r,"priority",16,!1);if(a&&!z7n.has(a))throw new Error("invalid tool arguments");return{description:i,project:s,deadline:o,...a?{priority:a}:{},...r.assignee_member==null?{}:{assignee_member:Wi(r,"assignee_member",63,!1)}}}throw new Error("unknown tool")}async function iZn(t,e,r){let n=e.id??null;try{if(e.method==="initialize")return{jsonrpc:"2.0",id:n,result:{protocolVersion:"2024-11-05",capabilities:{tools:{}},serverInfo:{name:`semo-worker-agent-${t}`,version:"1.0.0"}}};if(e.method==="notifications/initialized"||e.method==="initialized")return null;if(e.method==="ping")return{jsonrpc:"2.0",id:n,result:{}};if(e.method==="tools/list")return{jsonrpc:"2.0",id:n,result:{tools:K7n}};if(e.method!=="tools/call")return{jsonrpc:"2.0",id:n,error:{code:-32601,message:"method not found"}};let i=e.params??{},s=i.name;if(s!=="kb_get"&&s!=="kb_search"&&s!=="feedback_capture"&&s!=="decision_record"&&s!=="kb_note"&&s!=="action_list"&&s!=="action_create")throw new Error("unknown tool");let o=nZn(s,i.arguments);if(s==="feedback_capture"){let c=await Lzt({actor:t,payload:o,baseUrl:r.baseUrl,tokens:r.tokens,spoolRoot:r.spoolRoot,fetchImpl:r.fetchImpl});return r.logger?.(JSON.stringify({correlation_id:c.correlation_id,actor:c.actor,operation:c.operation,status:c.status,latency_ms:c.latency_ms,pending_count:c.pending_count})),{jsonrpc:"2.0",id:n,result:{content:[{type:"text",text:JSON.stringify(c)}]}}}if(s==="decision_record"){let c=await $zt({actor:t,payload:o,baseUrl:r.baseUrl,tokens:r.tokens,fetchImpl:r.fetchImpl});return r.logger?.(JSON.stringify({correlation_id:c.correlation_id,actor:c.actor,operation:c.operation,status:c.status,latency_ms:c.latency_ms})),{jsonrpc:"2.0",id:n,result:{content:[{type:"text",text:JSON.stringify(c)}]}}}if(s==="kb_note"){let c=await Vzt({actor:t,payload:o,baseUrl:r.baseUrl,tokens:r.tokens,fetchImpl:r.fetchImpl});return r.logger?.(JSON.stringify({correlation_id:c.correlation_id,actor:c.actor,operation:c.operation,status:c.status,latency_ms:c.latency_ms,quota_remaining:c.quota_remaining})),{jsonrpc:"2.0",id:n,result:{content:[{type:"text",text:JSON.stringify(c)}]}}}if(s==="action_list"){let c=await Qzt({actor:t,payload:o,baseUrl:r.baseUrl,tokens:r.tokens,fetchImpl:r.fetchImpl});return r.logger?.(JSON.stringify({correlation_id:c.correlation_id,actor:c.actor,operation:c.operation,status:c.status,latency_ms:c.latency_ms,count:c.items.length})),{jsonrpc:"2.0",id:n,result:{content:[{type:"text",text:JSON.stringify(c)}]}}}if(s==="action_create"){let c=await Dzt({actor:t,payload:o,baseUrl:r.baseUrl,tokens:r.tokens,fetchImpl:r.fetchImpl});return r.logger?.(JSON.stringify({correlation_id:c.correlation_id,actor:c.actor,operation:c.operation,status:c.status,latency_ms:c.latency_ms,action_item_id:c.action_item_id})),{jsonrpc:"2.0",id:n,result:{content:[{type:"text",text:JSON.stringify(c)}]}}}let a=await xzt({actor:t,operation:s,args:o,baseUrl:r.baseUrl,tokens:r.tokens,fetchImpl:r.fetchImpl});if(s==="kb_get"){let c=a.result;if(typeof c?.content!="string"||c.content.trim()==="")throw new Error("empty KB content")}return r.logger?.(JSON.stringify({correlation_id:a.correlation_id,actor:a.actor,operation:a.operation,status:a.status,latency_ms:a.latency_ms})),{jsonrpc:"2.0",id:n,result:{content:[{type:"text",text:JSON.stringify({result:a.result,correlation_id:a.correlation_id,actor:a.actor})}]}}}catch{return{jsonrpc:"2.0",id:n,result:{content:[{type:"text",text:"Worker-agent tool request failed"}],isError:!0}}}}async function zzt(t){let e=[],r=0;for await(let n of t){let i=Buffer.from(n);if(r+=i.length,r>Y7n)throw new Error("request too large");e.push(i)}return Buffer.concat(e).toString("utf8")}function sZn(t){return t==="/mcp/semi"?"semi":t==="/mcp/colony"?"colony":null}function oZn(t){let e=new Map;for(let r of t.split(/\r?\n/)){let n=r.indexOf("=");n>0&&e.set(r.slice(0,n),r.slice(n+1))}return e}async function aZn(t={}){let e=t.execFileImpl??(async(i,s)=>{let o=await V7n(i,s,{encoding:"utf8"});return{stdout:o.stdout,stderr:o.stderr}}),r=t.fetchImpl??fetch,n={};for(let i of Object.keys(Kzt)){let s=Kzt[i];try{let o=await e("/usr/bin/systemctl",["show",s,"--property=ActiveState","--property=SubState","--property=MainPID","--property=ExecMainStatus","--no-pager"]),a="unknown";try{a=(await e("/usr/bin/systemctl",["is-enabled",s])).stdout.trim()}catch(A){let g=A?.stdout;a=typeof g=="string"&&g.trim()?g.trim():"disabled"}let c=oZn(o.stdout),l=c.get("ActiveState")??"unknown",u=c.get("SubState")??"unknown",d=Number(c.get("MainPID")),f=Number(c.get("ExecMainStatus")),h=[];l!=="active"&&h.push(`ActiveState=${l}`),u!=="running"&&h.push(`SubState=${u}`),a!=="enabled"&&h.push(`UnitFileState=${a}`),(!Number.isSafeInteger(d)||d<=0)&&h.push(`MainPID=${c.get("MainPID")}`),f!==0&&h.push(`ExecMainStatus=${c.get("ExecMainStatus")}`),n[i]={service:i,unit:s,status:h.length===0?"pass":"fail",active_state:l,enabled_state:a,sub_state:u,main_pid:Number.isSafeInteger(d)?d:0,exec_main_status:Number.isSafeInteger(f)?f:-1,...h.length===0?{}:{reason:h.join(", ")}}}catch(o){n[i]={service:i,unit:s,status:"fail",active_state:"unknown",enabled_state:"unknown",sub_state:"unknown",main_pid:0,exec_main_status:-1,reason:`systemctl unavailable: ${o.message}`}}}if(n["kb-gateway"].status==="pass")try{let i=await r("http://127.0.0.1:18810/health");n["kb-gateway"].protocol={name:"http",destination:"http://127.0.0.1:18810/health",status:i.status},i.status!==200&&(n["kb-gateway"].status="fail",n["kb-gateway"].reason=`health HTTP ${i.status}`)}catch(i){n["kb-gateway"].status="fail",n["kb-gateway"].reason=`health unreachable: ${i.message}`}return n}async function cZn(t,e,r=fetch){let n={};for(let i of["semi","colony"]){let s=await r(`${t.replace(/\/$/,"")}/worker/release/get`,{method:"POST",headers:{authorization:`Bearer ${e[i]}`,"content-type":"application/json"},body:"{}"});n[i]=s.status}if(n.semi!==403||n.colony!==403)throw new Error("actor release denial probe failed");return n}function lZn(t){let e=kzt(t.credentialsDir),r=zl(t.baseUrl),n=t.port??fd;if(!Number.isInteger(n)||n<0||n>65535)throw new Error("broker port is invalid");let i=(0,Xzt.createServer)(async(s,o)=>{o.setHeader("cache-control","no-store");let a=sZn(s.url);if(s.method==="POST"&&s.url==="/doctor/services"&&!s.headers.authorization&&(s.headers["content-length"]===void 0||s.headers["content-length"]==="0")&&!s.headers["transfer-encoding"]){try{let c=await(t.serviceProbe??aZn)();o.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify(c))}catch{o.writeHead(503,{"content-type":"application/json"}).end(JSON.stringify({error:"host service probe failed"}))}return}if(s.method==="POST"&&s.url==="/doctor/release-deny"&&!s.headers.authorization){try{let c=await cZn(r,e,t.fetchImpl);o.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify(c))}catch{o.writeHead(503,{"content-type":"application/json"}).end(JSON.stringify({error:"release denial probe failed"}))}return}if(s.method==="POST"&&s.url==="/doctor/feedback-auth"&&!s.headers.authorization){try{let c=await Uzt(r,e,t.fetchImpl);o.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify(c))}catch{o.writeHead(503,{"content-type":"application/json"}).end(JSON.stringify({error:"feedback authorization probe failed"}))}return}if(s.method==="POST"&&s.url==="/doctor/decision-auth"&&!s.headers.authorization){try{let c=await Wzt(r,e,t.fetchImpl);o.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify(c))}catch{o.writeHead(503,{"content-type":"application/json"}).end(JSON.stringify({error:"decision authorization probe failed"}))}return}if(s.method==="POST"&&s.url==="/doctor/note-auth"&&!s.headers.authorization){try{let c=await Yzt(r,e,t.fetchImpl);o.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify(c))}catch{o.writeHead(503,{"content-type":"application/json"}).end(JSON.stringify({error:"note authorization probe failed"}))}return}if(s.method==="POST"&&s.url==="/doctor/feedback-status"&&!s.headers.authorization){try{let c={semi:hTe.pendingCount(t.spoolRoot,"semi"),colony:hTe.pendingCount(t.spoolRoot,"colony")};o.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify(c))}catch{o.writeHead(503,{"content-type":"application/json"}).end(JSON.stringify({error:"feedback spool status failed"}))}return}if(s.method==="POST"&&s.url==="/admin/feedback-replay"&&!s.headers.authorization){try{let c=JSON.parse(await zzt(s));if(!c||Array.isArray(c)||Object.keys(c).length!==0)throw new Error("invalid replay request");let l=await Fzt({baseUrl:r,tokens:e,spoolRoot:t.spoolRoot,fetchImpl:t.fetchImpl});o.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify(l))}catch{o.writeHead(503,{"content-type":"application/json"}).end(JSON.stringify({error:"feedback replay failed"}))}return}if(s.method!=="POST"||!a||s.headers.authorization){o.writeHead(404).end();return}try{let c=JSON.parse(await zzt(s)),l=await iZn(a,c,{baseUrl:r,tokens:e,spoolRoot:t.spoolRoot,fetchImpl:t.fetchImpl,logger:t.logger});if(l===null){o.writeHead(204).end();return}o.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify(l))}catch{o.writeHead(400,{"content-type":"application/json"}).end(JSON.stringify({error:"invalid request"}))}});return i.listen(n,"127.0.0.1"),i}async function V7(t,e,r=fetch){let n;try{n=JSON.parse(e)}catch{return null}let i=await r(`http://127.0.0.1:${fd}/mcp/${t}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)});return i.status===204?null:i.ok?i.text():JSON.stringify({jsonrpc:"2.0",id:n.id??null,error:{code:-32e3,message:"local Worker-agent broker unavailable"}})}function Zzt(t){let e="",r=Promise.resolve();process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{e+=n;let i;for(;(i=e.indexOf(`
1534
1534
  `))>=0;){let s=e.slice(0,i).trim();e=e.slice(i+1),s&&(r=r.then(async()=>{let o=await V7(t,s);o&&process.stdout.write(`${o}
1535
1535
  `)}).catch(()=>{process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32e3,message:"local Worker-agent broker unavailable"}})}
1536
1536
  `)}))}}),process.stdin.resume()}function r7t(t){let e=t.command("tools").description("local actor-fixed Worker-agent MCP broker");e.command("serve").requiredOption("--gateway-url <url>","fixed Gateway URL for the host service").requiredOption("--credentials-dir <absolute-path>","systemd credentials directory").requiredOption("--spool-dir <absolute-path>","fixed host feedback spool directory").option("--port <n>","loopback broker port",String(fd)).action(r=>{let n=Number(r.port);if(!Number.isInteger(n)||n<1||n>65535)throw new Error("broker port must be between 1 and 65535");lZn({baseUrl:r.gatewayUrl,credentialsDir:r.credentialsDir,spoolRoot:r.spoolDir,port:n,logger:i=>process.stderr.write(`[worker-agent-tools] ${i}
1537
- `)})}),e.command("doctor").description("verify both fixed MCP adapters expose exactly five tools").action(async()=>{for(let u of["semi","colony"]){let d=await V7(u,JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/list"})),f=d?JSON.parse(d):null;if(JSON.stringify(f?.result?.tools?.map(h=>h.name))!==JSON.stringify(["kb_get","kb_search","feedback_capture","decision_record","kb_note","action_list","action_create"]))throw new Error(`${u} adapter check failed`)}let r=await fetch(`http://127.0.0.1:${fd}/doctor/feedback-status`,{method:"POST"});if(!r.ok)throw new Error("feedback spool status check failed");let n=await r.json();if(!Number.isInteger(n.semi)||!Number.isInteger(n.colony))throw new Error("feedback spool status check failed");let i=await fetch(`http://127.0.0.1:${fd}/doctor/decision-auth`,{method:"POST"});if(!i.ok)throw new Error("decision authorization check failed");let s=await i.json();if(s.semi?.actor!=="semi"||s.colony?.actor!=="colony")throw new Error("decision authorization check failed");let o=await fetch(`http://127.0.0.1:${fd}/doctor/note-auth`,{method:"POST"});if(!o.ok)throw new Error("note authorization check failed");let a=await o.json();if(a.semi?.actor!=="semi"||a.colony?.actor!=="colony")throw new Error("note authorization check failed");let c=await fetch(`http://127.0.0.1:${fd}/doctor/services`,{method:"POST"});if(!c.ok)throw new Error("fixed host service probe failed");let l=await c.json();if(l["slack-router"]?.service!=="slack-router"||l["slack-router"]?.status!=="pass"||l["kb-gateway"]?.service!=="kb-gateway"||l["kb-gateway"]?.status!=="pass")throw new Error("fixed host service probe failed");console.log(`Worker-agent tools doctor: 2/2 adapters pass; tools=kb_get,kb_search,feedback_capture,decision_record,kb_note,action_list,action_create; decision-auth=2/2; note-auth=2/2; services=2/2; pending=semi:${n.semi},colony:${n.colony}`)}),e.command("replay-feedback").description("replay bounded actor feedback spools through the running loopback broker").action(async()=>{let r=await fetch(`http://127.0.0.1:${fd}/admin/feedback-replay`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"});if(!r.ok)throw new Error("Worker-agent feedback replay failed");console.log(JSON.stringify(await r.json()))}),e.command("connect-semi").description("fixed stdio adapter for the Semi Hermes profile").action(()=>Zzt("semi")),e.command("connect-colony").description("fixed stdio adapter for the Colony Hermes profile").action(()=>Zzt("colony"))}var Xzt,e7t,t7t,fd,V7n,Kzt,Y7n,J7n,K7n,z7n,Z7n,X7n,eZn,tZn,rZn,yTe=H(()=>{"use strict";Xzt=require("node:http"),e7t=require("node:child_process"),t7t=require("node:util");oR();Rzt();qzt();Gzt();Jzt();fd=18831,V7n=(0,t7t.promisify)(e7t.execFile),Kzt={"slack-router":"semo-slack-router.service","kb-gateway":"semo-kb-gateway.service"},Y7n=64*1024,J7n=new Set(["actor","reported_by","worker_id","device_id","installation_id","runtime_kind","profile_id","runtime_profile","url","headers","authorization","token","sql","path","file","credential"]),K7n=[{name:"kb_get",description:"Read one platform KB entry through the fixed Worker-agent actor adapter.",inputSchema:{type:"object",additionalProperties:!1,properties:{domain:{type:"string",minLength:1,maxLength:100},key:{type:"string",minLength:1,maxLength:240}},required:["domain","key"]}},{name:"kb_search",description:"Search platform KB through the fixed Worker-agent actor adapter.",inputSchema:{type:"object",additionalProperties:!1,properties:{query:{type:"string",minLength:1,maxLength:500},domain:{type:"string",minLength:1,maxLength:100},top_k:{type:"integer",minimum:1,maximum:20},min_score:{type:"number",minimum:0,maximum:1}},required:["query"]}},{name:"feedback_capture",description:"Capture bounded feedback through the fixed Worker-agent actor adapter.",inputSchema:{type:"object",additionalProperties:!1,properties:{category:{type:"string",enum:["context-failure","env-drift","policy-gap","tooling"]},summary:{type:"string",minLength:8,maxLength:500},failed_rule:{type:"string",minLength:1,maxLength:500},severity:{type:"string",enum:["low","normal","high","urgent"]},evidence:{type:"string",minLength:1,maxLength:1e4},proposed_fix:{type:"string",minLength:1,maxLength:1e4}},required:["category","summary"]}},{name:"decision_record",description:"Record one explicitly authorized decision through the fixed actor adapter.",inputSchema:{type:"object",additionalProperties:!1,properties:{domain:{type:"string",minLength:2,maxLength:63},slug:{type:"string",minLength:3,maxLength:100},content:{type:"string",minLength:30,maxLength:1e4},decision_ref:{type:"string",minLength:36,maxLength:36}},required:["domain","slug","content","decision_ref"]}},{name:"kb_note",description:"Record one fact the user asked to be kept, into the append-only note namespace. Use for status, progress, and observations \u2014 not for decisions (use decision_record) and not for corrections: an existing note is never overwritten, so a fix is a new slug.",inputSchema:{type:"object",additionalProperties:!1,properties:{domain:{type:"string",minLength:2,maxLength:63},slug:{type:"string",minLength:3,maxLength:100},content:{type:"string",minLength:30,maxLength:1e4}},required:["domain","slug","content"]}},{name:"action_list",description:"List action items through the fixed Worker-agent actor adapter. Omitting status returns every state including done and cancelled \u2014 pass status 'open' when the question is about work still outstanding.",inputSchema:{type:"object",additionalProperties:!1,properties:{status:{type:"string",enum:["open","in_progress","blocked","done","cancelled"]},project:{type:"string",minLength:2,maxLength:63},limit:{type:"integer",minimum:1,maximum:50}},required:[]}},{name:"action_create",description:"File one action item through the fixed Worker-agent actor adapter. deadline is required because the database refuses an item without one \u2014 ask the user for it, never invent a date. project must be a registered ontology domain. Omitting assignee_member assigns the item to the caller.",inputSchema:{type:"object",additionalProperties:!1,properties:{description:{type:"string",minLength:5,maxLength:2e3},project:{type:"string",minLength:2,maxLength:63},deadline:{type:"string",pattern:"^\\d{4}-\\d{2}-\\d{2}$"},priority:{type:"string",enum:["low","normal","high","urgent"]},assignee_member:{type:"string",minLength:2,maxLength:63}},required:["description","project","deadline"]}}],z7n=new Set(["low","normal","high","urgent"]),Z7n=new Set(["open","in_progress","blocked","done","cancelled"]),X7n=/^\d{4}-\d{2}-\d{2}$/,eZn=new Set(["context-failure","env-drift","policy-gap","tooling"]),tZn=new Set(["low","normal","high","urgent"]),rZn=/\bwck_[A-Za-z0-9_-]{20,}\b|\bAuthorization\b|postgres(?:ql)?:\/\/|\bDATABASE_URL\b|\bSEMO_OPS_WORKER_KB_TOKEN\b/i});var Czt={};bd(Czt,{WORKER_AGENT_PHASE2_REQUIRED_CHECKS:()=>bTe,WORKER_AGENT_PHASE3_REQUIRED_CHECKS:()=>ETe,WORKER_AGENT_PHASE4_REQUIRED_CHECKS:()=>o7t,WORKER_AGENT_PHASE7_REQUIRED_CHECKS:()=>uZn,renderWorkerAgentDoctor:()=>_Te,runWorkerAgentDoctor:()=>wTe});function TL(t,e){try{return{id:t,status:"pass",detail:e()}}catch(r){return{id:t,status:"fail",detail:r instanceof Error?r.message.replace(/wck_[A-Za-z0-9_-]+/g,"[redacted]"):"check failed"}}}function n7t(t,e){return Oc.join(t,"profiles",e)}function fZn(t){if(!vo.existsSync(t))return lR(Gs([]));let e=vo.lstatSync(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error("managed skill root is unsafe");let r=vo.readdirSync(t).sort((n,i)=>Buffer.from(n).compare(Buffer.from(i))).map(n=>{if(!/^[a-z0-9][a-z0-9-]*$/.test(n))throw new Error("managed skill name is unsafe");let i=Oc.join(t,n,"SKILL.md"),s=vo.lstatSync(i);if(!s.isFile()||s.isSymbolicLink())throw new Error("managed skill file is unsafe");return{name:n,sha256:lR(vo.readFileSync(i))}});return lR(Gs(r))}function a7t(t){for(let e of t){if(!vo.existsSync(e))continue;let r=vo.lstatSync(e);if(r.isSymbolicLink())throw new Error("managed profile contains a symlink");if(r.isDirectory())a7t(vo.readdirSync(e).map(n=>Oc.join(e,n)));else if(r.isFile()&&dZn.test(vo.readFileSync(e,"utf8")))throw new Error("managed profile contains a forbidden credential marker")}}async function cR(t,e,r){try{let n=e?await e():hZn(r);return{id:t,status:n.status,detail:n.detail.replace(/wck_[A-Za-z0-9_-]+/g,"[redacted]")}}catch{return{id:t,status:"fail",detail:"probe failed with redacted error"}}}function AZn(t){let e=t.fetchImpl??fetch,r,n,i,s=()=>(r??=e(`http://127.0.0.1:${fd}/doctor/feedback-auth`,{method:"POST"}).then(async a=>{if(!a.ok)throw new Error("actor feedback authorization probe failed");return await a.json()}),r),o=()=>(n??=e(`http://127.0.0.1:${fd}/doctor/note-auth`,{method:"POST"}).then(async a=>{if(!a.ok)throw new Error("actor note authorization probe failed");return await a.json()}),n);return{gatewayReleaseAuth:async()=>{await lp({env:t.env??process.env,surface:"semo-ops",fetchImpl:e}).fetchActiveRelease();let c=await e(`http://127.0.0.1:${fd}/doctor/release-deny`,{method:"POST"});if(!c.ok)throw new Error("actor release denial probe failed");let l=await c.json();if(l.semi!==403||l.colony!==403)throw new Error("actor release denial probe failed");return{status:"pass",detail:"host release read allowed; actor release reads denied 2/2"}},kbRead:async a=>{let c=await V7(a,JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"kb_get",arguments:{domain:"semicolon",key:"glossary/hive-service"}}}),e),l=c?JSON.parse(c):null;if(!l?.result?.content?.[0]?.text||l.result.isError)throw new Error("actor KB read failed");let u=JSON.parse(l.result.content[0].text);if(u.actor!==a||!u.correlation_id||!u.result?.content?.trim())throw new Error("actor KB read result is incomplete");return{status:"pass",detail:`${a} KB read non-empty; correlation=${u.correlation_id}`}},feedbackAuth:async a=>{let l=(await s())[a];if(l?.actor!==a||!l.correlation_id)throw new Error("actor feedback authorization probe failed");return{status:"pass",detail:`${a} feedback authorized; correlation=${l.correlation_id}`}},noteAuth:async a=>{let l=(await o())[a];if(l?.actor!==a||!l.correlation_id)throw new Error("actor note authorization probe failed");return{status:"pass",detail:`${a} note authorized; correlation=${l.correlation_id}`}},service:async a=>{i??=e(`http://127.0.0.1:${fd}/doctor/services`,{method:"POST"}).then(async l=>{if(!l.ok)throw new Error("fixed host service probe failed");return await l.json()});let c=(await i)[a];if(c?.service!==a||c.status!=="pass")throw new Error("fixed host service probe failed");return{status:"pass",detail:`${a} active, enabled, and running`}}}}async function wTe(t={}){let e=Oc.resolve(t.homeDir??process.env.HOME??s7t.homedir()),r=FE(e),n=null,i=null,s=new Map;try{if(n=tR(r.installationState),!n)throw new Error("Agent installation state is missing");s.set("agent:installation-state",{id:"agent:installation-state",status:"pass",detail:"fixed Agent installation state is valid"})}catch(g){s.set("agent:installation-state",{id:"agent:installation-state",status:"fail",detail:g instanceof Error?g.message:"Agent installation state is invalid"})}try{if(i=t.expectedReleaseState??rR(r.releaseState),!i)throw new Error("Agent release state is missing");s.set("agent:release-state",{id:"agent:release-state",status:"pass",detail:t.expectedReleaseState?"candidate Agent release receipt is valid during apply":"applied Agent release receipt is valid"})}catch(g){s.set("agent:release-state",{id:"agent:release-state",status:"fail",detail:g instanceof Error?g.message:"Agent release state is invalid"})}let o=t.requiredChecks??i?.required_doctor_checks??[...bTe],a=ETe.slice(-3).some(g=>o.includes(g)),c=o7t.slice(-2).some(g=>o.includes(g)),l=t.probes??(a||c?AZn(t):void 0),u=n,d=i;s.set("agent:gateway-release-auth",await cR("agent:gateway-release-auth",l?.gatewayReleaseAuth,"Phase 3"));for(let g of dd){let m=u?n7t(u.hermes_home,g.runtime_profile):"";s.set(`agent:profile:${g.actor_id}`,TL(`agent:profile:${g.actor_id}`,()=>{if(!u)throw new Error("Agent installation state is unavailable");let y=vo.lstatSync(m),b=vo.lstatSync(Oc.join(m,"SOUL.md"));if(!y.isDirectory()||y.isSymbolicLink()||!b.isFile()||b.isSymbolicLink())throw new Error("Hermes profile or persona is unsafe");return`${g.runtime_profile} profile and persona are regular paths`})),s.set(`agent:context-digest:${g.actor_id}`,TL(`agent:context-digest:${g.actor_id}`,()=>{if(!d||!u)throw new Error("Agent state is unavailable");let y=vo.readFileSync(Oc.join(m,"SOUL.md"),"utf8"),b=TI.extractManaged(y,g.actor_id);if(b===null)throw new Error("managed context block is missing");let w=lR(`${b}
1537
+ `)})}),e.command("doctor").description("verify both fixed MCP adapters expose exactly five tools").action(async()=>{for(let d of["semi","colony"]){let f=await V7(d,JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/list"})),h=f?JSON.parse(f):null;if(JSON.stringify(h?.result?.tools?.map(A=>A.name))!==JSON.stringify(["kb_get","kb_search","feedback_capture","decision_record","kb_note","action_list","action_create"]))throw new Error(`${d} adapter check failed`)}let r=await fetch(`http://127.0.0.1:${fd}/doctor/feedback-status`,{method:"POST"});if(!r.ok)throw new Error("feedback spool status check failed");let n=await r.json();if(!Number.isInteger(n.semi)||!Number.isInteger(n.colony))throw new Error("feedback spool status check failed");let i=await fetch(`http://127.0.0.1:${fd}/doctor/decision-auth`,{method:"POST"});if(!i.ok)throw new Error("decision authorization check failed");let s=await i.json();if(s.semi?.actor!=="semi"||s.colony?.actor!=="colony")throw new Error("decision authorization check failed");let o=await fetch(`http://127.0.0.1:${fd}/doctor/note-auth`,{method:"POST"});if(!o.ok)throw new Error("note authorization check failed");let a=await o.json();if(a.semi?.actor!=="semi"||a.colony?.actor!=="colony")throw new Error("note authorization check failed");let c=await fetch(`http://127.0.0.1:${fd}/doctor/services`,{method:"POST"});if(!c.ok)throw new Error("fixed host service probe failed");let l=await c.json(),u=["slack-router","kb-gateway"].filter(d=>l[d]?.service!==d||l[d]?.status!=="pass");if(u.length>0){let d=u.map(f=>`${f}: ${l[f]?.reason??"no receipt"}`).join("; ");throw new Error(`fixed host service probe failed \u2014 ${d}`)}console.log(`Worker-agent tools doctor: 2/2 adapters pass; tools=kb_get,kb_search,feedback_capture,decision_record,kb_note,action_list,action_create; decision-auth=2/2; note-auth=2/2; services=2/2; pending=semi:${n.semi},colony:${n.colony}`)}),e.command("replay-feedback").description("replay bounded actor feedback spools through the running loopback broker").action(async()=>{let r=await fetch(`http://127.0.0.1:${fd}/admin/feedback-replay`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"});if(!r.ok)throw new Error("Worker-agent feedback replay failed");console.log(JSON.stringify(await r.json()))}),e.command("connect-semi").description("fixed stdio adapter for the Semi Hermes profile").action(()=>Zzt("semi")),e.command("connect-colony").description("fixed stdio adapter for the Colony Hermes profile").action(()=>Zzt("colony"))}var Xzt,e7t,t7t,fd,V7n,Kzt,Y7n,J7n,K7n,z7n,Z7n,X7n,eZn,tZn,rZn,yTe=H(()=>{"use strict";Xzt=require("node:http"),e7t=require("node:child_process"),t7t=require("node:util");oR();Rzt();qzt();Gzt();Jzt();fd=18831,V7n=(0,t7t.promisify)(e7t.execFile),Kzt={"slack-router":"semo-slack-router.service","kb-gateway":"semo-kb-gateway.service"},Y7n=64*1024,J7n=new Set(["actor","reported_by","worker_id","device_id","installation_id","runtime_kind","profile_id","runtime_profile","url","headers","authorization","token","sql","path","file","credential"]),K7n=[{name:"kb_get",description:"Read one platform KB entry through the fixed Worker-agent actor adapter.",inputSchema:{type:"object",additionalProperties:!1,properties:{domain:{type:"string",minLength:1,maxLength:100},key:{type:"string",minLength:1,maxLength:240}},required:["domain","key"]}},{name:"kb_search",description:"Search platform KB through the fixed Worker-agent actor adapter.",inputSchema:{type:"object",additionalProperties:!1,properties:{query:{type:"string",minLength:1,maxLength:500},domain:{type:"string",minLength:1,maxLength:100},top_k:{type:"integer",minimum:1,maximum:20},min_score:{type:"number",minimum:0,maximum:1}},required:["query"]}},{name:"feedback_capture",description:"Capture bounded feedback through the fixed Worker-agent actor adapter.",inputSchema:{type:"object",additionalProperties:!1,properties:{category:{type:"string",enum:["context-failure","env-drift","policy-gap","tooling"]},summary:{type:"string",minLength:8,maxLength:500},failed_rule:{type:"string",minLength:1,maxLength:500},severity:{type:"string",enum:["low","normal","high","urgent"]},evidence:{type:"string",minLength:1,maxLength:1e4},proposed_fix:{type:"string",minLength:1,maxLength:1e4}},required:["category","summary"]}},{name:"decision_record",description:"Record one explicitly authorized decision through the fixed actor adapter.",inputSchema:{type:"object",additionalProperties:!1,properties:{domain:{type:"string",minLength:2,maxLength:63},slug:{type:"string",minLength:3,maxLength:100},content:{type:"string",minLength:30,maxLength:1e4},decision_ref:{type:"string",minLength:36,maxLength:36}},required:["domain","slug","content","decision_ref"]}},{name:"kb_note",description:"Record one fact the user asked to be kept, into the append-only note namespace. Use for status, progress, and observations \u2014 not for decisions (use decision_record) and not for corrections: an existing note is never overwritten, so a fix is a new slug.",inputSchema:{type:"object",additionalProperties:!1,properties:{domain:{type:"string",minLength:2,maxLength:63},slug:{type:"string",minLength:3,maxLength:100},content:{type:"string",minLength:30,maxLength:1e4}},required:["domain","slug","content"]}},{name:"action_list",description:"List action items through the fixed Worker-agent actor adapter. Omitting status returns every state including done and cancelled \u2014 pass status 'open' when the question is about work still outstanding.",inputSchema:{type:"object",additionalProperties:!1,properties:{status:{type:"string",enum:["open","in_progress","blocked","done","cancelled"]},project:{type:"string",minLength:2,maxLength:63},limit:{type:"integer",minimum:1,maximum:50}},required:[]}},{name:"action_create",description:"File one action item through the fixed Worker-agent actor adapter. deadline is required because the database refuses an item without one \u2014 ask the user for it, never invent a date. project must be a registered ontology domain. Omitting assignee_member assigns the item to the caller.",inputSchema:{type:"object",additionalProperties:!1,properties:{description:{type:"string",minLength:5,maxLength:2e3},project:{type:"string",minLength:2,maxLength:63},deadline:{type:"string",pattern:"^\\d{4}-\\d{2}-\\d{2}$"},priority:{type:"string",enum:["low","normal","high","urgent"]},assignee_member:{type:"string",minLength:2,maxLength:63}},required:["description","project","deadline"]}}],z7n=new Set(["low","normal","high","urgent"]),Z7n=new Set(["open","in_progress","blocked","done","cancelled"]),X7n=/^\d{4}-\d{2}-\d{2}$/,eZn=new Set(["context-failure","env-drift","policy-gap","tooling"]),tZn=new Set(["low","normal","high","urgent"]),rZn=/\bwck_[A-Za-z0-9_-]{20,}\b|\bAuthorization\b|postgres(?:ql)?:\/\/|\bDATABASE_URL\b|\bSEMO_OPS_WORKER_KB_TOKEN\b/i});var Czt={};bd(Czt,{WORKER_AGENT_PHASE2_REQUIRED_CHECKS:()=>bTe,WORKER_AGENT_PHASE3_REQUIRED_CHECKS:()=>ETe,WORKER_AGENT_PHASE4_REQUIRED_CHECKS:()=>o7t,WORKER_AGENT_PHASE7_REQUIRED_CHECKS:()=>uZn,renderWorkerAgentDoctor:()=>_Te,runWorkerAgentDoctor:()=>wTe});function TL(t,e){try{return{id:t,status:"pass",detail:e()}}catch(r){return{id:t,status:"fail",detail:r instanceof Error?r.message.replace(/wck_[A-Za-z0-9_-]+/g,"[redacted]"):"check failed"}}}function n7t(t,e){return Oc.join(t,"profiles",e)}function fZn(t){if(!vo.existsSync(t))return lR(Gs([]));let e=vo.lstatSync(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error("managed skill root is unsafe");let r=vo.readdirSync(t).sort((n,i)=>Buffer.from(n).compare(Buffer.from(i))).map(n=>{if(!/^[a-z0-9][a-z0-9-]*$/.test(n))throw new Error("managed skill name is unsafe");let i=Oc.join(t,n,"SKILL.md"),s=vo.lstatSync(i);if(!s.isFile()||s.isSymbolicLink())throw new Error("managed skill file is unsafe");return{name:n,sha256:lR(vo.readFileSync(i))}});return lR(Gs(r))}function a7t(t){for(let e of t){if(!vo.existsSync(e))continue;let r=vo.lstatSync(e);if(r.isSymbolicLink())throw new Error("managed profile contains a symlink");if(r.isDirectory())a7t(vo.readdirSync(e).map(n=>Oc.join(e,n)));else if(r.isFile()&&dZn.test(vo.readFileSync(e,"utf8")))throw new Error("managed profile contains a forbidden credential marker")}}async function cR(t,e,r){try{let n=e?await e():hZn(r);return{id:t,status:n.status,detail:n.detail.replace(/wck_[A-Za-z0-9_-]+/g,"[redacted]")}}catch{return{id:t,status:"fail",detail:"probe failed with redacted error"}}}function AZn(t){let e=t.fetchImpl??fetch,r,n,i,s=()=>(r??=e(`http://127.0.0.1:${fd}/doctor/feedback-auth`,{method:"POST"}).then(async a=>{if(!a.ok)throw new Error("actor feedback authorization probe failed");return await a.json()}),r),o=()=>(n??=e(`http://127.0.0.1:${fd}/doctor/note-auth`,{method:"POST"}).then(async a=>{if(!a.ok)throw new Error("actor note authorization probe failed");return await a.json()}),n);return{gatewayReleaseAuth:async()=>{await lp({env:t.env??process.env,surface:"semo-ops",fetchImpl:e}).fetchActiveRelease();let c=await e(`http://127.0.0.1:${fd}/doctor/release-deny`,{method:"POST"});if(!c.ok)throw new Error("actor release denial probe failed");let l=await c.json();if(l.semi!==403||l.colony!==403)throw new Error("actor release denial probe failed");return{status:"pass",detail:"host release read allowed; actor release reads denied 2/2"}},kbRead:async a=>{let c=await V7(a,JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"kb_get",arguments:{domain:"semicolon",key:"glossary/hive-service"}}}),e),l=c?JSON.parse(c):null;if(!l?.result?.content?.[0]?.text||l.result.isError)throw new Error("actor KB read failed");let u=JSON.parse(l.result.content[0].text);if(u.actor!==a||!u.correlation_id||!u.result?.content?.trim())throw new Error("actor KB read result is incomplete");return{status:"pass",detail:`${a} KB read non-empty; correlation=${u.correlation_id}`}},feedbackAuth:async a=>{let l=(await s())[a];if(l?.actor!==a||!l.correlation_id)throw new Error("actor feedback authorization probe failed");return{status:"pass",detail:`${a} feedback authorized; correlation=${l.correlation_id}`}},noteAuth:async a=>{let l=(await o())[a];if(l?.actor!==a||!l.correlation_id)throw new Error("actor note authorization probe failed");return{status:"pass",detail:`${a} note authorized; correlation=${l.correlation_id}`}},service:async a=>{i??=e(`http://127.0.0.1:${fd}/doctor/services`,{method:"POST"}).then(async l=>{if(!l.ok)throw new Error("fixed host service probe failed");return await l.json()});let c=(await i)[a];if(c?.service!==a||c.status!=="pass")throw new Error("fixed host service probe failed");return{status:"pass",detail:`${a} active, enabled, and running`}}}}async function wTe(t={}){let e=Oc.resolve(t.homeDir??process.env.HOME??s7t.homedir()),r=FE(e),n=null,i=null,s=new Map;try{if(n=tR(r.installationState),!n)throw new Error("Agent installation state is missing");s.set("agent:installation-state",{id:"agent:installation-state",status:"pass",detail:"fixed Agent installation state is valid"})}catch(g){s.set("agent:installation-state",{id:"agent:installation-state",status:"fail",detail:g instanceof Error?g.message:"Agent installation state is invalid"})}try{if(i=t.expectedReleaseState??rR(r.releaseState),!i)throw new Error("Agent release state is missing");s.set("agent:release-state",{id:"agent:release-state",status:"pass",detail:t.expectedReleaseState?"candidate Agent release receipt is valid during apply":"applied Agent release receipt is valid"})}catch(g){s.set("agent:release-state",{id:"agent:release-state",status:"fail",detail:g instanceof Error?g.message:"Agent release state is invalid"})}let o=t.requiredChecks??i?.required_doctor_checks??[...bTe],a=ETe.slice(-3).some(g=>o.includes(g)),c=o7t.slice(-2).some(g=>o.includes(g)),l=t.probes??(a||c?AZn(t):void 0),u=n,d=i;s.set("agent:gateway-release-auth",await cR("agent:gateway-release-auth",l?.gatewayReleaseAuth,"Phase 3"));for(let g of dd){let m=u?n7t(u.hermes_home,g.runtime_profile):"";s.set(`agent:profile:${g.actor_id}`,TL(`agent:profile:${g.actor_id}`,()=>{if(!u)throw new Error("Agent installation state is unavailable");let y=vo.lstatSync(m),b=vo.lstatSync(Oc.join(m,"SOUL.md"));if(!y.isDirectory()||y.isSymbolicLink()||!b.isFile()||b.isSymbolicLink())throw new Error("Hermes profile or persona is unsafe");return`${g.runtime_profile} profile and persona are regular paths`})),s.set(`agent:context-digest:${g.actor_id}`,TL(`agent:context-digest:${g.actor_id}`,()=>{if(!d||!u)throw new Error("Agent state is unavailable");let y=vo.readFileSync(Oc.join(m,"SOUL.md"),"utf8"),b=TI.extractManaged(y,g.actor_id);if(b===null)throw new Error("managed context block is missing");let w=lR(`${b}
1538
1538
  `),E=d.managed_target_digests[`profile:${g.actor_id}:context`];if(!E||w!==E)throw new Error("managed context digest mismatch");return"managed context digest matches the applied receipt"})),s.set(`agent:skill-digests:${g.actor_id}`,TL(`agent:skill-digests:${g.actor_id}`,()=>{if(!d||!u)throw new Error("Agent state is unavailable");let y=fZn(Oc.join(m,"skills","semo-ops-managed")),b=d.managed_target_digests[`profile:${g.actor_id}:skills`];if(!b||y!==b)throw new Error("managed skill digest mismatch");return"managed skill digest matches the applied receipt"})),s.set(`agent:tools:${g.actor_id}`,TL(`agent:tools:${g.actor_id}`,()=>{if(!d||!u)throw new Error("Agent state is unavailable");let y=Oc.join(m,"semo-ops-tools.json"),b=vo.lstatSync(y);if(!b.isFile()||b.isSymbolicLink())throw new Error("tool declaration is unsafe");let w=d.managed_target_digests[`profile:${g.actor_id}:tools`];if(!w||lR(vo.readFileSync(y))!==w)throw new Error("tool declaration digest mismatch");let E=Oc.join(m,"config.yaml"),_=d.managed_target_digests[`profile:${g.actor_id}:mcp`],I=TI.extractWorkerAgentMcp(vo.readFileSync(E,"utf8"),g.actor_id);if(!_||!I||lR(I)!==_)throw new Error("MCP projection digest mismatch");return"tool declaration and MCP projection digests match the applied receipt"})),s.set(`agent:kb-read:${g.actor_id}`,await cR(`agent:kb-read:${g.actor_id}`,l?.kbRead?()=>l.kbRead(g.actor_id):void 0,"Phase 3")),s.set(`agent:feedback-auth:${g.actor_id}`,await cR(`agent:feedback-auth:${g.actor_id}`,l?.feedbackAuth?()=>l.feedbackAuth(g.actor_id):void 0,"Phase 4")),s.set(`agent:note-auth:${g.actor_id}`,await cR(`agent:note-auth:${g.actor_id}`,l?.noteAuth?()=>l.noteAuth(g.actor_id):void 0,"Phase 8"))}s.set("agent:service:slack-router",await cR("agent:service:slack-router",l?.service?()=>l.service("slack-router"):void 0,"Phase 7")),s.set("agent:service:kb-gateway",await cR("agent:service:kb-gateway",l?.service?()=>l.service("kb-gateway"):void 0,"Phase 7")),s.set("agent:no-token-in-profile",TL("agent:no-token-in-profile",()=>{if(!u)throw new Error("Agent installation state is unavailable");let g=[r.installationState,r.releaseState];for(let m of dd){let y=n7t(u.hermes_home,m.runtime_profile);g.push(Oc.join(y,"SOUL.md"),Oc.join(y,"skills","semo-ops-managed"),Oc.join(y,"semo-ops-tools.json"),Oc.join(y,"config.yaml"))}return a7t(g),"no forbidden credential marker found in managed profile or receipt files"}));let f=O_.map(g=>s.get(g)),h=new Set(O_);return{status:o.every(g=>h.has(g)&&s.get(g)?.status==="pass")?"pass":"fail",required_checks:o,checks:f}}function _Te(t){return[`SEMO Ops Worker-agent doctor: ${t.status}`,...t.checks.map(e=>` ${e.status.toUpperCase()} ${e.id} \u2014 ${e.detail}`)].join(`
1539
1539
  `)}var i7t,vo,s7t,Oc,bTe,ETe,o7t,uZn,lR,dZn,hZn,aTe=H(()=>{"use strict";i7t=require("node:crypto"),vo=v(require("node:fs")),s7t=v(require("node:os")),Oc=v(require("node:path"));Mh();SL();j7();bB();yTe();bTe=["agent:installation-state","agent:release-state","agent:profile:semi","agent:profile:colony","agent:context-digest:semi","agent:context-digest:colony","agent:skill-digests:semi","agent:skill-digests:colony","agent:tools:semi","agent:tools:colony","agent:no-token-in-profile"],ETe=[...bTe,"agent:gateway-release-auth","agent:kb-read:semi","agent:kb-read:colony"],o7t=[...ETe,"agent:feedback-auth:semi","agent:feedback-auth:colony"],uZn=[...O_],lR=t=>(0,i7t.createHash)("sha256").update(t).digest("hex"),dZn=/DATABASE_URL|postgres:\/\/|SEMO_OPS_WORKER_KB_TOKEN|\bAuthorization\b|\bwck_[A-Za-z0-9_-]+/i;hZn=t=>({status:"warn",detail:`deferred to ${t}`})});var TMe=v(RMe(),1),{program:bXn,createCommand:EXn,createArgument:wXn,createOption:_Xn,CommanderError:CXn,InvalidArgumentError:IXn,InvalidOptionArgumentError:vXn,Command:MMe,Argument:kXn,Option:xXn,Help:BXn}=TMe.default;var x=v(Ne()),hd=v(Gc()),Z7=v(aW()),PL=require("child_process"),Yr=v(require("fs")),Rs=v(require("path")),NI=v(require("os"));nse();Zf();ur();var ys=v(Ne()),Gse=v(Gc()),rl=v(require("fs")),tl=v(require("path")),qT=v(require("os"));ur();so();var gt=v(require("fs")),Yt=v(require("path")),FHe=v(require("os")),RW=require("child_process");ur();ru();LT();var UHe=".semicolony-managed.json";function n1r(t){if(Yt.basename(t)!==".claude")throw new Error(`managed projection interlock requires a .claude directory, got: ${t}`);let e=Yt.dirname(t),r=LA({homeDirectory:e});NA(r.journalPath);let n=lb(r.receiptPath);if(!n)return{skipSkillMutation:!1,receiptSkillCount:0};let i=Yt.join(t,"skills");if(Yt.resolve(n.roots.claude.path)!==Yt.resolve(i))throw new Error("managed projection receipt Claude root mismatch; refusing global-cache skill mutation");return{skipSkillMutation:!0,receiptSkillCount:Object.keys(n.skills).length}}function i1r(t,e){let r=0,n=Yt.join(t,"skills"),i=qHe(n),s=!1,o=Yt.join(e,"skills");if(!gt.existsSync(o))return 0;gt.mkdirSync(n,{recursive:!0});let a=gt.readdirSync(o,{withFileTypes:!0});for(let c of a){if(!c.isDirectory())continue;let l=Yt.join(o,c.name),u=Yt.join(n,c.name);try{if(gt.existsSync(u)&&!i.has(c.name)){console.warn(`\u26A0\uFE0F unmanaged \uB3D9\uBA85 \uC2A4\uD0AC \uBCF4\uC874 \u2014 tenant overlay \uC2A4\uD0B5: ${c.name}`);continue}gt.existsSync(u)&&Qk(u),gt.cpSync(l,u,{recursive:!0}),i.has(c.name)||(i.add(c.name),s=!0),r++}catch(d){console.warn(`\u26A0\uFE0F tenant overlay \uC2E4\uD328 (skills/${c.name}): ${d.message}`)}}return s&&jHe(n,[...i]),r}function s1r(t,e){let r=0,n=Yt.join(e,"commands"),i=Yt.join(t,"commands");if(!gt.existsSync(n))return 0;gt.mkdirSync(i,{recursive:!0});let s=gt.readdirSync(n,{withFileTypes:!0});for(let o of s){if(!o.isDirectory())continue;let a=Yt.join(n,o.name),c=Yt.join(i,o.name);gt.mkdirSync(c,{recursive:!0});let l=gt.readdirSync(a);for(let u of l)if(u.endsWith(".md"))try{gt.cpSync(Yt.join(a,u),Yt.join(c,u)),r++}catch(d){console.warn(`\u26A0\uFE0F tenant overlay \uC2E4\uD328 (commands/${o.name}/${u}): ${d.message}`)}}return r}function o1r(t,e){let r=0,n=Yt.join(e,"agents"),i=Yt.join(t,"agents");if(!gt.existsSync(n))return 0;gt.mkdirSync(i,{recursive:!0});let s=gt.readdirSync(n,{withFileTypes:!0});for(let o of s){if(!o.isDirectory())continue;let a=Yt.join(n,o.name),c=Yt.join(i,o.name);try{gt.existsSync(c)&&Qk(c),gt.cpSync(a,c,{recursive:!0}),r++}catch(l){console.warn(`\u26A0\uFE0F tenant overlay \uC2E4\uD328 (agents/${o.name}): ${l.message}`)}}return r}function a1r(t,e,r={}){let n=0;return r.skipSkills||(n+=i1r(t,e)),n+=s1r(t,e),n+=o1r(t,e),n}var c1r=process.platform==="win32";function Qk(t){if(gt.existsSync(t))if(c1r)try{gt.lstatSync(t).isSymbolicLink()?(0,RW.execSync)(`cmd /c "rmdir "${t}""`,{stdio:"pipe"}):(0,RW.execSync)(`cmd /c "rd /s /q "${t}""`,{stdio:"pipe"})}catch{gt.rmSync(t,{recursive:!0,force:!0})}else(0,RW.execSync)(`rm -rf "${t}"`,{stdio:"pipe"})}function l1r(t,e){if(!e||e.length===0)return t;let r=`
1540
1540
  > **Agents:** ${e.join(", ")}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@team-semicolon/semicolony-cli",
3
- "version": "4.18.109",
3
+ "version": "4.18.111",
4
4
  "description": "SemiColony CLI - AI operations and agent orchestration installer",
5
5
  "main": "dist/bundle.js",
6
6
  "bin": {