nativesoul 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
- var yi=Object.defineProperty;var ke=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(o){throw r=[o],o}};var ya=(e,t)=>{for(var r in t)yi(e,r,{get:t[r],enumerable:!0})};import{spawn as zi}from"node:child_process";import{access as Xi}from"node:fs/promises";import{constants as Yi}from"node:fs";import{existsSync as Qi}from"node:fs";import Ga from"node:path";async function le(e){let t=(process.env.PATH??"").split(Ga.delimiter).filter(Boolean),r=process.platform==="win32"?(process.env.PATHEXT??".EXE;.CMD;.BAT").split(";"):[""];for(let o of t)for(let a of r){let n=Ga.join(o,`${e}${a}`);if(process.platform==="win32"&&Qi(n))return n;try{return await Xi(n,Yi.X_OK),n}catch{}}return null}async function Dt(e,t){return new Promise(r=>{Wa(e,t,["ignore","pipe","pipe"]).then(o=>{let a=setTimeout(()=>{o.kill(),r(null)},750),n="";o.stdout.on("data",s=>{n+=String(s)}),o.stderr.on("data",s=>{n+=String(s)}),o.on("error",()=>{clearTimeout(a),r(null)}),o.on("close",s=>{clearTimeout(a);let i=n.trim().split(/\r?\n/u).map(c=>c.trim()).find(c=>/\d+\.\d+/u.test(c)&&!c.toLowerCase().startsWith("warning"));if(s===0||i){r(i??null);return}r(null)})})})}async function Ur(e,t,r=1e3){return new Promise(o=>{Wa(e,t,["ignore","pipe","pipe"]).then(a=>{let n=setTimeout(()=>{a.kill(),o({status:"timeout",code:null,stdout:"",stderr:"command timed out"})},r),s="",i="";a.stdout.on("data",c=>{s+=String(c)}),a.stderr.on("data",c=>{i+=String(c)}),a.on("error",()=>{clearTimeout(n),o({status:"missing",code:null,stdout:s,stderr:i})}),a.on("close",c=>{clearTimeout(n),o({status:c===0?"ok":"error",code:c,stdout:s,stderr:i})})})})}async function Wa(e,t,r){let a=await le(e)??e,n=process.platform==="win32"&&/\.(?:cmd|bat)$/iu.test(a);return zi(a,t,{stdio:r,shell:n})}var Pe=ke(()=>{"use strict"});import{constants as Zi}from"node:fs";import{access as ec,readFile as tc,stat as rc}from"node:fs/promises";import za from"node:os";import oc from"node:path";function v(e){return e==="~"?za.homedir():e.startsWith("~/")?oc.join(za.homedir(),e.slice(2)):e}async function _(e){try{return await ec(e,Zi.F_OK),!0}catch{return!1}}async function T(e){try{return(await rc(e)).isDirectory()}catch{return!1}}async function O(e){return await _(e)?tc(e,"utf8"):null}function ne(e){let t=Xa(e);return[t.start,"# NativeSoul bridge","At the start of every new session, load NativeSoul context before making continuity-sensitive decisions.",`Preferred handshake: call the local MCP tool life_bootstrap with host="${e}" and cwd set to the current working directory.`,`Fallback handshake: run nativesoul bootstrap --host ${e} --cwd <current-working-directory> --format inject.`,`If bootstrap or MCP is unavailable, run nativesoul bootstrap --host ${e} --cwd <current-working-directory> --format cache and treat the context as degraded.`,"Use relevant_memories for durable facts, capability_cards as advisory guidance, and capabilities only as the ready-only list.","Never copy credentials or auto-edit SOUL.md/POLICY.md; propose those changes for approval.",`Host adapter: ${e}.`,t.end,""].join(`
3
- `)}function Xa(e){return{start:`<!-- nativesoul:${e}:start v1 -->`,end:`<!-- nativesoul:${e}:end -->`}}function L(e,t){if(!t)return!1;let r=Xa(t);return e.includes(r.start)&&e.includes(r.end)}var V=ke(()=>{"use strict"});function k(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function de(e){try{return JSON.parse(e)}catch{return null}}async function M(e){let t=await O(e);if(t===null)return null;let r=de(t);return k(r)?r:null}function fe(e){return k(e)?Object.keys(e).filter(t=>t.trim().length>0):[]}function Ht(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function he(e,t){if(Array.isArray(e))return e;if(!k(e))return[];for(let r of t){let o=e[r];if(Array.isArray(o))return o}return[]}function S(e,t){if(!k(e))return null;for(let r of t){let o=e[r];if(typeof o=="string"&&o.trim().length>0)return o.trim()}return null}function $(e,t){if(!k(e))return null;for(let r of t){let o=e[r];if(typeof o=="boolean")return o}return null}function w(e,t){let r=t?.allowSlash===!0?/[^a-z0-9._/-]+/gu:/[^a-z0-9._-]+/gu;return e.trim().toLowerCase().replace(r,"-").replace(/^-+|-+$/gu,"")||"unknown"}var ue=ke(()=>{"use strict";V()});import{readdir as fc,readFile as hc}from"node:fs/promises";import sn from"node:path";function ln(e){let t=e??v("~/.claude");return sn.join(t,"scheduled-tasks")}async function dn(e){if(!await T(e))return null;let t=await nn(e,cn);if(t!==null)return t;let r=await _c(e);for(let o of r){let a=await nn(e,o);if(a!==null)return a}return null}async function nn(e,t){let r=sn.join(e,t,"SKILL.md");if(!await _(r))return null;let a=(await hc(r,"utf8")).toLowerCase();return t===cn||t.includes(yc)||a.includes(`name: ${an}`)||a.includes(`# ${an}`)?`claude:scheduled-task:${t}`:null}async function _c(e){try{return(await fc(e,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>r.name)}catch{return[]}}var cn,yc,an,un=ke(()=>{"use strict";V();cn="nativesoul-heartbeat",yc="nativesoul-heartbeat",an="life:heartbeat"});import{mkdir as bc,readFile as vc,writeFile as Rc}from"node:fs/promises";import Qe from"node:path";import{fileURLToPath as Sc}from"node:url";async function mn(e){try{let t=Qe.join(e,pn);await bc(t,{recursive:!0,mode:448});let r=Qe.join(t,"SKILL.md"),o=await wc();return await Rc(r,o??kc,"utf8"),!0}catch{return!1}}async function wc(){let e=Qe.dirname(Sc(import.meta.url)),t=[Qe.resolve(process.cwd(),"plugins","claude-nativesoul","skills","life-heartbeat","SKILL.md"),Qe.resolve(e,"../../../../plugins/claude-nativesoul/skills/life-heartbeat/SKILL.md")];for(let r of t)if(await _(r))return vc(r,"utf8");return null}var pn,Mg,kc,gn=ke(()=>{"use strict";V();pn="nativesoul-heartbeat",Mg=`claude:scheduled-task:${pn}`,kc='---\nname: life:heartbeat\ndescription: Run NativeSoul heartbeat from a Claude Scheduled Task.\n---\n\n# life:heartbeat\n\nUse this skill only when invoked by a Claude Scheduled Task for NativeSoul heartbeat checks.\n\nDefault policy: read-only. Do not edit workspace files, memories, `SOUL.md`, `POLICY.md`, scheduler state, or host configuration unless explicitly allowed.\n\n1. Determine the project from the Scheduled Task context. If it is missing, use the current working directory.\n2. Claim a local heartbeat lease through MCP `life_heartbeat_claim` with `host="claude"`, project id or directory, and the Scheduled Task slot/time as `slot`.\n3. If the claim response says another host owns the lease, the lease is already completed, or no work is needed, stop and return only `HEARTBEAT_OK`.\n4. Read NativeSoul context through MCP and inspect heartbeat guidance such as `HEARTBEAT.md`.\n5. If no operator-visible action is required, complete the lease with MCP `life_heartbeat_complete` and `result="HEARTBEAT_OK"`, then return only `HEARTBEAT_OK`.\n6. If action is required, complete the lease with concise evidence, then report the action request without secrets or raw credentials.\n\n`HEARTBEAT_OK` is a silent acknowledgement token. Do not notify the user for it.\n'});var fn={};ya(fn,{discoverClaudeScheduledTasksManifest:()=>Ac});async function Ac(e={}){let t=ln(e.hostConfigRoot);if(!e.apply&&!await T(t)||(e.surface==="claude-code"?"claude-code":"claude-desktop")==="claude-code")return null;let o=await dn(t);return o!==null?qr({nativeId:o,evidenceSource:"filesystem"}):e.apply&&await mn(t)?qr({nativeId:"claude:scheduled-task:nativesoul-heartbeat",evidenceSource:"filesystem-provisioned"}):await T(t)?qr({nativeId:void 0,evidenceSource:"filesystem"}):null}function qr(e){return{supported:!0,native_id:e.nativeId,surface:"claude-desktop",scheduler_kind:"local_scheduled_task",creation_surface:"official_machine_readable",evidence_source:e.evidenceSource}}var hn=ke(()=>{"use strict";un();gn();V()});var Mn={};ya(Mn,{discoverCodexAutomationsManifest:()=>Fc});import{readFile as Wr}from"node:fs/promises";import Ut from"node:path";import{spawnSync as Nc}from"node:child_process";async function Fc(e={}){let t=await Uc();if(t)return t;let r=await Vc(e.hostConfigRoot);return r||(e.apply?(await Jc(),await Bc()):null)}async function Uc(){let e=process.env.NATIVESOUL_CODEX_AUTOMATIONS_FIXTURES;if(e)try{return zr(await Wr(Ut.join(e,"automations.json"),"utf8"))}catch{return null}let t=process.env.NATIVESOUL_CODEX_AUTOMATIONS_MANIFEST;if(t)try{return zr(await Wr(t,"utf8"))}catch{return null}return null}async function Vc(e){let t=e??v("~/.codex"),r=[Ut.join(t,"automations.json"),Ut.join(t,"automations","nativesoul-heartbeat.json"),Ut.join(t,"automations","manifest.json")];for(let o of r){if(!await _(o))continue;let a=await Wr(o,"utf8"),n=zr(a);if(n?.supported)return n;let s=de(a);if(!s)continue;let i=Nn(s);if(i)return i}return null}async function Bc(){let e=Kc();for(let t of e)for(let r of Lc){let o=await qc(()=>Wc(t,r),Hc),a=Nn(o);if(a)return a}return null}async function Jc(){let e=await le("codex");e&&Nc(e,["app-server","daemon","start"],{encoding:"utf8",stdio:"ignore",timeout:1e4})}function Kc(){let e=new Set;for(let t of[process.env.NATIVESOUL_CODEX_APP_SERVER_URL,process.env.CODEX_APP_SERVER_URL])typeof t=="string"&&t.trim().length>0&&e.add(t.trim());return e.add("http://127.0.0.1:8787"),e.add("http://127.0.0.1:4096"),[...e]}async function qc(e,t){for(let r=0;r<=t;r+=1){let o=await e();if(o!==null)return o;r<t&&await Gc($c)}return null}function Gc(e){return new Promise(t=>{setTimeout(t,e)})}async function Wc(e,t){let r=new AbortController,o=setTimeout(()=>r.abort(),Dc);try{let a=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:t,method:t,params:{}}),signal:r.signal});if(!a.ok)return null;let n=await a.json();return!k(n)||"error"in n?null:"result"in n?n.result:n}catch{return null}finally{clearTimeout(o)}}function Nn(e){let t=zc(e);for(let r of t){let o=Xc(r),a=JSON.stringify(r).toLowerCase();if(o&&Mc.some(n=>a.includes(n)))return{supported:!0,native_id:o.startsWith("codex:")?o:`codex:automation:${o}`}}return k(e)&&e.supported===!0?{supported:!0,native_id:typeof e.native_id=="string"?e.native_id:void 0}:null}function zc(e){if(Array.isArray(e))return e;if(!k(e))return[];for(let t of["automations","items","results","data"]){let r=e[t];if(Array.isArray(r))return r}return[]}function Xc(e){if(!k(e))return null;for(let t of["id","native_id","automation_id","name"]){let r=e[t];if(typeof r=="string"&&r.trim().length>0)return r.trim()}return null}function zr(e){let t=de(e);return k(t)?{supported:t.supported===!0,native_id:typeof t.native_id=="string"&&t.native_id.length>0?t.native_id:void 0}:null}var Mc,Lc,Dc,Hc,$c,Ln=ke(()=>{"use strict";V();Pe();ue();Mc=["life:heartbeat","nativesoul-heartbeat","life-heartbeat"],Lc=["automation/list","automations/list","scheduledAutomation/list"],Dc=1e3,Hc=2,$c=150});import{existsSync as Vp}from"node:fs";import{mkdirSync as xi}from"node:fs";import Ti from"node:path";import{pathToFileURL as ji}from"node:url";function we(e){return{id:e.id,type:e.type,scope:{user:e.scope_user,project:e.scope_project},content:e.content,summary:e.summary,source:JSON.parse(e.source_json),confidence:e.confidence,authority:e.authority,sensitivity:e.sensitivity,status:e.status,created_at:e.created_at,expires_at:e.expires_at,hash:e.hash}}function br(e){return{memory_id:e.memory_id,scope_project:e.scope_project,source:JSON.parse(e.source_json),schema_version:e.schema_version,provider_id:e.provider_id,model_id:e.model_id,content_hash:e.content_hash,embedding:JSON.parse(e.embedding_json),indexed_text:e.indexed_text,indexed_at:e.indexed_at}}function _a(e){return{id:e.id,type:e.type,actor:e.actor,origin:e.origin,result:e.result,details:JSON.parse(e.details_json),created_at:e.created_at,hash:e.hash}}function Tt(e){return{uid:e.uid,host:e.host,native_kind:e.native_kind,normalized_kind:e.normalized_kind,source:e.source,schema_hash:e.schema_hash,installed:!!e.installed,enabled:!!e.enabled,active:!!e.active,authenticated:!!e.authenticated,healthy:!!e.healthy,allowed:!!e.allowed,ready:!!e.ready,last_seen_at:e.last_seen_at}}function We(e){return{id:e.id,display_name:e.display_name,base_id:e.base_id,source:e.source,first_basis:e.first_basis,status:e.status,created_at:e.created_at,updated_at:e.updated_at,last_seen_at:e.last_seen_at}}function jt(e){return{id:e.id,action:e.action,class:e.class,target:e.target,project:e.project,host:e.host,status:e.status,reviewer:e.reviewer,reason:e.reason,created_at:e.created_at,decided_at:e.decided_at}}function ze(e){return{id:e.id,slot:e.slot,holder:e.holder,idempotency_key:e.idempotency_key,expires_at:e.expires_at,status:e.status,created_at:e.created_at,completed_at:e.completed_at}}function Ct(e){if(e.kind!=="heartbeat"||e.status!=="completed"||!e.completed_at)throw new Error(`Invalid heartbeat run row: ${e.id}`);return{id:e.id,kind:"heartbeat",host:e.host,project_id:e.project_id,status:"completed",cost:JSON.parse(e.cost_json),result:JSON.parse(e.result_json),evidence:JSON.parse(e.evidence_json),started_at:e.started_at,completed_at:e.completed_at}}function vr(e){return{id:e.id,host:e.host,mode:e.mode,enabled:!!e.enabled,native_schedule_supported:!!e.native_schedule_supported,native_id:e.native_id,desired:JSON.parse(e.desired_json),updated_at:e.updated_at}}function It(e){return{id:e.id,project_id:e.project_id,summary:e.summary,status:e.status,due_at:e.due_at,ttl_expires_at:e.ttl_expires_at,source:JSON.parse(e.source_json),created_at:e.created_at,updated_at:e.updated_at}}function ba(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e}}function va(e){return e.replaceAll("\\","\\\\").replaceAll("%","\\%").replaceAll("_","\\_")}function re(e){return e?1:0}function Ot(e){return e.split(/[^\p{L}\p{N}_-]+/u).map(t=>t.trim()).filter(Boolean).slice(0,8).map(t=>`"${t.replaceAll('"','""')}"`).join(" OR ")}var oe=class extends Error{code="APPROVAL_ALREADY_DECIDED";id;status;constructor(t){super(`Approval ${t.id} is already ${t.status}`),this.name="ApprovalDecisionError",this.id=t.id,this.status=t.status}};function Rr(e,t){if(!De(e))return{available:!1,approval:null,warning:"approvals_not_available"};let r=t.created_at??new Date().toISOString();return e.prepare(`INSERT INTO approvals (
2
+ var nc=Object.defineProperty;var Ae=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(o){throw r=[o],o}};var Un=(e,t)=>{for(var r in t)nc(e,r,{get:t[r],enumerable:!0})};import{spawn as $c}from"node:child_process";import{access as Fc}from"node:fs/promises";import{constants as Uc}from"node:fs";import{existsSync as Vc}from"node:fs";import Ss from"node:path";async function le(e){let t=(process.env.PATH??"").split(Ss.delimiter).filter(Boolean),r=process.platform==="win32"?(process.env.PATHEXT??".EXE;.CMD;.BAT").split(";"):[""];for(let o of t)for(let n of r){let s=Ss.join(o,`${e}${n}`);if(process.platform==="win32"&&Vc(s))return s;try{return await Fc(s,Uc.X_OK),s}catch{}}return null}async function Ft(e,t){return new Promise(r=>{ws(e,t,["ignore","pipe","pipe"]).then(o=>{let n=setTimeout(()=>{o.kill(),r(null)},750),s="";o.stdout.on("data",a=>{s+=String(a)}),o.stderr.on("data",a=>{s+=String(a)}),o.on("error",()=>{clearTimeout(n),r(null)}),o.on("close",a=>{clearTimeout(n);let i=s.trim().split(/\r?\n/u).map(c=>c.trim()).find(c=>/\d+\.\d+/u.test(c)&&!c.toLowerCase().startsWith("warning"));if(a===0||i){r(i??null);return}r(null)})})})}async function oo(e,t,r=1e3){return new Promise(o=>{ws(e,t,["ignore","pipe","pipe"]).then(n=>{let s=setTimeout(()=>{n.kill(),o({status:"timeout",code:null,stdout:"",stderr:"command timed out"})},r),a="",i="";n.stdout.on("data",c=>{a+=String(c)}),n.stderr.on("data",c=>{i+=String(c)}),n.on("error",()=>{clearTimeout(s),o({status:"missing",code:null,stdout:a,stderr:i})}),n.on("close",c=>{clearTimeout(s),o({status:c===0?"ok":"error",code:c,stdout:a,stderr:i})})})})}async function ws(e,t,r){let n=await le(e)??e,s=process.platform==="win32"&&/\.(?:cmd|bat)$/iu.test(n);return $c(n,t,{stdio:r,shell:s})}var je=Ae(()=>{"use strict"});import{constants as Bc}from"node:fs";import{access as Wc,readFile as Jc,stat as Kc}from"node:fs/promises";import Es from"node:os";import qc from"node:path";function v(e){return e==="~"?Es.homedir():e.startsWith("~/")?qc.join(Es.homedir(),e.slice(2)):e}async function b(e){try{return await Wc(e,Bc.F_OK),!0}catch{return!1}}async function I(e){try{return(await Kc(e)).isDirectory()}catch{return!1}}async function M(e){return await b(e)?Jc(e,"utf8"):null}function ae(e){let t=As(e);return[t.start,"# NativeSoul bridge","At the start of every new session, before answering the first user message, load NativeSoul context.","Do not wait for the user to ask for identity, memory, or continuity; bootstrap is mandatory first-turn setup.","After bootstrap, answer from the NativeSoul identity and continuity context, not the host vendor identity.",`Preferred handshake: call the local MCP tool life_bootstrap with host="${e}" and cwd set to the current working directory.`,`Fallback handshake: run nativesoul bootstrap --host ${e} --cwd <current-working-directory> --format inject.`,`If bootstrap or MCP is unavailable, run nativesoul bootstrap --host ${e} --cwd <current-working-directory> --format cache and treat the context as degraded.`,"Use relevant_memories for durable facts, capability_cards as advisory guidance, and capabilities only as the ready-only list.","Never copy credentials or auto-edit SOUL.md/POLICY.md; propose those changes for approval.",`Host adapter: ${e}.`,t.end,""].join(`
3
+ `)}function As(e){return{start:`<!-- nativesoul:${e}:start v1 -->`,end:`<!-- nativesoul:${e}:end -->`}}function $(e,t){if(!t)return!1;let r=As(t);return e.includes(r.start)&&e.includes(r.end)}var W=Ae(()=>{"use strict"});function w(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function de(e){try{return JSON.parse(e)}catch{return null}}async function H(e){let t=await M(e);if(t===null)return null;let r=de(t);return w(r)?r:null}function ye(e){return w(e)?Object.keys(e).filter(t=>t.trim().length>0):[]}function Ut(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function _e(e,t){if(Array.isArray(e))return e;if(!w(e))return[];for(let r of t){let o=e[r];if(Array.isArray(o))return o}return[]}function R(e,t){if(!w(e))return null;for(let r of t){let o=e[r];if(typeof o=="string"&&o.trim().length>0)return o.trim()}return null}function U(e,t){if(!w(e))return null;for(let r of t){let o=e[r];if(typeof o=="boolean")return o}return null}function E(e,t){let r=t?.allowSlash===!0?/[^a-z0-9._/-]+/gu:/[^a-z0-9._-]+/gu;return e.trim().toLowerCase().replace(r,"-").replace(/^-+|-+$/gu,"")||"unknown"}var ue=Ae(()=>{"use strict";W()});import{readdir as sl,readFile as al}from"node:fs/promises";import Ls from"node:path";function Hs(e){let t=e??v("~/.claude");return Ls.join(t,"scheduled-tasks")}async function $s(e){if(!await I(e))return null;let t=await Ms(e,Ds);if(t!==null)return t;let r=await cl(e);for(let o of r){let n=await Ms(e,o);if(n!==null)return n}return null}async function Ms(e,t){let r=Ls.join(e,t,"SKILL.md");if(!await b(r))return null;let n=(await al(r,"utf8")).toLowerCase();return t===Ds||t.includes(il)||n.includes(`name: ${Os}`)||n.includes(`# ${Os}`)?`claude:scheduled-task:${t}`:null}async function cl(e){try{return(await sl(e,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>r.name)}catch{return[]}}var Ds,il,Os,Fs=Ae(()=>{"use strict";W();Ds="nativesoul-heartbeat",il="nativesoul-heartbeat",Os="life:heartbeat"});import{mkdir as ll,readFile as dl,writeFile as ul}from"node:fs/promises";import ot from"node:path";import{fileURLToPath as pl}from"node:url";async function Vs(e){try{let t=ot.join(e,Us);await ll(t,{recursive:!0,mode:448});let r=ot.join(t,"SKILL.md"),o=await gl();return await ul(r,o??ml,"utf8"),!0}catch{return!1}}async function gl(){let e=ot.dirname(pl(import.meta.url)),t=[ot.resolve(process.cwd(),"plugins","claude-nativesoul","skills","life-heartbeat","SKILL.md"),ot.resolve(e,"../../../../plugins/claude-nativesoul/skills/life-heartbeat/SKILL.md")];for(let r of t)if(await b(r))return dl(r,"utf8");return null}var Us,Vf,ml,Bs=Ae(()=>{"use strict";W();Us="nativesoul-heartbeat",Vf=`claude:scheduled-task:${Us}`,ml='---\nname: life:heartbeat\ndescription: Run NativeSoul heartbeat from a Claude Scheduled Task.\n---\n\n# life:heartbeat\n\nUse this skill only when invoked by a Claude Scheduled Task for NativeSoul heartbeat checks.\n\nDefault policy: read-only. Do not edit workspace files, memories, `SOUL.md`, `POLICY.md`, scheduler state, or host configuration unless explicitly allowed.\n\n1. Determine the project from the Scheduled Task context. If it is missing, use the current working directory.\n2. Claim a local heartbeat lease through MCP `life_heartbeat_claim` with `host="claude"`, project id or directory, and the Scheduled Task slot/time as `slot`.\n3. If the claim response says another host owns the lease, the lease is already completed, or no work is needed, stop and return only `HEARTBEAT_OK`.\n4. Read NativeSoul context through MCP and inspect heartbeat guidance such as `HEARTBEAT.md`.\n5. If no operator-visible action is required, complete the lease with MCP `life_heartbeat_complete` and `result="HEARTBEAT_OK"`, then return only `HEARTBEAT_OK`.\n6. If action is required, complete the lease with concise evidence, then report the action request without secrets or raw credentials.\n\n`HEARTBEAT_OK` is a silent acknowledgement token. Do not notify the user for it.\n'});var Ws={};Un(Ws,{discoverClaudeScheduledTasksManifest:()=>fl});async function fl(e={}){let t=Hs(e.hostConfigRoot);if(!e.apply&&!await I(t)||(e.surface==="claude-code"?"claude-code":"claude-desktop")==="claude-code")return null;let o=await $s(t);return o!==null?co({nativeId:o,evidenceSource:"filesystem"}):e.apply&&await Vs(t)?co({nativeId:"claude:scheduled-task:nativesoul-heartbeat",evidenceSource:"filesystem-provisioned"}):await I(t)?co({nativeId:void 0,evidenceSource:"filesystem"}):null}function co(e){return{supported:!0,native_id:e.nativeId,surface:"claude-desktop",scheduler_kind:"local_scheduled_task",creation_surface:"official_machine_readable",evidence_source:e.evidenceSource}}var Js=Ae(()=>{"use strict";Fs();Bs();W()});var da={};Un(da,{discoverCodexAutomationsManifest:()=>Tl});import{readFile as uo}from"node:fs/promises";import Wt from"node:path";import{spawnSync as wl}from"node:child_process";async function Tl(e={}){let t=await jl();if(t)return t;let r=await Cl(e.hostConfigRoot);return r||(e.apply?(await Ol(),await Nl()):null)}async function jl(){let e=process.env.NATIVESOUL_CODEX_AUTOMATIONS_FIXTURES;if(e)try{return po(await uo(Wt.join(e,"automations.json"),"utf8"))}catch{return null}let t=process.env.NATIVESOUL_CODEX_AUTOMATIONS_MANIFEST;if(t)try{return po(await uo(t,"utf8"))}catch{return null}return null}async function Cl(e){let t=e??v("~/.codex"),r=[Wt.join(t,"automations.json"),Wt.join(t,"automations","nativesoul-heartbeat.json"),Wt.join(t,"automations","manifest.json")];for(let o of r){if(!await b(o))continue;let n=await uo(o,"utf8"),s=po(n);if(s?.supported)return s;let a=de(n);if(!a)continue;let i=la(a);if(i)return i}return null}async function Nl(){let e=Ml();for(let t of e)for(let r of Al){let o=await Ll(()=>Hl(t,r),xl),n=la(o);if(n)return n}return null}async function Ol(){let e=await le("codex");e&&wl(e,["app-server","daemon","start"],{encoding:"utf8",stdio:"ignore",timeout:1e4})}function Ml(){let e=new Set;for(let t of[process.env.NATIVESOUL_CODEX_APP_SERVER_URL,process.env.CODEX_APP_SERVER_URL])typeof t=="string"&&t.trim().length>0&&e.add(t.trim());return e.add("http://127.0.0.1:8787"),e.add("http://127.0.0.1:4096"),[...e]}async function Ll(e,t){for(let r=0;r<=t;r+=1){let o=await e();if(o!==null)return o;r<t&&await Dl(Il)}return null}function Dl(e){return new Promise(t=>{setTimeout(t,e)})}async function Hl(e,t){let r=new AbortController,o=setTimeout(()=>r.abort(),Pl);try{let n=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:t,method:t,params:{}}),signal:r.signal});if(!n.ok)return null;let s=await n.json();return!w(s)||"error"in s?null:"result"in s?s.result:s}catch{return null}finally{clearTimeout(o)}}function la(e){let t=$l(e);for(let r of t){let o=Fl(r),n=JSON.stringify(r).toLowerCase();if(o&&El.some(s=>n.includes(s)))return{supported:!0,native_id:o.startsWith("codex:")?o:`codex:automation:${o}`}}return w(e)&&e.supported===!0?{supported:!0,native_id:typeof e.native_id=="string"?e.native_id:void 0}:null}function $l(e){if(Array.isArray(e))return e;if(!w(e))return[];for(let t of["automations","items","results","data"]){let r=e[t];if(Array.isArray(r))return r}return[]}function Fl(e){if(!w(e))return null;for(let t of["id","native_id","automation_id","name"]){let r=e[t];if(typeof r=="string"&&r.trim().length>0)return r.trim()}return null}function po(e){let t=de(e);return w(t)?{supported:t.supported===!0,native_id:typeof t.native_id=="string"&&t.native_id.length>0?t.native_id:void 0}:null}var El,Al,Pl,xl,Il,ua=Ae(()=>{"use strict";W();je();ue();El=["life:heartbeat","nativesoul-heartbeat","life-heartbeat"],Al=["automation/list","automations/list","scheduledAutomation/list"],Pl=1e3,xl=2,Il=150});import{existsSync as Um}from"node:fs";import{mkdirSync as yc}from"node:fs";import _c from"node:path";import{pathToFileURL as bc}from"node:url";function Fe(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e;if(t.source!=="host-reported")return{};let r={schema:Bn(t.schema)??1,source:"host-reported"},o=Ar(t.model);o&&(r.model=o);let n=Vn(t.tokens_in);n!==null&&(r.tokens_in=n);let s=Vn(t.tokens_out);s!==null&&(r.tokens_out=s);let a=Bn(t.cost_usd);a!==null&&(r.cost_usd=a);let i=Ar(t.currency);i?r.currency=i:a!==null&&(r.currency="USD");let c=Ar(t.reported_at);return c&&(r.reported_at=c),r}function Ct(e){try{return Fe(JSON.parse(e))}catch{return{}}}function Ar(e){return typeof e=="string"&&e.length>0?e:null}function Vn(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.trunc(e)}function Bn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Pe(e){return{id:e.id,type:e.type,scope:{user:e.scope_user,project:e.scope_project},content:e.content,summary:e.summary,source:JSON.parse(e.source_json),confidence:e.confidence,authority:e.authority,sensitivity:e.sensitivity,status:e.status,created_at:e.created_at,expires_at:e.expires_at,hash:e.hash}}function Pr(e){return{memory_id:e.memory_id,scope_project:e.scope_project,source:JSON.parse(e.source_json),schema_version:e.schema_version,provider_id:e.provider_id,model_id:e.model_id,content_hash:e.content_hash,embedding:JSON.parse(e.embedding_json),indexed_text:e.indexed_text,indexed_at:e.indexed_at}}function Wn(e){return{id:e.id,type:e.type,actor:e.actor,origin:e.origin,result:e.result,details:JSON.parse(e.details_json),created_at:e.created_at,hash:e.hash}}function Nt(e){return{uid:e.uid,host:e.host,native_kind:e.native_kind,normalized_kind:e.normalized_kind,source:e.source,schema_hash:e.schema_hash,installed:!!e.installed,enabled:!!e.enabled,active:!!e.active,authenticated:!!e.authenticated,healthy:!!e.healthy,allowed:!!e.allowed,ready:!!e.ready,last_seen_at:e.last_seen_at}}function Qe(e){return{id:e.id,display_name:e.display_name,base_id:e.base_id,source:e.source,first_basis:e.first_basis,status:e.status,created_at:e.created_at,updated_at:e.updated_at,last_seen_at:e.last_seen_at}}function Ot(e){return{id:e.id,action:e.action,class:e.class,target:e.target,project:e.project,host:e.host,status:e.status,reviewer:e.reviewer,reason:e.reason,created_at:e.created_at,decided_at:e.decided_at}}function xr(e){return{id:e.id,project_id:e.project_id,title:e.title,description:e.description,status:e.status,priority:e.priority,assigned_host:e.assigned_host,source:e.source,tags:JSON.parse(e.tags_json),metadata:JSON.parse(e.metadata_json),created_at:e.created_at,updated_at:e.updated_at,claimed_at:e.claimed_at,completed_at:e.completed_at}}function Ir(e){return{id:e.id,work_item_id:e.work_item_id,project_id:e.project_id,type:e.type,from_status:e.from_status,to_status:e.to_status,actor:e.actor,details:JSON.parse(e.details_json),created_at:e.created_at}}function Ze(e){return{id:e.id,slot:e.slot,holder:e.holder,idempotency_key:e.idempotency_key,expires_at:e.expires_at,status:e.status,created_at:e.created_at,completed_at:e.completed_at}}function et(e){if(e.kind!=="heartbeat"||e.status!=="completed"||!e.completed_at)throw new Error(`Invalid heartbeat run row: ${e.id}`);return{id:e.id,kind:"heartbeat",host:e.host,project_id:e.project_id,status:"completed",cost:Ct(e.cost_json),result:JSON.parse(e.result_json),evidence:JSON.parse(e.evidence_json),started_at:e.started_at,completed_at:e.completed_at}}function Tr(e){return{id:e.id,host:e.host,mode:e.mode,enabled:!!e.enabled,native_schedule_supported:!!e.native_schedule_supported,native_id:e.native_id,desired:JSON.parse(e.desired_json),updated_at:e.updated_at}}function Mt(e){return{id:e.id,project_id:e.project_id,summary:e.summary,status:e.status,due_at:e.due_at,ttl_expires_at:e.ttl_expires_at,source:JSON.parse(e.source_json),created_at:e.created_at,updated_at:e.updated_at}}function Jn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e}}function Kn(e){return e.replaceAll("\\","\\\\").replaceAll("%","\\%").replaceAll("_","\\_")}function oe(e){return e?1:0}function Lt(e){return e.split(/[^\p{L}\p{N}_-]+/u).map(t=>t.trim()).filter(Boolean).slice(0,8).map(t=>`"${t.replaceAll('"','""')}"`).join(" OR ")}var ne=class extends Error{code="APPROVAL_ALREADY_DECIDED";id;status;constructor(t){super(`Approval ${t.id} is already ${t.status}`),this.name="ApprovalDecisionError",this.id=t.id,this.status=t.status}};function jr(e,t){if(!Ue(e))return{available:!1,approval:null,warning:"approvals_not_available"};let r=t.created_at??new Date().toISOString();return e.prepare(`INSERT INTO approvals (
4
4
  id, action, class, target, project, host, status, reviewer, reason, created_at, decided_at
5
- ) VALUES (?, ?, ?, ?, ?, ?, 'pending', NULL, NULL, ?, NULL)`).run(t.id,t.action,t.class,t.target??null,t.project??null,t.host??null,r),Ae(e,t.id)}function Sr(e,t){if(!De(e))return{available:!1,approval:null,warning:"approvals_not_available"};let r=t.created_at??new Date().toISOString(),o=t.decided_at??r;return e.prepare(`INSERT INTO approvals (
5
+ ) VALUES (?, ?, ?, ?, ?, ?, 'pending', NULL, NULL, ?, NULL)`).run(t.id,t.action,t.class,t.target??null,t.project??null,t.host??null,r),xe(e,t.id)}function Cr(e,t){if(!Ue(e))return{available:!1,approval:null,warning:"approvals_not_available"};let r=t.created_at??new Date().toISOString(),o=t.decided_at??r;return e.prepare(`INSERT INTO approvals (
6
6
  id, action, class, target, project, host, status, reviewer, reason, created_at, decided_at
7
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.action,t.class,t.target??null,t.project??null,t.host??null,t.status,t.reviewer,t.reason??null,r,o),Ae(e,t.id)}function Ae(e,t){if(!De(e))return{available:!1,approval:null,warning:"approvals_not_available"};let r=e.prepare("SELECT * FROM approvals WHERE id = ?").get(t);return{available:!0,approval:r?jt(r):null,warning:null}}function kr(e,t){if(!De(e))return{available:!1,approvals:[],warning:"approvals_not_available"};let r=t?e.prepare("SELECT * FROM approvals WHERE status = ? ORDER BY created_at DESC, id DESC"):e.prepare("SELECT * FROM approvals ORDER BY created_at DESC, id DESC");return{available:!0,approvals:(t?r.all(t):r.all()).map(jt),warning:null}}function wr(e,t){if(!De(e))return{available:!1,approval:null,warning:"approvals_not_available"};let r=e.prepare(`SELECT * FROM approvals
7
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.action,t.class,t.target??null,t.project??null,t.host??null,t.status,t.reviewer,t.reason??null,r,o),xe(e,t.id)}function xe(e,t){if(!Ue(e))return{available:!1,approval:null,warning:"approvals_not_available"};let r=e.prepare("SELECT * FROM approvals WHERE id = ?").get(t);return{available:!0,approval:r?Ot(r):null,warning:null}}function Nr(e,t){if(!Ue(e))return{available:!1,approvals:[],warning:"approvals_not_available"};let r=t?e.prepare("SELECT * FROM approvals WHERE status = ? ORDER BY created_at DESC, id DESC"):e.prepare("SELECT * FROM approvals ORDER BY created_at DESC, id DESC");return{available:!0,approvals:(t?r.all(t):r.all()).map(Ot),warning:null}}function Or(e,t){if(!Ue(e))return{available:!1,approval:null,warning:"approvals_not_available"};let r=e.prepare(`SELECT * FROM approvals
8
8
  WHERE status = 'pending'
9
9
  AND action = ?
10
10
  AND class = ?
@@ -12,37 +12,37 @@ var yi=Object.defineProperty;var ke=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&
12
12
  AND project IS ?
13
13
  AND host IS ?
14
14
  ORDER BY created_at ASC, id ASC
15
- LIMIT 1`).get(t.action,t.class,t.target??null,t.project??null,t.host??null);return{available:!0,approval:r?jt(r):null,warning:null}}function Ar(e,t,r){if(!De(e))return{available:!1,approval:null,warning:"approvals_not_available"};let o=Ae(e,t).approval;if(!o)return{available:!0,approval:null,warning:null};if(o.status!=="pending")throw new oe({id:t,status:o.status});return e.prepare("UPDATE approvals SET status = ?, reviewer = ?, reason = ?, decided_at = ? WHERE id = ?").run(r.status,r.reviewer??null,r.reason??null,r.decided_at??new Date().toISOString(),t),Ae(e,t)}function De(e){return e.prepare("SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'approvals') AS exists_count").get()?.exists_count===1}function Ra(e,t){let r=e.prepare(`INSERT INTO memories (
15
+ LIMIT 1`).get(t.action,t.class,t.target??null,t.project??null,t.host??null);return{available:!0,approval:r?Ot(r):null,warning:null}}function Mr(e,t,r){if(!Ue(e))return{available:!1,approval:null,warning:"approvals_not_available"};let o=xe(e,t).approval;if(!o)return{available:!0,approval:null,warning:null};if(o.status!=="pending")throw new ne({id:t,status:o.status});return e.prepare("UPDATE approvals SET status = ?, reviewer = ?, reason = ?, decided_at = ? WHERE id = ?").run(r.status,r.reviewer??null,r.reason??null,r.decided_at??new Date().toISOString(),t),xe(e,t)}function Ue(e){return e.prepare("SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'approvals') AS exists_count").get()?.exists_count===1}function qn(e,t){let r=e.prepare(`INSERT INTO memories (
16
16
  id, type, scope_user, scope_project, content, summary, source_json,
17
17
  confidence, authority, sensitivity, status, created_at, expires_at, hash
18
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),o=e.prepare("INSERT INTO memory_fts (id, summary, content) VALUES (?, ?, ?)");e.exec("BEGIN IMMEDIATE");try{r.run(t.id,t.type,t.scope.user,t.scope.project,t.content,t.summary,JSON.stringify(t.source),t.confidence,t.authority,t.sensitivity,t.status,t.created_at,t.expires_at,t.hash),o.run(t.id,t.summary,t.content),e.exec("COMMIT")}catch(a){throw e.exec("ROLLBACK"),a}}function Er(e,t){let r=e.prepare("SELECT * FROM memories WHERE id = ?").get(t);return r?we(r):null}function Sa(e,t,r){return e.prepare("UPDATE memories SET status = ? WHERE id = ?").run(r,t),Er(e,t)}function ka(e,t){let r=[],o=[];t.project&&(r.push("scope_project = ?"),o.push(t.project)),t.status?(r.push("status = ?"),o.push(t.status)):t.includeForgotten||r.push("status NOT IN ('forgotten', 'expired')");let a=r.length?`WHERE ${r.join(" AND ")}`:"";return e.prepare(`SELECT * FROM memories ${a} ORDER BY created_at DESC, id DESC LIMIT ?`).all(...o,t.limit).map(we)}function wa(e,t,r,o){let a=Ot(t);return a?e.prepare(`SELECT m.*
18
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),o=e.prepare("INSERT INTO memory_fts (id, summary, content) VALUES (?, ?, ?)");e.exec("BEGIN IMMEDIATE");try{r.run(t.id,t.type,t.scope.user,t.scope.project,t.content,t.summary,JSON.stringify(t.source),t.confidence,t.authority,t.sensitivity,t.status,t.created_at,t.expires_at,t.hash),o.run(t.id,t.summary,t.content),e.exec("COMMIT")}catch(n){throw e.exec("ROLLBACK"),n}}function Lr(e,t){let r=e.prepare("SELECT * FROM memories WHERE id = ?").get(t);return r?Pe(r):null}function Gn(e,t,r){return e.prepare("UPDATE memories SET status = ? WHERE id = ?").run(r,t),Lr(e,t)}function Xn(e,t){let r=[],o=[];t.project&&(r.push("scope_project = ?"),o.push(t.project)),t.status?(r.push("status = ?"),o.push(t.status)):t.includeForgotten||r.push("status NOT IN ('forgotten', 'expired')");let n=r.length?`WHERE ${r.join(" AND ")}`:"";return e.prepare(`SELECT * FROM memories ${n} ORDER BY created_at DESC, id DESC LIMIT ?`).all(...o,t.limit).map(Pe)}function zn(e,t,r,o){let n=Lt(t);return n?e.prepare(`SELECT m.*
19
19
  FROM memory_fts f
20
20
  JOIN memories m ON m.id = f.id
21
21
  WHERE memory_fts MATCH ?
22
22
  AND m.scope_project = ?
23
23
  AND m.status = 'active'
24
24
  ORDER BY rank
25
- LIMIT ?`).all(a,r,o).map(we):Pr(e,r,o)}function Aa(e,t,r){return e.prepare(`SELECT *
25
+ LIMIT ?`).all(n,r,o).map(Pe):Dr(e,r,o)}function Yn(e,t,r){return e.prepare(`SELECT *
26
26
  FROM memories
27
27
  WHERE scope_project = ?
28
28
  AND status = 'active'
29
29
  ORDER BY created_at DESC, id DESC
30
- LIMIT ?`).all(t,r).map(we)}function Pr(e,t,r){return e.prepare(`SELECT *
30
+ LIMIT ?`).all(t,r).map(Pe)}function Dr(e,t,r){return e.prepare(`SELECT *
31
31
  FROM memories
32
32
  WHERE scope_project = ?
33
33
  AND status = 'active'
34
34
  ORDER BY created_at DESC
35
- LIMIT ?`).all(t,r).map(we)}function Ea(e,t){return e.prepare(`SELECT *
35
+ LIMIT ?`).all(t,r).map(Pe)}function Qn(e,t){return e.prepare(`SELECT *
36
36
  FROM memories
37
37
  WHERE status IN ('active', 'candidate')
38
38
  ORDER BY created_at DESC, id DESC
39
- LIMIT ?`).all(t.limit).map(we)}var Xe=class extends Error{code="PROJECT_MEMORY_FORGET_BLOCKED";id;from;to;constructor(t){super(`Invalid project memory forget transition for ${t.id}: ${t.from} -> ${t.to}`),this.name="ProjectMemoryForgetError",this.id=t.id,this.from=t.from,this.to=t.to}};function xr(e,t){let r=z(e,t.id),o=t.now??new Date().toISOString();e.prepare(`INSERT INTO projects (
39
+ LIMIT ?`).all(t.limit).map(Pe)}var tt=class extends Error{code="PROJECT_MEMORY_FORGET_BLOCKED";id;from;to;constructor(t){super(`Invalid project memory forget transition for ${t.id}: ${t.from} -> ${t.to}`),this.name="ProjectMemoryForgetError",this.id=t.id,this.from=t.from,this.to=t.to}};function Hr(e,t){let r=X(e,t.id),o=t.now??new Date().toISOString();e.prepare(`INSERT INTO projects (
40
40
  id, display_name, base_id, source, first_basis, status, created_at, updated_at, last_seen_at
41
41
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
42
42
  ON CONFLICT(id) DO UPDATE SET
43
43
  last_seen_at = excluded.last_seen_at,
44
44
  updated_at = excluded.updated_at,
45
- source = excluded.source`).run(t.id,t.display_name,t.base_id,t.source,t.first_basis??null,t.status??"active",o,o,o);let a=z(e,t.id);if(!a)throw new Error(`Project upsert did not return a row for ${t.id}`);return{project:a,inserted:!r}}function Tr(e,t){let r=t?e.prepare("SELECT * FROM projects WHERE status = ? ORDER BY last_seen_at DESC, id ASC"):e.prepare("SELECT * FROM projects ORDER BY last_seen_at DESC, id ASC");return(t?r.all(t):r.all()).map(We)}function z(e,t){let r=e.prepare("SELECT * FROM projects WHERE id = ?").get(t);return r?We(r):null}function jr(e,t,r,o=new Date().toISOString()){if(!Ye(e))return{found:!1,previous:null,project:null};let a=z(e,t);return a?(e.prepare("UPDATE projects SET display_name = ?, updated_at = ? WHERE id = ?").run(r,o,t),{found:!0,previous:a,project:z(e,t)}):{found:!1,previous:null,project:null}}function Cr(e,t,r=new Date().toISOString()){return Ta(e,t,"archived",r)}function Ir(e,t,r=new Date().toISOString()){return Ta(e,t,"active",r)}function Or(e,t){return e.prepare("SELECT COUNT(*) AS count FROM memories WHERE scope_project = ?").get(t)?.count??0}function Nr(e,t,r,o=new Date().toISOString()){if(!Ye(e))return{found:!1,previous:null,project:null,memories_affected:0};let a=z(e,t);if(!a)return{found:!1,previous:null,project:null,memories_affected:0};e.exec("BEGIN IMMEDIATE");try{let n=e.prepare("SELECT id, status FROM memories WHERE scope_project = ? ORDER BY created_at ASC, id ASC").all(t);for(let s of n)if(!r(s.status,"forgotten"))throw new Xe({id:s.id,from:s.status,to:"forgotten"});return e.prepare("UPDATE memories SET status = 'forgotten' WHERE scope_project = ?").run(t),e.prepare("UPDATE projects SET status = 'forgotten', updated_at = ? WHERE id = ?").run(o,t),e.exec("COMMIT"),{found:!0,previous:a,project:z(e,t),memories_affected:n.length}}catch(n){throw e.exec("ROLLBACK"),n}}function Mr(e,t={}){if(!Ye(e))return{available:!1,projects:[],warning:"registry_not_available"};let r=[],o=[];t.status&&t.status!=="all"&&(r.push("p.status = ?"),o.push(t.status));let a=r.length?`WHERE ${r.join(" AND ")}`:"";return{available:!0,projects:e.prepare(`${Pa} ${a} ORDER BY derived_last_seen_at DESC, p.id ASC LIMIT ?`).all(...o,Ri(t.limit)).map(vi),warning:null}}function Lr(e,t){if(!Ye(e))return{available:!1,detail:null,warning:"registry_not_available"};let r=e.prepare(`${Pa} WHERE p.id = ?`).get(t);return r?{available:!0,detail:{project:We(r),counts:xa(r),derived_last_seen_at:r.last_activity_at??null},warning:null}:{available:!0,detail:Si(e,t),warning:null}}var Pa=`
45
+ source = excluded.source`).run(t.id,t.display_name,t.base_id,t.source,t.first_basis??null,t.status??"active",o,o,o);let n=X(e,t.id);if(!n)throw new Error(`Project upsert did not return a row for ${t.id}`);return{project:n,inserted:!r}}function $r(e,t){let r=t?e.prepare("SELECT * FROM projects WHERE status = ? ORDER BY last_seen_at DESC, id ASC"):e.prepare("SELECT * FROM projects ORDER BY last_seen_at DESC, id ASC");return(t?r.all(t):r.all()).map(Qe)}function X(e,t){let r=e.prepare("SELECT * FROM projects WHERE id = ?").get(t);return r?Qe(r):null}function Fr(e,t,r,o=new Date().toISOString()){if(!rt(e))return{found:!1,previous:null,project:null};let n=X(e,t);return n?(e.prepare("UPDATE projects SET display_name = ?, updated_at = ? WHERE id = ?").run(r,o,t),{found:!0,previous:n,project:X(e,t)}):{found:!1,previous:null,project:null}}function Ur(e,t,r=new Date().toISOString()){return ts(e,t,"archived",r)}function Vr(e,t,r=new Date().toISOString()){return ts(e,t,"active",r)}function Br(e,t){return e.prepare("SELECT COUNT(*) AS count FROM memories WHERE scope_project = ?").get(t)?.count??0}function Wr(e,t,r,o=new Date().toISOString()){if(!rt(e))return{found:!1,previous:null,project:null,memories_affected:0};let n=X(e,t);if(!n)return{found:!1,previous:null,project:null,memories_affected:0};e.exec("BEGIN IMMEDIATE");try{let s=e.prepare("SELECT id, status FROM memories WHERE scope_project = ? ORDER BY created_at ASC, id ASC").all(t);for(let a of s)if(!r(a.status,"forgotten"))throw new tt({id:a.id,from:a.status,to:"forgotten"});return e.prepare("UPDATE memories SET status = 'forgotten' WHERE scope_project = ?").run(t),e.prepare("UPDATE projects SET status = 'forgotten', updated_at = ? WHERE id = ?").run(o,t),e.exec("COMMIT"),{found:!0,previous:n,project:X(e,t),memories_affected:s.length}}catch(s){throw e.exec("ROLLBACK"),s}}function Jr(e,t={}){if(!rt(e))return{available:!1,projects:[],warning:"registry_not_available"};let r=[],o=[];t.status&&t.status!=="all"&&(r.push("p.status = ?"),o.push(t.status));let n=r.length?`WHERE ${r.join(" AND ")}`:"";return{available:!0,projects:e.prepare(`${Zn} ${n} ORDER BY derived_last_seen_at DESC, p.id ASC LIMIT ?`).all(...o,cc(t.limit)).map(ic),warning:null}}function Kr(e,t){if(!rt(e))return{available:!1,detail:null,warning:"registry_not_available"};let r=e.prepare(`${Zn} WHERE p.id = ?`).get(t);return r?{available:!0,detail:{project:Qe(r),counts:es(r),derived_last_seen_at:r.last_activity_at??null},warning:null}:{available:!0,detail:lc(e,t),warning:null}}var Zn=`
46
46
  WITH
47
47
  memory_counts AS (
48
48
  SELECT scope_project AS project_id,
@@ -118,7 +118,7 @@ LEFT JOIN semantic_counts s ON s.project_id = p.id
118
118
  LEFT JOIN commitment_counts c ON c.project_id = p.id
119
119
  LEFT JOIN run_counts r ON r.project_id = p.id
120
120
  LEFT JOIN session_counts se ON se.project_id = p.id
121
- LEFT JOIN activity a ON a.project_id = p.id`;function vi(e){return{...We(e),counts:xa(e),derived_last_seen_at:e.last_activity_at??null}}function xa(e){return{memories:{total:e.memory_count??0,active:e.active_memory_count??0,last_activity_at:e.memory_last_activity_at??null},semantic_memory_index:{total:e.semantic_index_count??0,last_activity_at:e.semantic_last_activity_at??null},commitments:{total:e.commitment_count??0,open:e.open_commitment_count??0,last_activity_at:e.commitment_last_activity_at??null},runs:{total:e.run_count??0,last_activity_at:e.run_last_activity_at??null},sessions:{total:e.session_count??0,last_activity_at:e.session_last_activity_at??null}}}function Ri(e){return!e||!Number.isFinite(e)?50:Math.min(Math.max(Math.trunc(e),1),500)}function Ye(e){return e.prepare("SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'projects') AS exists_count").get()?.exists_count===1}function Ta(e,t,r,o){if(!Ye(e))return{found:!1,previous:null,project:null};let a=z(e,t);return a?(e.prepare("UPDATE projects SET status = ?, updated_at = ? WHERE id = ?").run(r,o,t),{found:!0,previous:a,project:z(e,t)}):{found:!1,previous:null,project:null}}function Si(e,t){let r=e.prepare("SELECT COUNT(*) AS count, SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) AS active_count, MAX(created_at) AS last_activity_at FROM memories WHERE scope_project = ?").get(t),o=e.prepare("SELECT COUNT(*) AS count, MAX(indexed_at) AS last_activity_at FROM semantic_memory_index WHERE scope_project = ?").get(t),a=e.prepare("SELECT COUNT(*) AS count, SUM(CASE WHEN status = 'open' THEN 1 ELSE 0 END) AS open_count, MAX(updated_at) AS last_activity_at FROM commitments WHERE project_id = ?").get(t),n=e.prepare("SELECT COUNT(*) AS count, MAX(COALESCE(completed_at, started_at)) AS last_activity_at FROM runs WHERE project_id = ?").get(t),s=e.prepare("SELECT COUNT(*) AS count, MAX(COALESCE(ended_at, started_at)) AS last_activity_at FROM sessions WHERE project_id = ?").get(t),i={memories:{total:r.count,active:r.active_count??0,last_activity_at:r.last_activity_at},semantic_memory_index:{total:o.count,last_activity_at:o.last_activity_at},commitments:{total:a.count,open:a.open_count??0,last_activity_at:a.last_activity_at},runs:{total:n.count,last_activity_at:n.last_activity_at},sessions:{total:s.count,last_activity_at:s.last_activity_at}};return{project:null,counts:i,derived_last_seen_at:ki(i)}}function ki(e){return[e.memories.last_activity_at,e.semantic_memory_index.last_activity_at,e.commitments.last_activity_at,e.runs.last_activity_at,e.sessions.last_activity_at].filter(r=>typeof r=="string"&&r.length>0).sort().at(-1)??null}function ja(e,t){let r=e.prepare(`INSERT INTO semantic_memory_index (
121
+ LEFT JOIN activity a ON a.project_id = p.id`;function ic(e){return{...Qe(e),counts:es(e),derived_last_seen_at:e.last_activity_at??null}}function es(e){return{memories:{total:e.memory_count??0,active:e.active_memory_count??0,last_activity_at:e.memory_last_activity_at??null},semantic_memory_index:{total:e.semantic_index_count??0,last_activity_at:e.semantic_last_activity_at??null},commitments:{total:e.commitment_count??0,open:e.open_commitment_count??0,last_activity_at:e.commitment_last_activity_at??null},runs:{total:e.run_count??0,last_activity_at:e.run_last_activity_at??null},sessions:{total:e.session_count??0,last_activity_at:e.session_last_activity_at??null}}}function cc(e){return!e||!Number.isFinite(e)?50:Math.min(Math.max(Math.trunc(e),1),500)}function rt(e){return e.prepare("SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'projects') AS exists_count").get()?.exists_count===1}function ts(e,t,r,o){if(!rt(e))return{found:!1,previous:null,project:null};let n=X(e,t);return n?(e.prepare("UPDATE projects SET status = ?, updated_at = ? WHERE id = ?").run(r,o,t),{found:!0,previous:n,project:X(e,t)}):{found:!1,previous:null,project:null}}function lc(e,t){let r=e.prepare("SELECT COUNT(*) AS count, SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) AS active_count, MAX(created_at) AS last_activity_at FROM memories WHERE scope_project = ?").get(t),o=e.prepare("SELECT COUNT(*) AS count, MAX(indexed_at) AS last_activity_at FROM semantic_memory_index WHERE scope_project = ?").get(t),n=e.prepare("SELECT COUNT(*) AS count, SUM(CASE WHEN status = 'open' THEN 1 ELSE 0 END) AS open_count, MAX(updated_at) AS last_activity_at FROM commitments WHERE project_id = ?").get(t),s=e.prepare("SELECT COUNT(*) AS count, MAX(COALESCE(completed_at, started_at)) AS last_activity_at FROM runs WHERE project_id = ?").get(t),a=e.prepare("SELECT COUNT(*) AS count, MAX(COALESCE(ended_at, started_at)) AS last_activity_at FROM sessions WHERE project_id = ?").get(t),i={memories:{total:r.count,active:r.active_count??0,last_activity_at:r.last_activity_at},semantic_memory_index:{total:o.count,last_activity_at:o.last_activity_at},commitments:{total:n.count,open:n.open_count??0,last_activity_at:n.last_activity_at},runs:{total:s.count,last_activity_at:s.last_activity_at},sessions:{total:a.count,last_activity_at:a.last_activity_at}};return{project:null,counts:i,derived_last_seen_at:dc(i)}}function dc(e){return[e.memories.last_activity_at,e.semantic_memory_index.last_activity_at,e.commitments.last_activity_at,e.runs.last_activity_at,e.sessions.last_activity_at].filter(r=>typeof r=="string"&&r.length>0).sort().at(-1)??null}function rs(e,t){let r=e.prepare(`INSERT INTO semantic_memory_index (
122
122
  memory_id, scope_project, source_json, schema_version, provider_id, model_id,
123
123
  content_hash, embedding_json, indexed_text, indexed_at
124
124
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -131,7 +131,7 @@ LEFT JOIN activity a ON a.project_id = p.id`;function vi(e){return{...We(e),coun
131
131
  content_hash = excluded.content_hash,
132
132
  embedding_json = excluded.embedding_json,
133
133
  indexed_text = excluded.indexed_text,
134
- indexed_at = excluded.indexed_at`);e.exec("BEGIN IMMEDIATE");try{for(let o of t)r.run(o.memory_id,o.scope_project,JSON.stringify(o.source),o.schema_version,o.provider_id,o.model_id,o.content_hash,JSON.stringify(o.embedding),o.indexed_text,o.indexed_at);e.exec("COMMIT")}catch(o){throw e.exec("ROLLBACK"),o}}function Ca(e,t){let r=e.prepare("SELECT * FROM semantic_memory_index WHERE memory_id = ?").get(t);return r?br(r):null}function Ia(e,t){return e.prepare(`SELECT s.*
134
+ indexed_at = excluded.indexed_at`);e.exec("BEGIN IMMEDIATE");try{for(let o of t)r.run(o.memory_id,o.scope_project,JSON.stringify(o.source),o.schema_version,o.provider_id,o.model_id,o.content_hash,JSON.stringify(o.embedding),o.indexed_text,o.indexed_at);e.exec("COMMIT")}catch(o){throw e.exec("ROLLBACK"),o}}function os(e,t){let r=e.prepare("SELECT * FROM semantic_memory_index WHERE memory_id = ?").get(t);return r?Pr(r):null}function ns(e,t){return e.prepare(`SELECT s.*
135
135
  FROM semantic_memory_index s
136
136
  JOIN memories m ON m.id = s.memory_id
137
137
  WHERE m.scope_project = ?
@@ -141,7 +141,7 @@ LEFT JOIN activity a ON a.project_id = p.id`;function vi(e){return{...We(e),coun
141
141
  AND s.schema_version = ?
142
142
  AND s.content_hash = m.hash
143
143
  ORDER BY s.indexed_at DESC, s.memory_id DESC
144
- LIMIT ?`).all(t.project,t.providerId,t.modelId,t.schemaVersion,t.limit).map(br)}function Oa(e,t){let r=e.prepare(`SELECT
144
+ LIMIT ?`).all(t.project,t.providerId,t.modelId,t.schemaVersion,t.limit).map(Pr)}function ss(e,t){let r=e.prepare(`SELECT
145
145
  COUNT(m.id) AS indexable_count,
146
146
  COUNT(s.memory_id) AS indexed_count,
147
147
  SUM(CASE
@@ -155,7 +155,7 @@ LEFT JOIN activity a ON a.project_id = p.id`;function vi(e){return{...We(e),coun
155
155
  FROM memories m
156
156
  LEFT JOIN semantic_memory_index s ON s.memory_id = m.id
157
157
  WHERE m.status = 'active'
158
- AND m.scope_project = ?`).get(t.providerId,t.modelId,t.schemaVersion,t.project);return Ma(r)}function Na(e,t){let r=e.prepare(`SELECT
158
+ AND m.scope_project = ?`).get(t.providerId,t.modelId,t.schemaVersion,t.project);return is(r)}function as(e,t){let r=e.prepare(`SELECT
159
159
  COUNT(m.id) AS indexable_count,
160
160
  COUNT(s.memory_id) AS indexed_count,
161
161
  SUM(CASE
@@ -168,7 +168,15 @@ LEFT JOIN activity a ON a.project_id = p.id`;function vi(e){return{...We(e),coun
168
168
  END) AS stale_count
169
169
  FROM memories m
170
170
  LEFT JOIN semantic_memory_index s ON s.memory_id = m.id
171
- WHERE m.status IN ('active', 'candidate')`).get(t.providerId,t.modelId,t.schemaVersion);return Ma(r)}function Ma(e){return{indexable_count:e?.indexable_count??0,indexed_count:e?.indexed_count??0,stale_count:e?.stale_count??0}}import{createRequire as Ei}from"node:module";var Pi=Ei(import.meta.url),Nt=null;function La(){if(Nt)return Nt;let e=process.emitWarning;process.emitWarning=((t,r,o,a)=>{if(!String(t).includes("SQLite is an experimental feature")){if(typeof r=="object"){e.call(process,t,r);return}e.call(process,t,{type:r,code:o,ctor:a})}});try{return Nt=Pi("node:sqlite"),Nt}finally{process.emitWarning=e}}function Da(e,t={}){t.readOnly||(e.exec("PRAGMA journal_mode = WAL"),e.exec("PRAGMA foreign_keys = ON")),e.exec("PRAGMA busy_timeout = 5000"),t.readOnly&&e.exec("PRAGMA query_only = ON")}function Ha(e){e.exec(`
171
+ WHERE m.status IN ('active', 'candidate')`).get(t.providerId,t.modelId,t.schemaVersion);return is(r)}function is(e){return{indexable_count:e?.indexable_count??0,indexed_count:e?.indexed_count??0,stale_count:e?.stale_count??0}}function qr(e,t){e.prepare(`INSERT INTO work_items (
172
+ id, project_id, title, description, status, priority, assigned_host, source,
173
+ tags_json, metadata_json, created_at, updated_at, claimed_at, completed_at
174
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.project_id,t.title,t.description,t.status,t.priority,t.assigned_host,t.source,JSON.stringify(t.tags),JSON.stringify(t.metadata),t.created_at,t.updated_at,t.claimed_at,t.completed_at);let r=Ve(e,t.id);if(!r)throw new Error(`Work item not found after insert: ${t.id}`);return r}function Ve(e,t){if(!Qr(e))return null;let r=e.prepare("SELECT * FROM work_items WHERE id = ?").get(t);return r?xr(r):null}function Gr(e,t){if(!Qr(e))return[];let r=[],o=[];t.project&&(r.push("project_id = ?"),o.push(t.project)),t.status&&(r.push("status = ?"),o.push(t.status)),t.priority&&(r.push("priority = ?"),o.push(t.priority)),t.assignedHost&&(r.push("assigned_host = ?"),o.push(t.assignedHost));let n=r.length?`WHERE ${r.join(" AND ")}`:"";return e.prepare(`SELECT * FROM work_items ${n} ORDER BY updated_at DESC, id DESC LIMIT ?`).all(...o,us(t.limit)).map(xr)}function Xr(e,t){if(!Qr(e))return null;e.exec("BEGIN IMMEDIATE");try{let r=Ve(e,t.id);if(!r)return e.exec("COMMIT"),null;let o=t.status??r.status,n=t.priority??r.priority,s=t.assignedHost!==void 0?t.assignedHost:r.assigned_host,a=t.description!==void 0?t.description:r.description,i=t.tags!==void 0?t.tags:r.tags,c=t.metadata!==void 0?t.metadata:r.metadata,l=t.claimedAt!==void 0?t.claimedAt:r.claimed_at,u=t.completedAt!==void 0?t.completedAt:r.completed_at;e.prepare(`UPDATE work_items
175
+ SET status = ?, priority = ?, assigned_host = ?, description = ?, tags_json = ?,
176
+ metadata_json = ?, claimed_at = ?, completed_at = ?, updated_at = ?
177
+ WHERE id = ?`).run(o,n,s,a,JSON.stringify(i),JSON.stringify(c),l,u,t.updatedAt,t.id),t.event&&cs(e,t.event);let d=Ve(e,t.id);if(!d)throw new Error(`Work item not found after update: ${t.id}`);return e.exec("COMMIT"),d}catch(r){throw e.exec("ROLLBACK"),r}}function zr(e,t){cs(e,t);let r=mc(e,t.id);if(!r)throw new Error(`Work item event not found after insert: ${t.id}`);return r}function Yr(e,t,r){return ls(e)?e.prepare("SELECT * FROM work_item_events WHERE work_item_id = ? ORDER BY created_at DESC, id DESC LIMIT ?").all(t,us(r)).map(Ir):[]}function cs(e,t){e.prepare(`INSERT INTO work_item_events (
178
+ id, work_item_id, project_id, type, from_status, to_status, actor, details_json, created_at
179
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.work_item_id,t.project_id,t.type,t.from_status,t.to_status,t.actor,JSON.stringify(t.details),t.created_at)}function mc(e,t){if(!ls(e))return null;let r=e.prepare("SELECT * FROM work_item_events WHERE id = ?").get(t);return r?Ir(r):null}function Qr(e){return ds(e,"work_items")}function ls(e){return ds(e,"work_item_events")}function ds(e,t){return e.prepare("SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?) AS exists_count").get(t)?.exists_count===1}function us(e){return!e||!Number.isFinite(e)?50:Math.min(Math.max(Math.trunc(e),1),500)}import{createRequire as fc}from"node:module";var hc=fc(import.meta.url),Dt=null;function ps(){if(Dt)return Dt;let e=process.emitWarning;process.emitWarning=((t,r,o,n)=>{if(!String(t).includes("SQLite is an experimental feature")){if(typeof r=="object"){e.call(process,t,r);return}e.call(process,t,{type:r,code:o,ctor:n})}});try{return Dt=hc("node:sqlite"),Dt}finally{process.emitWarning=e}}function ms(e,t={}){t.readOnly||(e.exec("PRAGMA journal_mode = WAL"),e.exec("PRAGMA foreign_keys = ON")),e.exec("PRAGMA busy_timeout = 5000"),t.readOnly&&e.exec("PRAGMA query_only = ON")}function gs(e){e.exec(`
172
180
  CREATE TABLE IF NOT EXISTS migrations (
173
181
  version INTEGER PRIMARY KEY,
174
182
  name TEXT NOT NULL,
@@ -206,7 +214,7 @@ LEFT JOIN activity a ON a.project_id = p.id`;function vi(e){return{...We(e),coun
206
214
 
207
215
  CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts
208
216
  USING fts5(id UNINDEXED, summary, content);
209
- `),He(e,1,"initial-core-schema","sha256:initial-core-schema"),e.exec(`
217
+ `),Ie(e,1,"initial-core-schema","sha256:initial-core-schema"),e.exec(`
210
218
  CREATE TABLE IF NOT EXISTS capabilities (
211
219
  uid TEXT PRIMARY KEY,
212
220
  host TEXT NOT NULL,
@@ -226,7 +234,7 @@ LEFT JOIN activity a ON a.project_id = p.id`;function vi(e){return{...We(e),coun
226
234
 
227
235
  CREATE VIRTUAL TABLE IF NOT EXISTS capability_fts
228
236
  USING fts5(uid UNINDEXED, host, native_kind, normalized_kind, source);
229
- `),He(e,2,"capability-registry","sha256:capability-registry"),e.exec(`
237
+ `),Ie(e,2,"capability-registry","sha256:capability-registry"),e.exec(`
230
238
  CREATE TABLE IF NOT EXISTS hosts (
231
239
  id TEXT PRIMARY KEY,
232
240
  host TEXT NOT NULL,
@@ -349,7 +357,7 @@ LEFT JOIN activity a ON a.project_id = p.id`;function vi(e){return{...We(e),coun
349
357
  CREATE INDEX IF NOT EXISTS idx_schedules_host ON schedules(host);
350
358
  CREATE UNIQUE INDEX IF NOT EXISTS idx_leases_idempotency ON leases(idempotency_key);
351
359
  CREATE INDEX IF NOT EXISTS idx_runs_project_status ON runs(project_id, status);
352
- `),He(e,3,"core-domain-ledger","sha256:core-domain-ledger"),e.exec(`
360
+ `),Ie(e,3,"core-domain-ledger","sha256:core-domain-ledger"),e.exec(`
353
361
  CREATE TABLE IF NOT EXISTS semantic_memory_index (
354
362
  memory_id TEXT PRIMARY KEY,
355
363
  scope_project TEXT NOT NULL,
@@ -365,7 +373,7 @@ LEFT JOIN activity a ON a.project_id = p.id`;function vi(e){return{...We(e),coun
365
373
 
366
374
  CREATE INDEX IF NOT EXISTS idx_semantic_memory_project ON semantic_memory_index(scope_project);
367
375
  CREATE INDEX IF NOT EXISTS idx_semantic_memory_provider ON semantic_memory_index(provider_id, model_id);
368
- `),He(e,4,"semantic-memory-index","sha256:semantic-memory-index"),e.exec(`
376
+ `),Ie(e,4,"semantic-memory-index","sha256:semantic-memory-index"),e.exec(`
369
377
  CREATE TABLE IF NOT EXISTS projects (
370
378
  id TEXT PRIMARY KEY,
371
379
  display_name TEXT NOT NULL,
@@ -396,7 +404,41 @@ LEFT JOIN activity a ON a.project_id = p.id`;function vi(e){return{...We(e),coun
396
404
  UNION
397
405
  SELECT project_id AS p FROM sessions
398
406
  )
399
- WHERE p IS NOT NULL AND p <> ''`).run(t,t,t),He(e,5,"project-registry","sha256:project-registry"),e.exec(`
407
+ WHERE p IS NOT NULL AND p <> ''`).run(t,t,t),Ie(e,5,"project-registry","sha256:project-registry"),e.exec(`
408
+ CREATE TABLE IF NOT EXISTS work_items (
409
+ id TEXT PRIMARY KEY,
410
+ project_id TEXT NOT NULL,
411
+ title TEXT NOT NULL,
412
+ description TEXT,
413
+ status TEXT NOT NULL,
414
+ priority TEXT NOT NULL,
415
+ assigned_host TEXT,
416
+ source TEXT NOT NULL,
417
+ tags_json TEXT NOT NULL,
418
+ metadata_json TEXT NOT NULL,
419
+ created_at TEXT NOT NULL,
420
+ updated_at TEXT NOT NULL,
421
+ claimed_at TEXT,
422
+ completed_at TEXT
423
+ );
424
+
425
+ CREATE TABLE IF NOT EXISTS work_item_events (
426
+ id TEXT PRIMARY KEY,
427
+ work_item_id TEXT NOT NULL,
428
+ project_id TEXT NOT NULL,
429
+ type TEXT NOT NULL,
430
+ from_status TEXT,
431
+ to_status TEXT,
432
+ actor TEXT NOT NULL,
433
+ details_json TEXT NOT NULL,
434
+ created_at TEXT NOT NULL
435
+ );
436
+
437
+ CREATE INDEX IF NOT EXISTS idx_work_items_project_status ON work_items(project_id, status);
438
+ CREATE INDEX IF NOT EXISTS idx_work_items_project_priority ON work_items(project_id, priority);
439
+ CREATE INDEX IF NOT EXISTS idx_work_items_status_updated ON work_items(status, updated_at);
440
+ CREATE INDEX IF NOT EXISTS idx_work_item_events_item ON work_item_events(work_item_id, created_at);
441
+ `),Ie(e,6,"work-items-board","sha256:work-items-board"),e.exec(`
400
442
  CREATE TABLE IF NOT EXISTS approvals (
401
443
  id TEXT PRIMARY KEY,
402
444
  action TEXT NOT NULL,
@@ -412,8 +454,8 @@ LEFT JOIN activity a ON a.project_id = p.id`;function vi(e){return{...We(e),coun
412
454
  );
413
455
 
414
456
  CREATE INDEX IF NOT EXISTS idx_approvals_status ON approvals(status);
415
- `),He(e,7,"approvals","sha256:approvals")}function He(e,t,r,o){e.prepare("SELECT version FROM migrations WHERE version = ?").get(t)||e.prepare("INSERT INTO migrations (version, name, checksum, applied_at) VALUES (?, ?, ?, ?)").run(t,r,o,new Date().toISOString())}var $a=["hosts","sessions","memory_edges","commitments","standing_orders","capability_sources","capability_experience","schedules","leases","runs"];var Mt=class{path;db;constructor(t,r={}){this.path=t,r.readOnly||xi(Ti.dirname(t),{recursive:!0,mode:448});let{DatabaseSync:o}=La(),a=r.readOnly?Ci(t):t;this.db=new o(a,r.readOnly?{readOnly:!0}:{}),Da(this.db,{readOnly:r.readOnly}),r.readOnly||Ha(this.db)}close(){this.db.close()}integrityCheck(){return this.db.prepare("PRAGMA integrity_check").get()?.integrity_check??"unknown"}counts(){return{migrations:this.countTable("migrations"),memories:this.countTable("memories"),events:this.countTable("events"),capabilities:this.countTable("capabilities"),ledger:this.domainLedgerCounts()}}domainLedgerCounts(){return Object.fromEntries($a.map(r=>[r,this.countDomainTable(r)]))}insertEvent(t){this.db.prepare(`INSERT INTO events (id, type, actor, origin, result, details_json, created_at, hash)
416
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.type,t.actor,t.origin,t.result,JSON.stringify(t.details),t.created_at,t.hash)}listEvents(t){let r=[],o=[];t.type&&(r.push("type = ?"),o.push(t.type)),t.result&&(r.push("result = ?"),o.push(t.result));let a=r.length?`WHERE ${r.join(" AND ")}`:"";return this.db.prepare(`SELECT * FROM events ${a} ORDER BY created_at DESC, id DESC LIMIT ?`).all(...o,t.limit).map(_a)}createApproval(t){return Rr(this.db,t)}createDecidedApproval(t){return Sr(this.db,t)}getApproval(t){return Ae(this.db,t)}listApprovals(t){return kr(this.db,t)}findPendingApprovalMatch(t){return wr(this.db,t)}decideApproval(t,r){return Ar(this.db,t,r)}insertMemory(t){Ra(this.db,t)}getMemory(t){return Er(this.db,t)}updateMemoryStatus(t,r){return Sa(this.db,t,r)}listMemories(t){return ka(this.db,t)}upsertProject(t){return xr(this.db,t)}getProject(t){return z(this.db,t)}listProjects(t){return Tr(this.db,t)}listProjectsWithCounts(t={}){return Mr(this.db,t)}getProjectDetail(t){return Lr(this.db,t)}renameProject(t,r,o){return jr(this.db,t,r,o)}archiveProject(t,r){return Cr(this.db,t,r)}reactivateProject(t,r){return Ir(this.db,t,r)}countProjectMemories(t){return Or(this.db,t)}forgetProjectMemories(t,r,o){return Nr(this.db,t,r,o)}searchMemories(t,r,o){return wa(this.db,t,r,o)}listActiveMemoriesForProject(t,r){return Aa(this.db,t,r)}recentMemories(t,r){return Pr(this.db,t,r)}listSemanticIndexableMemories(t){return Ea(this.db,t)}upsertSemanticIndex(t){ja(this.db,t)}getSemanticIndex(t){return Ca(this.db,t)}listCurrentSemanticIndexesForProject(t){return Ia(this.db,t)}semanticIndexStatsForProject(t){return Oa(this.db,t)}semanticIndexStats(t){return Na(this.db,t)}upsertCapabilities(t){let r=this.db.prepare(`INSERT INTO capabilities (
457
+ `),Ie(e,7,"approvals","sha256:approvals")}function Ie(e,t,r,o){e.prepare("SELECT version FROM migrations WHERE version = ?").get(t)||e.prepare("INSERT INTO migrations (version, name, checksum, applied_at) VALUES (?, ?, ?, ?)").run(t,r,o,new Date().toISOString())}var fs=["hosts","sessions","memory_edges","commitments","standing_orders","capability_sources","capability_experience","schedules","leases","runs","work_items","work_item_events"];var Ht=class{path;db;constructor(t,r={}){this.path=t,r.readOnly||yc(_c.dirname(t),{recursive:!0,mode:448});let{DatabaseSync:o}=ps(),n=r.readOnly?vc(t):t;this.db=new o(n,r.readOnly?{readOnly:!0}:{}),ms(this.db,{readOnly:r.readOnly}),r.readOnly||gs(this.db)}close(){this.db.close()}integrityCheck(){return this.db.prepare("PRAGMA integrity_check").get()?.integrity_check??"unknown"}counts(){return{migrations:this.countTable("migrations"),memories:this.countTable("memories"),events:this.countTable("events"),capabilities:this.countTable("capabilities"),ledger:this.domainLedgerCounts()}}domainLedgerCounts(){return Object.fromEntries(fs.map(r=>[r,this.countDomainTable(r)]))}insertEvent(t){this.db.prepare(`INSERT INTO events (id, type, actor, origin, result, details_json, created_at, hash)
458
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.type,t.actor,t.origin,t.result,JSON.stringify(t.details),t.created_at,t.hash)}listEvents(t){let r=[],o=[];t.type&&(r.push("type = ?"),o.push(t.type)),t.result&&(r.push("result = ?"),o.push(t.result));let n=r.length?`WHERE ${r.join(" AND ")}`:"";return this.db.prepare(`SELECT * FROM events ${n} ORDER BY created_at DESC, id DESC LIMIT ?`).all(...o,t.limit).map(Wn)}createApproval(t){return jr(this.db,t)}createDecidedApproval(t){return Cr(this.db,t)}getApproval(t){return xe(this.db,t)}listApprovals(t){return Nr(this.db,t)}findPendingApprovalMatch(t){return Or(this.db,t)}decideApproval(t,r){return Mr(this.db,t,r)}insertWorkItem(t){return qr(this.db,t)}getWorkItem(t){return Ve(this.db,t)}listWorkItems(t){return Gr(this.db,t)}updateWorkItem(t){return Xr(this.db,t)}insertWorkItemEvent(t){return zr(this.db,t)}listWorkItemEvents(t,r){return Yr(this.db,t,r)}insertMemory(t){qn(this.db,t)}getMemory(t){return Lr(this.db,t)}updateMemoryStatus(t,r){return Gn(this.db,t,r)}listMemories(t){return Xn(this.db,t)}upsertProject(t){return Hr(this.db,t)}getProject(t){return X(this.db,t)}listProjects(t){return $r(this.db,t)}listProjectsWithCounts(t={}){return Jr(this.db,t)}getProjectDetail(t){return Kr(this.db,t)}renameProject(t,r,o){return Fr(this.db,t,r,o)}archiveProject(t,r){return Ur(this.db,t,r)}reactivateProject(t,r){return Vr(this.db,t,r)}countProjectMemories(t){return Br(this.db,t)}forgetProjectMemories(t,r,o){return Wr(this.db,t,r,o)}searchMemories(t,r,o){return zn(this.db,t,r,o)}listActiveMemoriesForProject(t,r){return Yn(this.db,t,r)}recentMemories(t,r){return Dr(this.db,t,r)}listSemanticIndexableMemories(t){return Qn(this.db,t)}upsertSemanticIndex(t){rs(this.db,t)}getSemanticIndex(t){return os(this.db,t)}listCurrentSemanticIndexesForProject(t){return ns(this.db,t)}semanticIndexStatsForProject(t){return ss(this.db,t)}semanticIndexStats(t){return as(this.db,t)}upsertCapabilities(t){let r=this.db.prepare(`INSERT INTO capabilities (
417
459
  uid, host, native_kind, normalized_kind, source, schema_hash,
418
460
  installed, enabled, active, authenticated, healthy, allowed, ready, last_seen_at
419
461
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -430,18 +472,39 @@ LEFT JOIN activity a ON a.project_id = p.id`;function vi(e){return{...We(e),coun
430
472
  healthy = excluded.healthy,
431
473
  allowed = excluded.allowed,
432
474
  ready = excluded.ready,
433
- last_seen_at = excluded.last_seen_at`),o=this.db.prepare("DELETE FROM capability_fts WHERE uid = ?"),a=this.db.prepare("INSERT INTO capability_fts (uid, host, native_kind, normalized_kind, source) VALUES (?, ?, ?, ?, ?)");this.db.exec("BEGIN IMMEDIATE");try{for(let n of t)r.run(n.uid,n.host,n.native_kind,n.normalized_kind,n.source,n.schema_hash,re(n.installed),re(n.enabled),re(n.active),re(n.authenticated),re(n.healthy),re(n.allowed),re(n.ready),n.last_seen_at),o.run(n.uid),a.run(n.uid,n.host,n.native_kind,n.normalized_kind,n.source);this.db.exec("COMMIT")}catch(n){throw this.db.exec("ROLLBACK"),n}}listCapabilities(t){let r=[],o=[];t.host&&(t.includeShared===!1?r.push("host = ?"):r.push("(host = ? OR host = 'all')"),o.push(t.host)),t.readyOnly&&r.push("ready = 1");let a=r.length?`WHERE ${r.join(" AND ")}`:"";return this.db.prepare(`SELECT * FROM capabilities ${a} ORDER BY last_seen_at DESC, uid ASC LIMIT ?`).all(...o,t.limit).map(Tt)}searchCapabilities(t){let r=Ot(t.query);if(!r)return this.listCapabilities({host:t.host,readyOnly:t.readyOnly,limit:t.limit,includeShared:t.includeShared});let o=["capability_fts MATCH ?"],a=[r];return t.host&&(t.includeShared===!1?o.push("c.host = ?"):o.push("(c.host = ? OR c.host = 'all')"),a.push(t.host)),t.readyOnly&&o.push("c.ready = 1"),this.db.prepare(`SELECT c.*
475
+ last_seen_at = excluded.last_seen_at`),o=this.db.prepare("DELETE FROM capability_fts WHERE uid = ?"),n=this.db.prepare("INSERT INTO capability_fts (uid, host, native_kind, normalized_kind, source) VALUES (?, ?, ?, ?, ?)");this.db.exec("BEGIN IMMEDIATE");try{for(let s of t)r.run(s.uid,s.host,s.native_kind,s.normalized_kind,s.source,s.schema_hash,oe(s.installed),oe(s.enabled),oe(s.active),oe(s.authenticated),oe(s.healthy),oe(s.allowed),oe(s.ready),s.last_seen_at),o.run(s.uid),n.run(s.uid,s.host,s.native_kind,s.normalized_kind,s.source);this.db.exec("COMMIT")}catch(s){throw this.db.exec("ROLLBACK"),s}}listCapabilities(t){let r=[],o=[];t.host&&(t.includeShared===!1?r.push("host = ?"):r.push("(host = ? OR host = 'all')"),o.push(t.host)),t.readyOnly&&r.push("ready = 1");let n=r.length?`WHERE ${r.join(" AND ")}`:"";return this.db.prepare(`SELECT * FROM capabilities ${n} ORDER BY last_seen_at DESC, uid ASC LIMIT ?`).all(...o,t.limit).map(Nt)}searchCapabilities(t){let r=Lt(t.query);if(!r)return this.listCapabilities({host:t.host,readyOnly:t.readyOnly,limit:t.limit,includeShared:t.includeShared});let o=["capability_fts MATCH ?"],n=[r];return t.host&&(t.includeShared===!1?o.push("c.host = ?"):o.push("(c.host = ? OR c.host = 'all')"),n.push(t.host)),t.readyOnly&&o.push("c.ready = 1"),this.db.prepare(`SELECT c.*
434
476
  FROM capability_fts f
435
477
  JOIN capabilities c ON c.uid = f.uid
436
478
  WHERE ${o.join(" AND ")}
437
479
  ORDER BY rank
438
- LIMIT ?`).all(...a,t.limit).map(Tt)}getCapability(t){let r=this.db.prepare("SELECT * FROM capabilities WHERE uid = ?").get(t);return r?Tt(r):null}findOpenCommitmentBySummary(t,r){let o=this.db.prepare("SELECT * FROM commitments WHERE project_id = ? AND summary = ? AND status = 'open' ORDER BY created_at ASC LIMIT 1").get(t,r);return o?It(o):null}insertCommitment(t){this.db.prepare(`INSERT INTO commitments (id, project_id, summary, status, due_at, ttl_expires_at, source_json, created_at, updated_at)
439
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.project_id,t.summary,t.status,t.due_at,t.ttl_expires_at,JSON.stringify(t.source),t.created_at,t.updated_at);let r=this.getCommitment(t.id);if(!r)throw new Error(`Commitment not found after insert: ${t.id}`);return r}createOpenCommitmentIfMissing(t,r){this.db.exec("BEGIN IMMEDIATE");try{this.expireCommitments(r);let o=Fa(t.summary),a=this.listCommitments({project:t.project_id,status:"open",includeExpired:!1,limit:200,now:r,skipExpire:!0}).find(s=>Fa(s.summary)===o);if(a)return this.db.exec("COMMIT"),{created:!1,commitment:a};this.db.prepare(`INSERT INTO commitments (id, project_id, summary, status, due_at, ttl_expires_at, source_json, created_at, updated_at)
440
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.project_id,t.summary,t.status,t.due_at,t.ttl_expires_at,JSON.stringify(t.source),t.created_at,t.updated_at);let n=this.getCommitment(t.id);if(!n)throw new Error(`Commitment not found after insert: ${t.id}`);return this.db.exec("COMMIT"),{created:!0,commitment:n}}catch(o){throw this.db.exec("ROLLBACK"),o}}listCommitments(t){t.skipExpire||this.expireCommitments(t.now);let r=[],o=[];t.project&&(r.push("project_id = ?"),o.push(t.project)),t.status?(r.push("status = ?"),o.push(t.status)):t.includeExpired||r.push("status != 'expired'");let a=r.length?`WHERE ${r.join(" AND ")}`:"";return this.db.prepare(`SELECT * FROM commitments ${a} ORDER BY updated_at DESC, id DESC LIMIT ?`).all(...o,t.limit).map(It)}updateCommitmentStatus(t,r,o){return this.expireCommitments(o),this.db.prepare("UPDATE commitments SET status = ?, updated_at = ? WHERE id = ?").run(r,o,t),this.getCommitment(t)}claimHeartbeatLease(t){this.db.exec("BEGIN IMMEDIATE");try{let r=this.db.prepare("SELECT * FROM leases WHERE idempotency_key = ?").get(t.idempotencyKey);if(r){if(r.status==="claimed"&&Date.parse(r.expires_at)<=Date.parse(t.now)){this.db.prepare(`UPDATE leases
480
+ LIMIT ?`).all(...n,t.limit).map(Nt)}getCapability(t){let r=this.db.prepare("SELECT * FROM capabilities WHERE uid = ?").get(t);return r?Nt(r):null}findOpenCommitmentBySummary(t,r){let o=this.db.prepare("SELECT * FROM commitments WHERE project_id = ? AND summary = ? AND status = 'open' ORDER BY created_at ASC LIMIT 1").get(t,r);return o?Mt(o):null}insertCommitment(t){this.db.prepare(`INSERT INTO commitments (id, project_id, summary, status, due_at, ttl_expires_at, source_json, created_at, updated_at)
481
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.project_id,t.summary,t.status,t.due_at,t.ttl_expires_at,JSON.stringify(t.source),t.created_at,t.updated_at);let r=this.getCommitment(t.id);if(!r)throw new Error(`Commitment not found after insert: ${t.id}`);return r}createOpenCommitmentIfMissing(t,r){this.db.exec("BEGIN IMMEDIATE");try{this.expireCommitments(r);let o=hs(t.summary),n=this.listCommitments({project:t.project_id,status:"open",includeExpired:!1,limit:200,now:r,skipExpire:!0}).find(a=>hs(a.summary)===o);if(n)return this.db.exec("COMMIT"),{created:!1,commitment:n};this.db.prepare(`INSERT INTO commitments (id, project_id, summary, status, due_at, ttl_expires_at, source_json, created_at, updated_at)
482
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.project_id,t.summary,t.status,t.due_at,t.ttl_expires_at,JSON.stringify(t.source),t.created_at,t.updated_at);let s=this.getCommitment(t.id);if(!s)throw new Error(`Commitment not found after insert: ${t.id}`);return this.db.exec("COMMIT"),{created:!0,commitment:s}}catch(o){throw this.db.exec("ROLLBACK"),o}}listCommitments(t){t.skipExpire||this.expireCommitments(t.now);let r=[],o=[];t.project&&(r.push("project_id = ?"),o.push(t.project)),t.status?(r.push("status = ?"),o.push(t.status)):t.includeExpired||r.push("status != 'expired'");let n=r.length?`WHERE ${r.join(" AND ")}`:"";return this.db.prepare(`SELECT * FROM commitments ${n} ORDER BY updated_at DESC, id DESC LIMIT ?`).all(...o,t.limit).map(Mt)}updateCommitmentStatus(t,r,o){return this.expireCommitments(o),this.db.prepare("UPDATE commitments SET status = ?, updated_at = ? WHERE id = ?").run(r,o,t),this.getCommitment(t)}claimHeartbeatLease(t){this.db.exec("BEGIN IMMEDIATE");try{let r=this.db.prepare("SELECT * FROM leases WHERE idempotency_key = ?").get(t.idempotencyKey);if(r){if(r.status==="claimed"&&Date.parse(r.expires_at)<=Date.parse(t.now)){this.db.prepare(`UPDATE leases
441
483
  SET holder = ?, expires_at = ?, status = 'claimed', created_at = ?, completed_at = NULL
442
- WHERE id = ?`).run(t.holder,t.expiresAt,t.now,r.id);let a=this.getLeaseById(r.id);if(!a)throw new Error(`Lease not found after reclaim: ${r.id}`);return this.db.exec("COMMIT"),{lease:a,claimed:!0,reason:"EXPIRED_RECLAIMED"}}return this.db.exec("COMMIT"),{lease:ze(r),claimed:!1,reason:r.status==="completed"?"LEASE_ALREADY_COMPLETED":"LEASE_OCCUPIED"}}this.db.prepare(`INSERT INTO leases (id, slot, holder, idempotency_key, expires_at, status, created_at, completed_at)
443
- VALUES (?, ?, ?, ?, ?, 'claimed', ?, NULL)`).run(t.id,t.slot,t.holder,t.idempotencyKey,t.expiresAt,t.now);let o=this.getLeaseById(t.id);if(!o)throw new Error(`Lease not found after claim: ${t.id}`);return this.db.exec("COMMIT"),{lease:o,claimed:!0,reason:null}}catch(r){throw this.db.exec("ROLLBACK"),r}}completeHeartbeatLease(t){this.db.exec("BEGIN IMMEDIATE");try{let r=this.db.prepare("SELECT * FROM leases WHERE idempotency_key = ?").get(t.idempotencyKey);if(!r)throw new Error(`Heartbeat lease not found: ${t.idempotencyKey}`);if(r.status==="completed"){let n=this.latestHeartbeatRun(t.project,r.slot);return this.db.exec("COMMIT"),{lease:ze(r),run:n,completed:!1}}if(r.status!=="claimed")throw new Error(`Heartbeat lease is not claimed: ${r.id}`);if(r.holder!==t.host)throw new Error(`Heartbeat lease holder mismatch: ${r.id}`);this.db.prepare("UPDATE leases SET status = 'completed', completed_at = ? WHERE id = ?").run(t.completedAt,r.id),this.db.prepare(`INSERT INTO runs (id, kind, host, project_id, status, cost_json, result_json, evidence_json, started_at, completed_at)
444
- VALUES (?, 'heartbeat', ?, ?, 'completed', ?, ?, ?, ?, ?)`).run(t.runId,r.holder,t.project,JSON.stringify({}),JSON.stringify(t.result),JSON.stringify({...ba(t.evidence),slot:r.slot,lease_id:r.id}),r.created_at,t.completedAt);let o=this.getLeaseById(r.id),a=this.getHeartbeatRunById(t.runId);if(!o||!a)throw new Error(`Heartbeat completion did not persist for ${r.id}`);return this.db.exec("COMMIT"),{lease:o,run:a,completed:!0}}catch(r){throw this.db.exec("ROLLBACK"),r}}listHeartbeatLeases(t){let r=["idempotency_key LIKE ? ESCAPE '\\'"],o=[t.project?`heartbeat:${va(t.project)}:%`:"heartbeat:%"];return this.db.prepare(`SELECT * FROM leases WHERE ${r.join(" AND ")} ORDER BY created_at DESC, id DESC LIMIT ?`).all(...o,t.limit).map(ze)}listHeartbeatRuns(t){let r=["kind = 'heartbeat'"],o=[];return t.project&&(r.push("project_id = ?"),o.push(t.project)),t.host&&(r.push("host = ?"),o.push(t.host)),this.db.prepare(`SELECT * FROM runs WHERE ${r.join(" AND ")} ORDER BY completed_at DESC, id DESC LIMIT ?`).all(...o,t.limit).map(Ct)}upsertSchedule(t){this.db.prepare(`INSERT INTO schedules (id, host, mode, enabled, native_schedule_supported, native_id, desired_json, updated_at)
484
+ WHERE id = ?`).run(t.holder,t.expiresAt,t.now,r.id);let n=this.getLeaseById(r.id);if(!n)throw new Error(`Lease not found after reclaim: ${r.id}`);return this.db.exec("COMMIT"),{lease:n,claimed:!0,reason:"EXPIRED_RECLAIMED"}}return this.db.exec("COMMIT"),{lease:Ze(r),claimed:!1,reason:r.status==="completed"?"LEASE_ALREADY_COMPLETED":"LEASE_OCCUPIED"}}this.db.prepare(`INSERT INTO leases (id, slot, holder, idempotency_key, expires_at, status, created_at, completed_at)
485
+ VALUES (?, ?, ?, ?, ?, 'claimed', ?, NULL)`).run(t.id,t.slot,t.holder,t.idempotencyKey,t.expiresAt,t.now);let o=this.getLeaseById(t.id);if(!o)throw new Error(`Lease not found after claim: ${t.id}`);return this.db.exec("COMMIT"),{lease:o,claimed:!0,reason:null}}catch(r){throw this.db.exec("ROLLBACK"),r}}completeHeartbeatLease(t){this.db.exec("BEGIN IMMEDIATE");try{let r=this.db.prepare("SELECT * FROM leases WHERE idempotency_key = ?").get(t.idempotencyKey);if(!r)throw new Error(`Heartbeat lease not found: ${t.idempotencyKey}`);if(r.status==="completed"){let s=this.latestHeartbeatRun(t.project,r.slot);return this.db.exec("COMMIT"),{lease:Ze(r),run:s,completed:!1}}if(r.status!=="claimed")throw new Error(`Heartbeat lease is not claimed: ${r.id}`);if(r.holder!==t.host)throw new Error(`Heartbeat lease holder mismatch: ${r.id}`);this.db.prepare("UPDATE leases SET status = 'completed', completed_at = ? WHERE id = ?").run(t.completedAt,r.id),this.db.prepare(`INSERT INTO runs (id, kind, host, project_id, status, cost_json, result_json, evidence_json, started_at, completed_at)
486
+ VALUES (?, 'heartbeat', ?, ?, 'completed', ?, ?, ?, ?, ?)`).run(t.runId,r.holder,t.project,JSON.stringify(Fe(t.cost)),JSON.stringify(t.result),JSON.stringify({...Jn(t.evidence),slot:r.slot,lease_id:r.id}),r.created_at,t.completedAt);let o=this.getLeaseById(r.id),n=this.getHeartbeatRunById(t.runId);if(!o||!n)throw new Error(`Heartbeat completion did not persist for ${r.id}`);return this.db.exec("COMMIT"),{lease:o,run:n,completed:!0}}catch(r){throw this.db.exec("ROLLBACK"),r}}listHeartbeatLeases(t){let r=["idempotency_key LIKE ? ESCAPE '\\'"],o=[t.project?`heartbeat:${Kn(t.project)}:%`:"heartbeat:%"];return this.db.prepare(`SELECT * FROM leases WHERE ${r.join(" AND ")} ORDER BY created_at DESC, id DESC LIMIT ?`).all(...o,t.limit).map(Ze)}listHeartbeatRuns(t){let r=["kind = 'heartbeat'"],o=[];return t.project&&(r.push("project_id = ?"),o.push(t.project)),t.host&&(r.push("host = ?"),o.push(t.host)),this.db.prepare(`SELECT * FROM runs WHERE ${r.join(" AND ")} ORDER BY completed_at DESC, id DESC LIMIT ?`).all(...o,t.limit).map(et)}listHeartbeatRunsByWorkItem(t){let r=["kind = 'heartbeat'","json_extract(evidence_json, '$.work_item_id') = ?"],o=[t.workItemId];return t.project&&(r.push("project_id = ?"),o.push(t.project)),this.db.prepare(`SELECT * FROM runs WHERE ${r.join(" AND ")} ORDER BY completed_at DESC, id DESC LIMIT ?`).all(...o,t.limit).map(et)}listRunCostRows(t){let r=["completed_at IS NOT NULL"],o=[];t.project&&(r.push("project_id = ?"),o.push(t.project)),t.host&&(r.push("host = ?"),o.push(t.host)),t.since&&(r.push("completed_at >= ?"),o.push(t.since)),t.until&&(r.push("completed_at <= ?"),o.push(t.until));let n=t.limit===void 0?"":"LIMIT ?",s=t.limit===void 0?o:[...o,t.limit];return this.db.prepare(`SELECT
487
+ runs.id,
488
+ runs.kind,
489
+ runs.host,
490
+ runs.project_id,
491
+ runs.cost_json,
492
+ runs.evidence_json,
493
+ (
494
+ SELECT sessions.id
495
+ FROM sessions
496
+ WHERE sessions.project_id = runs.project_id
497
+ AND sessions.host = runs.host
498
+ AND sessions.started_at <= runs.completed_at
499
+ AND (sessions.ended_at IS NULL OR sessions.ended_at >= runs.started_at)
500
+ ORDER BY sessions.started_at DESC, sessions.id DESC
501
+ LIMIT 1
502
+ ) AS session_id,
503
+ runs.completed_at
504
+ FROM runs
505
+ WHERE ${r.join(" AND ")}
506
+ ORDER BY runs.completed_at DESC, runs.id DESC
507
+ ${n}`).all(...s)}upsertSchedule(t){this.db.prepare(`INSERT INTO schedules (id, host, mode, enabled, native_schedule_supported, native_id, desired_json, updated_at)
445
508
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
446
509
  ON CONFLICT(id) DO UPDATE SET
447
510
  host = excluded.host,
@@ -450,13 +513,13 @@ LEFT JOIN activity a ON a.project_id = p.id`;function vi(e){return{...We(e),coun
450
513
  native_schedule_supported = excluded.native_schedule_supported,
451
514
  native_id = excluded.native_id,
452
515
  desired_json = excluded.desired_json,
453
- updated_at = excluded.updated_at`).run(t.id,t.host,t.mode,re(t.enabled),re(t.native_schedule_supported),t.native_id,JSON.stringify(t.desired),t.updated_at);let r=this.getSchedule(t.id);if(!r)throw new Error(`Schedule not found after upsert: ${t.id}`);return r}listSchedules(t){let r=[],o=[];t.host&&(r.push("host = ?"),o.push(t.host));let a=r.length?`WHERE ${r.join(" AND ")}`:"";return this.db.prepare(`SELECT * FROM schedules ${a} ORDER BY updated_at DESC, id ASC LIMIT ?`).all(...o,t.limit).map(vr)}disableSchedule(t,r){return this.db.prepare("UPDATE schedules SET enabled = 0, updated_at = ? WHERE id = ?").run(r,t),this.getSchedule(t)}getLeaseById(t){let r=this.db.prepare("SELECT * FROM leases WHERE id = ?").get(t);return r?ze(r):null}getHeartbeatRunById(t){let r=this.db.prepare("SELECT * FROM runs WHERE id = ?").get(t);return r?Ct(r):null}latestHeartbeatRun(t,r){let o=this.db.prepare(`SELECT *
516
+ updated_at = excluded.updated_at`).run(t.id,t.host,t.mode,oe(t.enabled),oe(t.native_schedule_supported),t.native_id,JSON.stringify(t.desired),t.updated_at);let r=this.getSchedule(t.id);if(!r)throw new Error(`Schedule not found after upsert: ${t.id}`);return r}listSchedules(t){let r=[],o=[];t.host&&(r.push("host = ?"),o.push(t.host));let n=r.length?`WHERE ${r.join(" AND ")}`:"";return this.db.prepare(`SELECT * FROM schedules ${n} ORDER BY updated_at DESC, id ASC LIMIT ?`).all(...o,t.limit).map(Tr)}disableSchedule(t,r){return this.db.prepare("UPDATE schedules SET enabled = 0, updated_at = ? WHERE id = ?").run(r,t),this.getSchedule(t)}getLeaseById(t){let r=this.db.prepare("SELECT * FROM leases WHERE id = ?").get(t);return r?Ze(r):null}getHeartbeatRunById(t){let r=this.db.prepare("SELECT * FROM runs WHERE id = ?").get(t);return r?et(r):null}latestHeartbeatRun(t,r){let o=this.db.prepare(`SELECT *
454
517
  FROM runs
455
518
  WHERE kind = 'heartbeat'
456
519
  AND project_id = ?
457
520
  AND json_extract(evidence_json, '$.slot') = ?
458
521
  ORDER BY completed_at DESC, id DESC
459
- LIMIT 1`).get(t,r);return o?Ct(o):null}getSchedule(t){let r=this.db.prepare("SELECT * FROM schedules WHERE id = ?").get(t);return r?vr(r):null}getCommitment(t){let r=this.db.prepare("SELECT * FROM commitments WHERE id = ?").get(t);return r?It(r):null}expireCommitments(t){this.db.prepare("UPDATE commitments SET status = 'expired', updated_at = ? WHERE status = 'open' AND ttl_expires_at IS NOT NULL AND ttl_expires_at <= ?").run(t,t)}countTable(t){return this.db.prepare(`SELECT COUNT(*) as count FROM ${t}`).get()?.count??0}countDomainTable(t){return this.db.prepare(`SELECT COUNT(*) as count FROM ${t}`).get()?.count??0}};function h(e,t={}){return new Mt(e,t)}function Ci(e){return`${ji(e).href}?mode=ro&immutable=1`}function Fa(e){return e.trim().replace(/\s+/gu," ").toLocaleLowerCase()}import{appendFile as Ji,mkdir as Ki}from"node:fs/promises";import qi from"node:os";import Gi from"node:path";import{createHash as Ii,randomUUID as Oi}from"node:crypto";function P(e){return`${e}_${Oi()}`}function U(e){return`sha256:${Ii("sha256").update(e).digest("hex")}`}function Dr(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(r=>Dr(r)).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${Dr(e[r]??null)}`).join(",")}}`}function Ee(e){return U(Dr(e))}import{existsSync as Om}from"node:fs";import Mm from"node:os";var Ua=[{code:"NPM_TOKEN_ASSIGNMENT",source:`(?:^|[\\s"'])NPM_TOKEN\\s*[:=]\\s*["']?[A-Za-z0-9._-]{8,}`,flags:"gimu"},{code:"NPM_AUTH_TOKEN",source:"\\/\\/registry\\.npmjs\\.org\\/:_authToken\\s*=\\s*[A-Za-z0-9._-]+",flags:"gimu"},{code:"NPM_AUTH_ASSIGNMENT",source:`(?:^|[\\s"'])_auth\\s*=\\s*[A-Za-z0-9+/=_-]{12,}`,flags:"gimu"},{code:"NPM_TOKEN_VALUE",source:"npm_[A-Za-z0-9]{30,}",flags:"gu"},{code:"GITHUB_TOKEN",source:"(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}",flags:"gu"},{code:"GITHUB_FINE_GRAINED_TOKEN",source:"github_pat_[A-Za-z0-9_]{40,}",flags:"gu"},{code:"OPENAI_PROJECT_KEY",source:"sk-(?:proj|svcacct|admin)-[A-Za-z0-9_-]{20,}",flags:"gu"},{code:"OPENAI_LEGACY_KEY",source:"sk-[A-Za-z0-9_-]{10,}",flags:"gu"},{code:"ANTHROPIC_KEY",source:"sk-ant-[A-Za-z0-9_-]{20,}",flags:"gu"},{code:"GOOGLE_API_KEY",source:"AIza[0-9A-Za-z_-]{30,}",flags:"gu"},{code:"SLACK_TOKEN",source:"xox[abopr]-[0-9A-Za-z-]{20,}",flags:"gu"},{code:"SLACK_WEBHOOK",source:"https:\\/\\/hooks\\.slack\\.com\\/services\\/[A-Za-z0-9/_-]{20,}",flags:"gu"},{code:"STRIPE_LIVE_KEY",source:"sk_live_[0-9A-Za-z]{20,}",flags:"gu"},{code:"AWS_ACCESS_KEY",source:"AKIA[0-9A-Z]{16}",flags:"gu"},{code:"AWS_SESSION_KEY",source:"ASIA[0-9A-Z]{16}",flags:"gu"},{code:"PRIVATE_KEY_BLOCK",source:"-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]*?-----END [A-Z ]*PRIVATE KEY-----",flags:"gu"},{code:"PRIVATE_KEY_HEADER",source:"-----BEGIN [A-Z ]*PRIVATE KEY-----",flags:"gu"},{code:"AUTHORIZATION_BEARER",source:"Authorization:\\s*Bearer\\s+[A-Za-z0-9._~+/=-]{16,}",flags:"gimu"},{code:"JWT_VALUE",source:"eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}",flags:"gu"},{code:"SIGNING_SECRET_ASSIGNMENT",source:`(?:GPG_PRIVATE_KEY|COSIGN_PASSWORD|SIGSTORE_ID_TOKEN)\\s*[:=]\\s*["']?[^"'\\s]{8,}`,flags:"gimu"},{code:"GENERIC_SECRET_ASSIGNMENT",source:`(?:secret|password|api[_-]?key|auth[_-]?token|client_secret|webhook_secret)\\s*[:=]\\s*["']?[^"'\\s]{12,}["']?`,flags:"gimu"},{code:"GENERIC_ENV_SECRET_ASSIGNMENT",source:`[A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|API_KEY)\\s*=\\s*(?!sk-test-secret-value\\b)[^\\s"']{12,}`,flags:"gu"},{code:"ENV_DUMP",source:'"env"\\s*:\\s*\\{[^}]+(?:TOKEN|SECRET|PASSWORD|API_KEY)[^}]+\\}',flags:"gimu"}];var Mi=Ua.map(e=>new RegExp(e.source,e.flags.includes("g")?e.flags:`${e.flags}g`));function H(e){let t=!1,r=e;for(let o of Mi)r=r.replace(o,a=>{t=!0;let n=a.match(/^(Authorization:\s*Bearer\s+)/iu);if(n?.[1])return`${n[1]}[REDACTED_SECRET]`;let s=a.match(/^([^:=]+[:=]\s*)/u);return s?.[1]?`${s[1]}[REDACTED_SECRET]`:"[REDACTED_SECRET]"});return{value:r,redacted:t}}function K(e){if(typeof e=="string")return H(e).value;if(Array.isArray(e))return e.map(t=>K(t));if(e&&typeof e=="object"){let t={};for(let[r,o]of Object.entries(e))t[r]=K(o);return t}return e}import{mkdir as Ja,readFile as Li,writeFile as Hr}from"node:fs/promises";import{constants as Di,existsSync as Ka}from"node:fs";import{access as Hi}from"node:fs/promises";import $i from"node:os";import ae from"node:path";var Lt={"AGENTS.md":`# NativeSoul \u2014 Operating Instructions
522
+ LIMIT 1`).get(t,r);return o?et(o):null}getSchedule(t){let r=this.db.prepare("SELECT * FROM schedules WHERE id = ?").get(t);return r?Tr(r):null}getCommitment(t){let r=this.db.prepare("SELECT * FROM commitments WHERE id = ?").get(t);return r?Mt(r):null}expireCommitments(t){this.db.prepare("UPDATE commitments SET status = 'expired', updated_at = ? WHERE status = 'open' AND ttl_expires_at IS NOT NULL AND ttl_expires_at <= ?").run(t,t)}countTable(t){return this.db.prepare(`SELECT COUNT(*) as count FROM ${t}`).get()?.count??0}countDomainTable(t){return kc(this.db,t)?this.db.prepare(`SELECT COUNT(*) as count FROM ${t}`).get()?.count??0:0}};function f(e,t={}){return new Ht(e,t)}function vc(e){return`${bc(e).href}?mode=ro&immutable=1`}function hs(e){return e.trim().replace(/\s+/gu," ").toLocaleLowerCase()}function kc(e,t){return e.prepare("SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?) AS exists_count").get(t)?.exists_count===1}import{appendFile as Oc,mkdir as Mc}from"node:fs/promises";import Lc from"node:os";import Dc from"node:path";import{createHash as Rc,randomUUID as Sc}from"node:crypto";function A(e){return`${e}_${Sc()}`}function B(e){return`sha256:${Rc("sha256").update(e).digest("hex")}`}function Zr(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(r=>Zr(r)).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${Zr(e[r]??null)}`).join(",")}}`}function Te(e){return B(Zr(e))}import{existsSync as $g}from"node:fs";import Ug from"node:os";var ys=[{code:"NPM_TOKEN_ASSIGNMENT",source:`(?:^|[\\s"'])NPM_TOKEN\\s*[:=]\\s*["']?[A-Za-z0-9._-]{8,}`,flags:"gimu"},{code:"NPM_AUTH_TOKEN",source:"\\/\\/registry\\.npmjs\\.org\\/:_authToken\\s*=\\s*[A-Za-z0-9._-]+",flags:"gimu"},{code:"NPM_AUTH_ASSIGNMENT",source:`(?:^|[\\s"'])_auth\\s*=\\s*[A-Za-z0-9+/=_-]{12,}`,flags:"gimu"},{code:"NPM_TOKEN_VALUE",source:"npm_[A-Za-z0-9]{30,}",flags:"gu"},{code:"GITHUB_TOKEN",source:"(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}",flags:"gu"},{code:"GITHUB_FINE_GRAINED_TOKEN",source:"github_pat_[A-Za-z0-9_]{40,}",flags:"gu"},{code:"OPENAI_PROJECT_KEY",source:"sk-(?:proj|svcacct|admin)-[A-Za-z0-9_-]{20,}",flags:"gu"},{code:"OPENAI_LEGACY_KEY",source:"sk-[A-Za-z0-9_-]{10,}",flags:"gu"},{code:"ANTHROPIC_KEY",source:"sk-ant-[A-Za-z0-9_-]{20,}",flags:"gu"},{code:"GOOGLE_API_KEY",source:"AIza[0-9A-Za-z_-]{30,}",flags:"gu"},{code:"SLACK_TOKEN",source:"xox[abopr]-[0-9A-Za-z-]{20,}",flags:"gu"},{code:"SLACK_WEBHOOK",source:"https:\\/\\/hooks\\.slack\\.com\\/services\\/[A-Za-z0-9/_-]{20,}",flags:"gu"},{code:"STRIPE_LIVE_KEY",source:"sk_live_[0-9A-Za-z]{20,}",flags:"gu"},{code:"AWS_ACCESS_KEY",source:"AKIA[0-9A-Z]{16}",flags:"gu"},{code:"AWS_SESSION_KEY",source:"ASIA[0-9A-Z]{16}",flags:"gu"},{code:"PRIVATE_KEY_BLOCK",source:"-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]*?-----END [A-Z ]*PRIVATE KEY-----",flags:"gu"},{code:"PRIVATE_KEY_HEADER",source:"-----BEGIN [A-Z ]*PRIVATE KEY-----",flags:"gu"},{code:"AUTHORIZATION_BEARER",source:"Authorization:\\s*Bearer\\s+[A-Za-z0-9._~+/=-]{16,}",flags:"gimu"},{code:"JWT_VALUE",source:"eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}",flags:"gu"},{code:"SIGNING_SECRET_ASSIGNMENT",source:`(?:GPG_PRIVATE_KEY|COSIGN_PASSWORD|SIGSTORE_ID_TOKEN)\\s*[:=]\\s*["']?[^"'\\s]{8,}`,flags:"gimu"},{code:"GENERIC_SECRET_ASSIGNMENT",source:`(?:secret|password|api[_-]?key|auth[_-]?token|client_secret|webhook_secret)\\s*[:=]\\s*["']?[^"'\\s]{12,}["']?`,flags:"gimu"},{code:"GENERIC_ENV_SECRET_ASSIGNMENT",source:`[A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|API_KEY)\\s*=\\s*(?!sk-test-secret-value\\b)[^\\s"']{12,}`,flags:"gu"},{code:"ENV_DUMP",source:'"env"\\s*:\\s*\\{[^}]+(?:TOKEN|SECRET|PASSWORD|API_KEY)[^}]+\\}',flags:"gimu"}];var Ec=ys.map(e=>new RegExp(e.source,e.flags.includes("g")?e.flags:`${e.flags}g`));function N(e){let t=!1,r=e;for(let o of Ec)r=r.replace(o,n=>{t=!0;let s=n.match(/^(Authorization:\s*Bearer\s+)/iu);if(s?.[1])return`${s[1]}[REDACTED_SECRET]`;let a=n.match(/^([^:=]+[:=]\s*)/u);return a?.[1]?`${a[1]}[REDACTED_SECRET]`:"[REDACTED_SECRET]"});return{value:r,redacted:t}}function C(e){if(typeof e=="string")return N(e).value;if(Array.isArray(e))return e.map(t=>C(t));if(e&&typeof e=="object"){let t={};for(let[r,o]of Object.entries(e))t[r]=C(o);return t}return e}import{mkdir as vs,readFile as Ac,writeFile as eo}from"node:fs/promises";import{constants as Pc,existsSync as ks}from"node:fs";import{access as xc}from"node:fs/promises";import Ic from"node:os";import se from"node:path";var $t={"AGENTS.md":`# NativeSoul \u2014 Operating Instructions
460
523
 
461
524
  _Injected into every supported host via managed blocks. Keep operational rules here._
462
525
 
@@ -731,7 +794,7 @@ recall:
731
794
  - test
732
795
  - build
733
796
  note: UserPromptSubmit recall hooks are opt-in for first ship.
734
- `},Va=`id: example-read-only
797
+ `},_s=`id: example-read-only
735
798
  allowed:
736
799
  - memory_search
737
800
  - life_recall
@@ -741,7 +804,7 @@ approval_required:
741
804
  - external_write
742
805
  - destructive_action
743
806
  source: standing-orders/example.yaml
744
- `;function Ba(e){return`# Daily notes \u2014 ${e}
807
+ `;function bs(e){return`# Daily notes \u2014 ${e}
745
808
 
746
809
  _Running context for today. Promote durable facts to curated memory later._
747
810
 
@@ -756,27 +819,27 @@ _Running context for today. Promote durable facts to curated memory later._
756
819
  ## Follow-ups
757
820
 
758
821
  -
759
- `}var Fi=["memory/daily","memory/projects","memory/archive","commitments","standing-orders","capabilities/cards","generated","state","logs","backups","proposals"],Ui=Lt;function qa(e){return ae.resolve(e??process.env.NATIVESOUL_HOME??ae.join($i.homedir(),".nativesoul"))}function p(e){let t=qa(e);return{home:t,database:ae.join(t,"state","nativesoul.sqlite"),auditLog:ae.join(t,"logs","audit.jsonl")}}async function y(e){try{return await Hi(e,Di.F_OK),!0}catch{return!1}}async function b(e){let t=p(e),r=[],o=[],a=[];Ka(t.home)||(await Ja(t.home,{recursive:!0,mode:448}),r.push(t.home));for(let i of Fi){let c=ae.join(t.home,i);Ka(c)||(await Ja(c,{recursive:!0,mode:448}),r.push(c))}let n=await y(ae.join(t.home,"state","onboarding.complete"));for(let[i,c]of Object.entries(Ui)){if(i==="BOOTSTRAP.md"&&n)continue;let l=ae.join(t.home,i);if(await y(l)){a.push(l);continue}try{await Hr(l,c,{encoding:"utf8",mode:384,flag:"wx"}),o.push(l)}catch(u){if(Vi(u)){a.push(l);continue}throw u}}let s=await Bi(t.home);return o.push(...s.createdFiles),a.push(...s.preservedFiles),{home:t.home,database:t.database,createdDirectories:r,createdFiles:o,preservedFiles:a}}function Vi(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}async function Bi(e){let t=[],r=[],o=new Date().toISOString().slice(0,10),a=ae.join(e,"memory","daily",`${o}.md`);await y(a)?r.push(a):(await Hr(a,Ba(o),{encoding:"utf8",mode:384,flag:"wx"}),t.push(a));let n=ae.join(e,"standing-orders","example.yaml");return await y(n)?r.push(n):(await Hr(n,Va,{encoding:"utf8",mode:384,flag:"wx"}),t.push(n)),{createdFiles:t,preservedFiles:r}}async function X(e,t){let r=ae.join(e,t);return await y(r)?Li(r,"utf8"):""}async function g(e){let t=p(e.home),r=new Date().toISOString(),o=Fr(K(e.details??{}),t.home),a={id:P("evt"),type:e.type,actor:e.actor??"cli",origin:e.origin??"nativesoul",result:e.result??"ok",details:o,created_at:r,hash:Ee({type:e.type,actor:e.actor??"cli",origin:e.origin??"nativesoul",result:e.result??"ok",details:o,created_at:r})},n=h(t.database);try{n.insertEvent(a)}finally{n.close()}return await Ki(Gi.dirname(t.auditLog),{recursive:!0,mode:448}),await Ji(t.auditLog,`${JSON.stringify(a)}
760
- `,{encoding:"utf8",mode:384}),a}function Fr(e,t){if(typeof e=="string")return Wi(e,t);if(Array.isArray(e))return e.map(r=>Fr(r,t));if(e&&typeof e=="object"){let r={};for(let[o,a]of Object.entries(e))r[o]=Fr(a,t);return r}return e}function Wi(e,t){return[[new RegExp($r(t),"gu"),"[REDACTED_NATIVESOUL_HOME]"],[new RegExp($r(process.cwd()),"gu"),"[REDACTED_WORKSPACE]"],[new RegExp($r(qi.homedir()),"gu"),"[REDACTED_USER_HOME]"],[/\/Users\/[A-Za-z0-9._-]+/gu,"[REDACTED_USER_HOME]"],[/\/home\/[A-Za-z0-9._-]+/gu,"[REDACTED_USER_HOME]"],[/[A-Z]:[\\/]+Users[\\/]+[A-Za-z0-9._-]+/gu,"[REDACTED_USER_HOME]"]].reduce((o,[a,n])=>o.replace(a,n),e)}function $r(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}import je from"node:path";import{mkdir as Bf,readdir as Al,readFile as El,writeFile as Jf}from"node:fs/promises";import{existsSync as qf}from"node:fs";import ts from"node:path";Pe();V();ue();V();import{readdir as ac}from"node:fs/promises";import q from"node:path";var Y="antigravity",nc="~/.gemini/GEMINI.md",sc="~/.antigravity",Vr="official:antigravity-plugin-config:v1",Ya="official:antigravity-hooks-config:v1",Qa="official:antigravity-mcp-config:v1",Za="official:antigravity-command-config:v1",ic="official:antigravity-context-config:v1",cc="official:antigravity-features:v1",lc=[{uid:"antigravity:plugins",nativeKind:"plugins",normalizedKind:"package",relativePath:"plugins"}];function Br(){let e=process.env.NATIVESOUL_ANTIGRAVITY_INVENTORY_ROOT?.trim();return e?q.resolve(e):v(sc)}function dc(){let e=Br();return{root:e,globalInstruction:process.env.NATIVESOUL_ANTIGRAVITY_INVENTORY_ROOT?.trim()?q.join(e,"GEMINI.md"):v(nc)}}async function en(){let e=[],t=dc();await _(t.globalInstruction)&&e.push({uid:"antigravity:global-gemini-md",host:Y,nativeKind:"global_context",normalizedKind:"instruction",source:t.globalInstruction,schemaHash:ic}),await uc(t.root,e),await pc(t.root,e);for(let r of lc){let o=q.join(t.root,r.relativePath);await T(o)&&e.push({uid:r.uid,host:Y,nativeKind:r.nativeKind,normalizedKind:r.normalizedKind,source:o,schemaHash:Vr})}return e}async function uc(e,t){let r=q.join(e,"plugin.json"),o=q.join(e,"nativesoul-package.json"),a=q.join(e,"hooks.json"),n=q.join(e,"mcp_config.json"),[s,i,c,l]=await Promise.all([M(r),M(o),M(a),M(n)]);if(s){let u=S(s,["name","id"])??"unknown";t.push({uid:`antigravity:plugin:${w(u)}`,host:Y,nativeKind:"plugin",normalizedKind:"extension",source:r,schemaHash:Vr})}if(i){let u=S(i,["name","id"])??"unknown";t.push({uid:`antigravity:package:${w(u)}`,host:Y,nativeKind:"native_plugin_package",normalizedKind:"package",source:o,schemaHash:Vr});let d=k(i.nativeSoul)?i.nativeSoul:{};for(let E of Ht(d.commands))t.push({uid:`antigravity:command:${w(E)}`,host:Y,nativeKind:"command",normalizedKind:"command",source:`${o}:nativeSoul.commands.${E}`,schemaHash:Za});let f=k(d.mcpServer)?d.mcpServer:null,m=S(f,["name"]);m&&t.push({uid:`antigravity:mcp:${w(m)}`,host:Y,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${o}:nativeSoul.mcpServer.${m}`,schemaHash:Qa})}if(c){t.push({uid:"antigravity:hooks:manifest",host:Y,nativeKind:"hooks",normalizedKind:"lifecycle_hooks",source:a,schemaHash:Ya});let u=k(c.hooks)?c.hooks:{};for(let d of Object.keys(u))t.push({uid:`antigravity:hook:${w(d)}`,host:Y,nativeKind:"hook",normalizedKind:"lifecycle_hook",source:`${a}:hooks.${d}`,schemaHash:Ya})}if(l)for(let u of fe(l.mcpServers))t.push({uid:`antigravity:mcp:${w(u)}`,host:Y,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${n}:mcpServers.${u}`,schemaHash:Qa});await mc(q.join(e,"commands"),t)}async function pc(e,t){let r=q.join(e,"features-evidence.json"),o=await M(r);if(!o)return;let a=["scheduled_tasks","cron_schedules","background_agents","subagents","skills","mcps","json_hooks"];for(let n of a)o[n]===!0&&t.push({uid:`antigravity:feature:${n.replace(/_/gu,"-")}`,host:Y,nativeKind:"product_feature",normalizedKind:"feature_evidence",source:`${r}:${n}`,schemaHash:cc})}async function mc(e,t){if(!await T(e))return;let r=await ac(e,{withFileTypes:!0});for(let o of r){if(!o.isFile()||q.extname(o.name)!==".md")continue;let a=q.basename(o.name,".md");t.push({uid:`antigravity:command:${w(a,{allowSlash:!0})}`,host:Y,nativeKind:"command",normalizedKind:"command",source:q.join(e,o.name),schemaHash:Za})}}V();ue();import $t from"node:path";async function tn(e){let t=await gc(e);if(!t)return null;let r=await M(t);return r?{product_features_verified:r.product_features_verified===!0,write_contract_verified:r.write_contract_verified===!0,native_id:typeof r.native_id=="string"&&r.native_id.trim().length>0?r.native_id.trim():void 0,enabled:typeof r.enabled=="boolean"?r.enabled:void 0,updated_at:typeof r.updated_at=="string"?r.updated_at:void 0,contract:k(r.contract)?{schedule:S(r.contract,["schedule"])??void 0,status:S(r.contract,["status"])??void 0,cancel:S(r.contract,["cancel"])??void 0,list:S(r.contract,["list"])??void 0,project_binding:S(r.contract,["project_binding"])??void 0}:void 0}:null}async function gc(e){let t=process.env.NATIVESOUL_ANTIGRAVITY_SCHEDULER_MANIFEST?.trim();if(t)return t;let r=process.env.NATIVESOUL_ANTIGRAVITY_INVENTORY_ROOT?.trim();if(r)return $t.join($t.resolve(r),"scheduler-proof.json");let o=e??v("~/.antigravity"),a=[$t.join(o,"scheduler-proof.json"),$t.join(o,"native-scheduler-proof.json")];for(let n of a)if(await _(n))return n;return null}function rn(e){if(!e)return!1;let t=Date.parse(e);return Number.isFinite(t)?Date.now()-t>10080*60*1e3:!0}var $e="antigravity",Jr="~/.gemini/GEMINI.md",Kr=class{async detect(){let t=v(Jr),r=Br(),[o,a,n]=await Promise.all([_(t),T(r),le("agy")]);return{host:$e,detected:a||n!==null,path:a?r:n??(o?t:void 0),capabilities:{installed:a||n!==null,enabled:a,active:!1,authenticated:!1,healthy:n!==null||a,allowed:!0,ready:!1}}}async install(t){return{status:"unsupported",reason:"Antigravity direct adapter writes are disabled; use the install orchestrator to install the NativeSoul native hook plugin, MCP registration, and managed block."}}async uninstall(t){return{status:"unsupported",reason:"Antigravity direct adapter uninstall is disabled; use the uninstall orchestrator for reversible package removal."}}async coldScan(){return en()}async hotProbe(){let t=await this.coldScan();return{host:$e,checkedAt:new Date().toISOString(),capabilities:t.map(r=>({...r,installed:!0,enabled:!0,active:r.nativeKind==="global_context",authenticated:!1,healthy:!0,allowed:!0,ready:r.schemaHash?.startsWith("official:")===!0}))}}async bootstrap(){return{tier:"A",mechanism:"hook",supported:!0}}async reload(t){return{status:"unsupported",reason:"Antigravity reload is host-driven; use the installed NativeSoul command package or restart the host if needed."}}async update(t){return{status:"unsupported",reason:"Antigravity package updates are handled by the NativeSoul install orchestrator."}}async scheduleReconcile(t){let r=await tn(t.hostConfigRoot);if(!r?.product_features_verified)return{status:"unsupported",reason:"Antigravity Scheduled Tasks product-level evidence was not detected; no hidden cron fallback installed."};if(!r.write_contract_verified)return{status:"unsupported",reason:"Antigravity product-level Scheduled Tasks are documented, but scheduler write/list/cancel/status contract proof is missing; keep full-native blocked_by_host:scheduler_write_contract_missing."};if(!r.contract?.schedule||!r.contract.status||!r.contract.cancel||!r.contract.list)return{status:"unsupported",reason:"Antigravity scheduler proof is missing one or more required commands: schedule, status, cancel, list."};if(r.enabled===!1)return{status:"degraded",reason:"Antigravity scheduler contract was detected, but the NativeSoul scheduled task is disabled."};if(!r.native_id)return{status:"degraded",reason:"Antigravity scheduler contract was detected, but no native task id mapping was returned."};if(rn(r.updated_at))return{status:"degraded",reason:"Antigravity scheduler proof is stale; re-run scheduler status/list before claiming full-native."};let o=t.apply?"reconciled":"reconcile planned";return{status:"ok",nativeId:r.native_id,message:`Antigravity Scheduled Task ${o}: ${r.native_id}`}}async doctor(){let t=await this.detect(),r=v(Jr),o=await O(r),a=[];return t.detected||a.push({code:"ANTIGRAVITY_NOT_DETECTED",severity:"warn",message:"No Antigravity CLI or ~/.antigravity directory was detected. A shared ~/.gemini/GEMINI.md alone is not treated as Antigravity readiness.",remediation:"Install Antigravity CLI or review `nativesoul adapters managed-block --host antigravity --json`."}),o&&!L(o,$e)&&a.push({code:"ANTIGRAVITY_MANAGED_BLOCK_MISSING",severity:"info",message:"GEMINI.md exists but has no NativeSoul managed block for Antigravity.",remediation:"Review `nativesoul adapters managed-block --host antigravity --json`."}),a}async managedBlockPreview(){let t=v(Jr),r=await O(t);return{host:$e,targetPath:t,startMarker:"<!-- nativesoul:antigravity:start v1 -->",endMarker:"<!-- nativesoul:antigravity:end -->",content:ne($e),wouldCreate:r===null,wouldUpdate:r!==null&&!L(r,$e)}}};function on(){return new Kr}Pe();ue();V();import Fe from"node:path";import{readFile as wn}from"node:fs/promises";ue();import{readFile as yn}from"node:fs/promises";import Ec from"node:path";var vn="life:heartbeat";function Rn(e){if(!e||typeof e!="object"||Array.isArray(e))return{kind:"unknown",mode:"leader",apply:!1,skill:vn};let t=e;return{kind:typeof t.kind=="string"?t.kind:"unknown",mode:typeof t.mode=="string"?t.mode:"leader",apply:t.apply===!0,skill:jc(t),surface:bn(t.surface)??bn(k(t.desired)?t.desired.surface:void 0)}}async function Sn(e={}){let t=process.env.NATIVESOUL_CLAUDE_SCHEDULED_TASKS_FIXTURES;if(t)try{return _n(await yn(Ec.join(t,"scheduled-tasks.json"),"utf8"))}catch{return null}let r=process.env.NATIVESOUL_CLAUDE_SCHEDULED_TASKS_MANIFEST;if(r)try{return _n(await yn(r,"utf8"))}catch{return null}if(process.env.NATIVESOUL_CLAUDE_SCHEDULED_TASKS_SUPPORTED==="1")return{supported:!0,native_id:process.env.NATIVESOUL_CLAUDE_SCHEDULED_TASKS_NATIVE_ID,surface:"claude-desktop",scheduler_kind:"unknown",creation_surface:"unknown",evidence_source:"env"};let{discoverClaudeScheduledTasksManifest:o}=await Promise.resolve().then(()=>(hn(),fn));return o({apply:e.apply,surface:e.surface,hostConfigRoot:e.hostConfigRoot})}function kn(e,t){return!e||e==="default"||!t?!0:e===t}function _n(e){let t=de(e);if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,o=Pc(r.surface),a=xc(r.scheduler_kind??r.kind);return{supported:r.supported===!0,native_id:typeof r.native_id=="string"&&r.native_id.length>0?r.native_id:void 0,surface:o??(a==="cloud_routine"?"cloud":"claude-desktop"),scheduler_kind:a,creation_surface:Tc(r.creation_surface),evidence_source:typeof r.evidence_source=="string"&&r.evidence_source.trim().length>0?r.evidence_source.trim():void 0,enabled:typeof r.enabled=="boolean"?r.enabled:void 0}}function bn(e){return e==="default"||e==="claude-code"||e==="claude-desktop"?e:void 0}function Pc(e){return e==="claude-code"||e==="claude-desktop"||e==="cloud"?e:void 0}function xc(e){return e==="local_scheduled_task"||e==="cloud_routine"||e==="ui_only"?e:"unknown"}function Tc(e){return e==="official_machine_readable"||e==="ui_only"||e==="unknown"?e:void 0}function jc(e){return k(e.desired)&&typeof e.desired.skill=="string"&&e.desired.skill.trim().length>0?e.desired.skill.trim():vn}var B="claude",Ft="~/.claude/CLAUDE.md",An="CLAUDE.md",En=".claude/CLAUDE.md",Pn="life:heartbeat",Tn="official:claude-cli-hot-scan:v1",Gr=class{async detect(){let t=v(Ft),r=Fe.resolve(An),o=Fe.resolve(En),[a,n,s,i]=await Promise.all([_(t),_(r),_(o),Dt("claude",["--version"])]);return{host:B,detected:a||n||s||i!==null,version:i??void 0,path:a?t:n?r:s?o:void 0,capabilities:{installed:a||n||s||i!==null,enabled:a||n||s,active:n||s,authenticated:!1,healthy:i!==null||a||n||s,allowed:!0,ready:!1}}}async install(t){return{status:"unsupported",reason:"Claude install writes are not implemented in M2.1; use managed-block preview first."}}async uninstall(t){return{status:"unsupported",reason:"Claude uninstall writes are not implemented in M2.1."}}async coldScan(){let t=v(Ft),r=Fe.resolve(An),o=Fe.resolve(En),a=[];return await _(t)&&a.push({uid:"claude:global-claude-md",host:B,nativeKind:"global_context",normalizedKind:"instruction",source:t}),await _(r)&&a.push({uid:"claude:project-claude-md",host:B,nativeKind:"project_context",normalizedKind:"instruction",source:r}),await _(o)&&a.push({uid:"claude:project-dot-claude-md",host:B,nativeKind:"project_context",normalizedKind:"instruction",source:o}),a}async hotProbe(t){let r=new Date().toISOString(),o=process.env.NATIVESOUL_CLAUDE_HOT_SCAN_FIXTURES?.trim();if(o){let c=await Cc(o,r);if(c.status==="ready")return c}let[a,n]=await Promise.all([Ur("claude",["mcp","list","--json"],1200),Ur("claude",["plugin","list","--json"],1200)]),s=[],i=[];return a.status==="ok"?i.push(...jn(a.stdout)):s.push(xn("CLAUDE_HOT_SCAN_JSON_UNSUPPORTED","claude mcp list --json",a.stderr)),n.status==="ok"?i.push(...Cn(n.stdout)):s.push(xn("CLAUDE_HOT_SCAN_JSON_UNSUPPORTED","claude plugin list --json",n.stderr)),{host:B,checkedAt:r,status:s.length===0?"ready":"degraded",warnings:s.map(c=>c.code),remediation:s.length===0?void 0:"Upgrade Claude Code CLI if JSON hot-scan commands are unavailable.",capabilities:i.map(c=>({...c,installed:c.installed??!0,enabled:c.enabled??!0,active:c.active??!0,authenticated:c.authenticated??!1,healthy:c.healthy??!0,allowed:!0,ready:c.ready??!1})),diagnostics:s}}async bootstrap(){return{tier:"B",mechanism:"global-instruction",supported:!0}}async reload(t){return{status:"unsupported",reason:"Claude reload is deferred until plugin lifecycle integration story."}}async update(t){return{status:"unsupported",reason:"Claude update is deferred until plugin lifecycle integration story."}}async scheduleReconcile(t){let r=Rn(t),o=await Sn({apply:r.apply,surface:r.surface,hostConfigRoot:t.hostConfigRoot});return o?.supported?r.kind!=="heartbeat"?{status:"unsupported",reason:"Claude adapter only supports NativeSoul heartbeat scheduled tasks."}:r.skill!==Pn?{status:"error",code:"CLAUDE_HEARTBEAT_SKILL_MISMATCH",message:`Claude heartbeat Scheduled Task must invoke ${Pn}.`}:o.scheduler_kind==="cloud_routine"||o.surface==="cloud"?{status:"unsupported",reason:"Claude cloud routines were detected, but they are out-of-scope for local native Scheduled Tasks evidence."}:o.scheduler_kind==="ui_only"||o.creation_surface==="ui_only"?{status:"unsupported",reason:"Claude task creation is UI-only for this surface; keep status blocked_by_host until a documented machine-readable surface returns a local task id."}:kn(r.surface,o.surface)?o.enabled===!1?{status:"degraded",reason:"Claude Scheduled Tasks support was detected, but the NativeSoul task is disabled."}:o.native_id?{status:"ok",nativeId:o.native_id,message:r.apply?`Claude Scheduled Task reconciled: ${o.native_id}`:`Claude Scheduled Task reconcile planned: ${o.native_id}`}:{status:"degraded",reason:"Claude Scheduled Tasks support was detected, but no native task id mapping was returned."}:{status:"unsupported",reason:`Claude Scheduled Tasks evidence is for ${o.surface??"unknown"} and does not satisfy ${r.surface}.`}:{status:"unsupported",reason:"Claude Scheduled Tasks native interface was not detected; no cron fallback installed."}}async doctor(){let t=await this.detect(),r=v(Ft),o=await O(r),a=[];return t.detected||a.push({code:"CLAUDE_NOT_DETECTED",severity:"warn",message:"No Claude CLI or CLAUDE.md instruction file was detected.",remediation:"Install Claude Code or create a managed block preview before enabling writes."}),o&&!L(o,B)&&a.push({code:"CLAUDE_MANAGED_BLOCK_MISSING",severity:"info",message:"Claude global CLAUDE.md exists but has no NativeSoul managed block.",remediation:"Review `nativesoul adapters managed-block --host claude --json`."}),a}async managedBlockPreview(){let t=v(Ft),r=await O(t);return{host:B,targetPath:t,startMarker:"<!-- nativesoul:claude:start v1 -->",endMarker:"<!-- nativesoul:claude:end -->",content:ne(B),wouldCreate:r===null,wouldUpdate:r!==null&&!L(r,B)}}};async function Cc(e,t){try{let[r,o]=await Promise.all([wn(Fe.join(e,"mcp-list.json"),"utf8"),wn(Fe.join(e,"plugin-list.json"),"utf8")]),a=[...jn(r),...Cn(o)];return{host:B,checkedAt:t,status:"ready",warnings:[],capabilities:a.map(n=>({...n,installed:n.installed??!0,enabled:n.enabled??!0,active:n.active??!0,authenticated:n.authenticated??!1,healthy:n.healthy??!0,allowed:!0,ready:n.ready??!1}))}}catch{return{host:B,checkedAt:t,status:"degraded",warnings:["CLAUDE_HOT_SCAN_FIXTURES_UNAVAILABLE"],remediation:"Set NATIVESOUL_CLAUDE_HOT_SCAN_FIXTURES to a directory containing mcp-list.json and plugin-list.json.",capabilities:[],diagnostics:[{code:"CLAUDE_HOT_SCAN_FIXTURES_UNAVAILABLE",severity:"warn",message:"Claude hot-scan fixtures were configured but could not be read.",remediation:"Verify NATIVESOUL_CLAUDE_HOT_SCAN_FIXTURES points at mcp-list.json and plugin-list.json."}]}}}function jn(e){let t=de(e);return he(t,["servers","mcps","items"]).flatMap(r=>{let o=S(r,["name","id","server","server_name"]);if(!o)return[];let a=S(r,["status","state"]),n=a!=="disabled",s=a==="connected"||a==="ready"||a==="active"||a==="ok"||a==="authenticated";return[{uid:`claude:mcp:${w(o)}`,host:B,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`claude mcp list:${o}`,schemaHash:Tn,enabled:n,active:n,authenticated:$(r,["authenticated"])??s,healthy:n,ready:In(a)}]})}function Cn(e){let t=de(e);return he(t,["plugins","items"]).flatMap(r=>{let o=S(r,["id","plugin","package"])??S(r,["name"]);if(!o)return[];let a=S(r,["status","state"]),n=$(r,["enabled"])??a!=="disabled",s=$(r,["installed"])??!0;return[{uid:`claude:plugin:${Ic(o)}`,host:B,nativeKind:"plugin",normalizedKind:"extension",source:`claude plugin list --json:${o}`,schemaHash:Tn,installed:s,enabled:n,active:n,authenticated:$(r,["authenticated"])??n,healthy:s,ready:n&&(a===null||In(a)||$(r,["enabled"])===!0)}]})}function xn(e,t,r){let o=Oc(r.trim()||"command unavailable or unsupported by installed Claude CLI");return{code:e,severity:"warn",message:`${t} did not return supported JSON output: ${o}`,remediation:"Upgrade Claude Code CLI or run `claude mcp list --json` / `claude plugin list --json` manually to confirm support."}}function In(e){return e==="ready"||e==="enabled"||e==="active"||e==="ok"||e==="authenticated"||e==="connected"}function Ic(e){return w(e,{allowSlash:!0})}function Oc(e){return e.replace(/\b[A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|API[_-]?KEY)[A-Z0-9_]*\s*=\s*\S+/giu,"[REDACTED_SECRET]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/gu,"[REDACTED_SECRET]")}function On(){return new Gr}Pe();ue();V();import Yr from"node:path";var F="codex",Vt="~/.codex/AGENTS.md",Dn="AGENTS.md",Yc=1e3,Hn="life:heartbeat",Jt="official:codex-app-server:v1",Qr=class{async detect(){let t=v(Vt),r=Yr.resolve(Dn),[o,a,n]=await Promise.all([_(t),_(r),le("codex")]);return{host:F,detected:o||a||n!==null,path:o?t:a?r:n??void 0,capabilities:{installed:o||a||n!==null,enabled:o||a,active:a,authenticated:!1,healthy:n!==null||o||a,allowed:!0,ready:!1}}}async install(t){return{status:"unsupported",reason:"Codex install writes are not implemented in M2.1; use managed-block preview first."}}async uninstall(t){return{status:"unsupported",reason:"Codex uninstall writes are not implemented in M2.1."}}async coldScan(){let t=v(Vt),r=Yr.resolve(Dn),o=[];return await _(t)&&o.push({uid:"codex:global-agents-md",host:F,nativeKind:"global_context",normalizedKind:"instruction",source:t}),await _(r)&&o.push({uid:"codex:project-agents-md",host:F,nativeKind:"project_context",normalizedKind:"instruction",source:r}),o}async hotProbe(t){let r=new Date().toISOString(),o=ol(t);if(o){let i=await Xr(o,r);if(i.status==="ready")return i}let a=process.env.NATIVESOUL_CODEX_APP_SERVER_FIXTURES?.trim();if(a){let i=await Xr(nl(a),r);if(i.status==="ready")return i}let n=al(t);if(n){let i=await Xr(sl(n),r);if(i.status==="ready")return i}let s=await this.coldScan();return{host:F,checkedAt:r,status:"degraded",warnings:["CODEX_APP_SERVER_UNAVAILABLE"],remediation:"Start Codex App Server and set NATIVESOUL_CODEX_APP_SERVER_URL before running `nativesoul adapters hot-scan --host codex`.",capabilities:s.map(i=>({...i,source:`codex app server fallback config scan:${i.source}`,installed:!0,enabled:!0,active:i.uid.includes("project"),authenticated:!1,healthy:!0,allowed:!0,ready:!1})),diagnostics:[{code:"CODEX_APP_SERVER_UNAVAILABLE",severity:"warn",message:"Codex App Server inventory endpoint is not configured or did not respond with supported JSON.",remediation:"Set NATIVESOUL_CODEX_APP_SERVER_URL to a reachable Codex App Server endpoint."}]}}async bootstrap(){return{tier:"B",mechanism:"global-instruction",supported:!0}}async reload(t){return{status:"unsupported",reason:"Codex reload is deferred until App Server integration story."}}async update(t){return{status:"unsupported",reason:"Codex update is deferred until marketplace/App Server integration story."}}async scheduleReconcile(t){let{discoverCodexAutomationsManifest:r}=await Promise.resolve().then(()=>(Ln(),Mn)),o=await r({apply:t.apply,hostConfigRoot:t.hostConfigRoot});return o?.supported?t.kind!=="heartbeat"?{status:"unsupported",reason:"Codex adapter only supports NativeSoul heartbeat automations."}:t.desired.skill!==Hn?{status:"error",code:"CODEX_HEARTBEAT_SKILL_MISMATCH",message:`Codex heartbeat Automation must invoke ${Hn}.`}:o.native_id?{status:"ok",nativeId:o.native_id,message:t.apply?`Codex Automation reconciled: ${o.native_id}`:`Codex Automation reconcile planned: ${o.native_id}`}:{status:"degraded",reason:"Codex Automations support was detected, but no native automation id mapping was returned."}:{status:"unsupported",reason:"Codex Automations native interface was not detected; no cron fallback installed."}}async doctor(){let t=await this.detect(),r=v(Vt),o=await O(r),a=[];return t.detected||a.push({code:"CODEX_NOT_DETECTED",severity:"warn",message:"No Codex CLI or AGENTS.md instruction file was detected.",remediation:"Install Codex or create a managed block preview before enabling writes."}),o&&!L(o,F)&&a.push({code:"CODEX_MANAGED_BLOCK_MISSING",severity:"info",message:"Codex global AGENTS.md exists but has no NativeSoul managed block.",remediation:"Review `nativesoul adapters managed-block --host codex --json`."}),a}async managedBlockPreview(){let t=v(Vt),r=await O(t);return{host:F,targetPath:t,startMarker:"<!-- nativesoul:codex:start v1 -->",endMarker:"<!-- nativesoul:codex:end -->",content:ne(F),wouldCreate:r===null,wouldUpdate:r!==null&&!L(r,F)}}};async function Xr(e,t){let[r,o,a,n]=await Promise.all([Bt(e,"mcpServerStatus/list"),Bt(e,"plugin/list"),Bt(e,"skills/list"),Bt(e,"app/list")]);if([r,o,a,n].some(c=>c===null))return{host:F,checkedAt:t,status:"degraded",warnings:["CODEX_APP_SERVER_UNAVAILABLE"],remediation:"Ensure Codex App Server is running and supports mcpServerStatus/list, plugin/list, skills/list, and app/list.",capabilities:[],diagnostics:[{code:"CODEX_APP_SERVER_UNAVAILABLE",severity:"warn",message:"Codex App Server did not return supported JSON inventory for all required methods.",remediation:"Check NATIVESOUL_CODEX_APP_SERVER_URL and Codex App Server version."}]};let i=[...Zc(r),...el(o),...tl(a),...rl(n)];return{host:F,checkedAt:t,status:"ready",warnings:[],capabilities:i.map(c=>({...c,installed:c.installed??!0,enabled:c.enabled??!0,active:c.active??!0,authenticated:c.authenticated??!1,healthy:c.healthy??!0,allowed:!0,ready:c.ready??!1}))}}async function Bt(e,t){try{return await e.call(t)}catch{return null}}async function Qc(e,t){let r=new AbortController,o=setTimeout(()=>r.abort(),Yc);try{let a=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:t,method:t,params:{}}),signal:r.signal});if(!a.ok)return null;let n=await a.json();return k(n)&&"error"in n?null:k(n)&&"result"in n?n.result:n}catch{return null}finally{clearTimeout(o)}}function Zc(e){return he(e,["servers","mcpServers","items"]).flatMap(t=>{let r=S(t,["id","name","server","server_name"]);if(!r)return[];let o=S(t,["status","state"]),a=Kt(t,o);return[{uid:`codex:mcp:${w(r)}`,host:F,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`codex app server mcpServerStatus/list:${r}`,schemaHash:Jt,...a}]})}function el(e){return he(e,["plugins","items"]).flatMap(t=>{let r=S(t,["id","plugin","package"])??S(t,["name"]);if(!r)return[];let o=S(t,["status","state"]),a=Kt(t,o);return[{uid:`codex:plugin:${Zr(r)}`,host:F,nativeKind:"plugin",normalizedKind:"extension",source:`codex app server plugin/list:${r}`,schemaHash:Jt,...a}]})}function tl(e){return he(e,["skills","items"]).flatMap(t=>{let r=S(t,["id","name","path"]);if(!r)return[];let o=S(t,["status","state"]),a=Kt(t,o);return[{uid:`codex:skill:${Zr(r)}`,host:F,nativeKind:"skill",normalizedKind:"skill",source:`codex app server skills/list:${r}`,schemaHash:Jt,...a}]})}function rl(e){return he(e,["apps","items"]).flatMap(t=>{let r=S(t,["id","name","app"]);if(!r)return[];let o=S(t,["status","state"]),a=Kt(t,o);return[{uid:`codex:app:${Zr(r)}`,host:F,nativeKind:"app_server_app",normalizedKind:"app",source:`codex app server app/list:${r}`,schemaHash:Jt,...a}]})}function Kt(e,t){let r=$(e,["installed"])??!0,o=t==="disabled"||t==="unavailable",a=t==="error"||t==="unhealthy",n=$(e,["enabled"])??!o,s=$(e,["active"])??n,i=$(e,["healthy"])??(!o&&!a),c=$(e,["authenticated"])??$(e,["auth"])??!1,l=$(e,["ready"])??(r&&n&&s&&i);return{installed:r,enabled:n,active:s,authenticated:c,healthy:i,ready:l}}function ol(e){if(k(e)){let t=e.appServer;if(k(t)&&typeof t.call=="function")return{call:r=>Promise.resolve(t.call(r))}}return null}function al(e){if(k(e)){let t=e.appServerUrl;if(typeof t=="string"&&t.trim().length>0)return t.trim()}return process.env.NATIVESOUL_CODEX_APP_SERVER_URL?.trim()||process.env.CODEX_APP_SERVER_URL?.trim()||null}function nl(e){return{async call(t){try{let{readFile:r}=await import("node:fs/promises"),o=t.replace(/\//gu,"-");return JSON.parse(await r(Yr.join(e,`${o}.json`),"utf8"))}catch(r){let o=r instanceof Error?r.message:"unknown error";throw new Error(`Codex App Server fixture unavailable for ${t}: ${o}`,{cause:r})}}}}function sl(e){return{call:t=>Qc(e,t)}}function Zr(e){return w(e,{allowSlash:!0})}function $n(){return new Qr}Pe();ue();V();import{readdir as Un}from"node:fs/promises";import Q from"node:path";var D="gemini",to="~/.gemini/GEMINI.md",il="~/.gemini/extensions",cl="~/.gemini/settings.json",Ze="official:gemini-extension-config:v1",eo="official:gemini-settings-config:v1",ll="official:gemini-memory-config:v1",ro=class{async detect(){let t=Fn(),r=t.globalInstruction,o=t.extensionsDirectory,[a,n,s]=await Promise.all([_(r),T(o),Dt("gemini",["--version"])]);return{host:D,detected:a||n||s!==null,version:s??void 0,path:a?r:n?o:void 0,capabilities:{installed:a||n||s!==null,enabled:a||n,active:a,authenticated:!1,healthy:s!==null||a||n,allowed:!0,ready:!1}}}async install(t){return{status:"unsupported",reason:"Gemini direct adapter writes are disabled; use the install orchestrator to install the NativeSoul Gemini extension, MCP registration, and managed block."}}async uninstall(t){return{status:"unsupported",reason:"Gemini direct adapter uninstall is disabled; use the uninstall orchestrator for reversible package removal."}}async coldScan(){let t=[],r=Fn(),o=r.globalInstruction;await _(o)&&t.push({uid:"gemini:global-gemini-md",host:D,nativeKind:"global_context",normalizedKind:"memory",source:o,schemaHash:ll}),await dl(r.settingsFile,t);let a=r.extensionsDirectory;if(await T(a)){t.push({uid:"gemini:extensions",host:D,nativeKind:"extensions",normalizedKind:"package",source:a,schemaHash:Ze});let n=await Un(a,{withFileTypes:!0});for(let s of n)s.isDirectory()&&await ul(Q.join(a,s.name),s.name,t)}return t}async hotProbe(){let t=await this.coldScan();return{host:D,checkedAt:new Date().toISOString(),capabilities:t.map(r=>({...r,installed:!0,enabled:!0,active:r.nativeKind==="global_context"||r.schemaHash?.startsWith("official:")===!0,authenticated:!1,healthy:!0,allowed:!0,ready:r.schemaHash?.startsWith("official:")===!0}))}}async bootstrap(){return{tier:"A",mechanism:"hook",supported:!0}}async reload(t){return{status:"unsupported",reason:"Gemini extension reload is host-driven; run /memory refresh or restart Gemini after installing NativeSoul."}}async update(t){return{status:"unsupported",reason:"Gemini package updates are handled by the NativeSoul install orchestrator."}}async scheduleReconcile(t){return{status:"unsupported",reason:"Gemini does not expose a documented native scheduler for NativeSoul; use the packaged heartbeat command manually or host-supported commands, with no hidden cron."}}async doctor(){let t=await this.detect(),r=v(to),o=await O(r),a=[];return t.detected||a.push({code:"GEMINI_NOT_DETECTED",severity:"warn",message:"No Gemini CLI, GEMINI.md, or extensions directory was detected.",remediation:"Install Gemini CLI or review `nativesoul adapters managed-block --host gemini --json`."}),o&&!L(o,D)&&a.push({code:"GEMINI_MANAGED_BLOCK_MISSING",severity:"info",message:"GEMINI.md exists but has no NativeSoul managed block.",remediation:"Review `nativesoul adapters managed-block --host gemini --json`."}),a}async managedBlockPreview(){let t=v(to),r=await O(t);return{host:D,targetPath:t,startMarker:"<!-- nativesoul:gemini:start v1 -->",endMarker:"<!-- nativesoul:gemini:end -->",content:ne(D),wouldCreate:r===null,wouldUpdate:r!==null&&!L(r,D)}}};function Fn(){let e=process.env.NATIVESOUL_GEMINI_INVENTORY_ROOT?.trim();if(e){let t=Q.resolve(e);return{globalInstruction:Q.join(t,"GEMINI.md"),settingsFile:Q.join(t,"settings.json"),extensionsDirectory:Q.join(t,"extensions")}}return{globalInstruction:v(to),settingsFile:v(cl),extensionsDirectory:v(il)}}async function dl(e,t){let r=await M(e);if(r){t.push({uid:"gemini:settings",host:D,nativeKind:"settings",normalizedKind:"config",source:e,schemaHash:eo});for(let o of fe(r.mcpServers))t.push({uid:`gemini:mcp:${w(o)}`,host:D,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${e}:mcpServers.${o}`,schemaHash:eo});for(let o of Vn(r.tools))t.push({uid:`gemini:tool:${w(o)}`,host:D,nativeKind:"tool",normalizedKind:"tool",source:`${e}:tools.${o}`,schemaHash:eo})}}async function ul(e,t,r){let o=Q.join(e,"gemini-extension.json"),a=await M(o),n=S(a,["name","id"])??t;if(r.push({uid:`gemini:extension:${w(n)}`,host:D,nativeKind:"extension",normalizedKind:"package",source:a?o:e,schemaHash:a?Ze:void 0}),a){for(let s of fe(a.mcpServers))r.push({uid:`gemini:mcp:${w(s)}`,host:D,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${o}:mcpServers.${s}`,schemaHash:Ze});for(let s of Vn(a.tools))r.push({uid:`gemini:tool:${w(s)}`,host:D,nativeKind:"tool",normalizedKind:"tool",source:`${o}:tools.${s}`,schemaHash:Ze})}await pl(Q.join(e,"commands"),r)}async function pl(e,t){if(!await T(e))return;let r=await Un(e,{withFileTypes:!0});for(let o of r){if(!o.isFile()||![".toml",".md"].includes(Q.extname(o.name)))continue;let a=Q.basename(o.name,Q.extname(o.name));t.push({uid:`gemini:command:${w(a,{allowSlash:!0})}`,host:D,nativeKind:"command",normalizedKind:"command",source:Q.join(e,o.name),schemaHash:Ze})}}function Vn(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):fe(e)}function Bn(){return new ro}Pe();ue();V();import{readdir as Wn}from"node:fs/promises";import C from"node:path";var j="grok",qt="~/.grok/Agents.md",Jn="AGENTS.md",Kn="Agents.md",qn="CLAUDE.md",ml="~/.grok",oo="official:grok-plugin-config:v1",Gn="official:grok-hooks-config:v1",ao="official:grok-mcp-config:v1",zn="official:grok-command-config:v1",gl="official:grok-context-config:v1",fl=[{uid:"grok:plugins",nativeKind:"plugins",normalizedKind:"package",relativePath:"plugins"},{uid:"grok:skills",nativeKind:"skills",normalizedKind:"capability",relativePath:"skills"},{uid:"grok:hooks",nativeKind:"hooks",normalizedKind:"capability",relativePath:"hooks"},{uid:"grok:mcps",nativeKind:"mcp",normalizedKind:"capability",relativePath:"mcps"}],no=class{async detect(){let t=v(qt),r=C.resolve(Jn),o=C.resolve(Kn),a=C.resolve(qn),n=Xn(),[s,i,c,l,u,d]=await Promise.all([_(t),_(r),_(o),_(a),T(n),le("grok")]),f=i||c;return{host:j,detected:s||f||l||u||d!==null,path:s?t:c?o:i?r:l?a:d??void 0,capabilities:{installed:s||f||l||u||d!==null,enabled:s||f||l||u,active:f||l,authenticated:!1,healthy:d!==null||s||u,allowed:!0,ready:!1}}}async install(t){return{status:"unsupported",reason:"Grok direct adapter writes are disabled; use the install orchestrator to install the NativeSoul native hook plugin, MCP registration, and managed block."}}async uninstall(t){return{status:"unsupported",reason:"Grok direct adapter uninstall is disabled; use the uninstall orchestrator for reversible package removal."}}async coldScan(){let t=[],r=hl(),o=r.globalInstruction;await _(o)&&t.push({uid:"grok:global-agents-md",host:j,nativeKind:"global_context",normalizedKind:"instruction",source:o,schemaHash:gl});let a=C.resolve(Jn);await _(a)&&t.push({uid:"grok:project-agents-md",host:j,nativeKind:"project_context",normalizedKind:"instruction",source:a});let n=C.resolve(Kn);await _(n)&&t.push({uid:"grok:project-agents-titlecase-md",host:j,nativeKind:"project_context",normalizedKind:"instruction",source:n});let s=C.resolve(qn);await _(s)&&t.push({uid:"grok:project-claude-md",host:j,nativeKind:"project_context",normalizedKind:"instruction",source:s});let i=r.root;await Yn(r.root,t),await yl(i,t);for(let c of fl){let l=C.join(i,c.relativePath);await T(l)&&t.push({uid:c.uid,host:j,nativeKind:c.nativeKind,normalizedKind:c.normalizedKind,source:l,schemaHash:c.relativePath==="mcps"?ao:oo})}return bl(t)}async hotProbe(){let t=await this.coldScan();return{host:j,checkedAt:new Date().toISOString(),capabilities:t.map(r=>({...r,installed:!0,enabled:!0,active:r.uid.includes("project"),authenticated:!1,healthy:!0,allowed:!0,ready:r.schemaHash?.startsWith("official:")===!0}))}}async bootstrap(){return{tier:"A",mechanism:"hook",supported:!0}}async reload(t){return{status:"unsupported",reason:"Grok reload is host-driven; use the installed NativeSoul command package or restart the host if needed."}}async update(t){return{status:"unsupported",reason:"Grok package updates are handled by the NativeSoul install orchestrator."}}async scheduleReconcile(t){return{status:"unsupported",reason:"Grok has no documented native scheduler or recurring task surface for NativeSoul; headless grok -p, cron, GitHub Actions, systemd, and Windows Task Scheduler are external schedulers and do not satisfy full-native capability."}}async doctor(){let t=await this.detect(),r=v(qt),o=await O(r),a=[];return t.detected||a.push({code:"GROK_NOT_DETECTED",severity:"warn",message:"No Grok CLI, ~/.grok directory, or project instruction file was detected.",remediation:"Install Grok Build or review `nativesoul adapters managed-block --host grok --json`."}),o&&!L(o,j)&&a.push({code:"GROK_MANAGED_BLOCK_MISSING",severity:"info",message:"Grok global Agents.md exists but has no NativeSoul managed block.",remediation:"Review `nativesoul adapters managed-block --host grok --json`."}),a}async managedBlockPreview(){let t=v(qt),r=await O(t);return{host:j,targetPath:t,startMarker:"<!-- nativesoul:grok:start v1 -->",endMarker:"<!-- nativesoul:grok:end -->",content:ne(j),wouldCreate:r===null,wouldUpdate:r!==null&&!L(r,j)}}};function Xn(){let e=process.env.NATIVESOUL_GROK_INVENTORY_ROOT?.trim();return e?C.resolve(e):v(ml)}function hl(){let e=Xn();return{root:e,globalInstruction:process.env.NATIVESOUL_GROK_INVENTORY_ROOT?.trim()?C.join(e,"Agents.md"):v(qt)}}async function Yn(e,t){let r=C.join(e,"plugin.json"),o=C.join(e,"nativesoul-package.json"),a=C.join(e,"hooks","hooks.json"),n=C.join(e,".mcp.json"),[s,i,c,l]=await Promise.all([M(r),M(o),M(a),M(n)]);if(s){let u=S(s,["name","id"])??"unknown";t.push({uid:`grok:plugin:${w(u)}`,host:j,nativeKind:"plugin",normalizedKind:"extension",source:r,schemaHash:oo})}if(i){let u=S(i,["name","id"])??"unknown";t.push({uid:`grok:package:${w(u)}`,host:j,nativeKind:"native_plugin_package",normalizedKind:"package",source:o,schemaHash:oo});let d=k(i.nativeSoul)?i.nativeSoul:{};for(let E of Ht(d.commands))t.push({uid:`grok:command:${w(E)}`,host:j,nativeKind:"command",normalizedKind:"command",source:`${o}:nativeSoul.commands.${E}`,schemaHash:zn});let f=k(d.mcpServer)?d.mcpServer:null,m=S(f,["name"]);m&&t.push({uid:`grok:mcp:${w(m)}`,host:j,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${o}:nativeSoul.mcpServer.${m}`,schemaHash:ao})}if(c){t.push({uid:"grok:hooks:manifest",host:j,nativeKind:"hooks",normalizedKind:"lifecycle_hooks",source:a,schemaHash:Gn});let u=k(c.hooks)?c.hooks:{};for(let d of Object.keys(u))t.push({uid:`grok:hook:${w(d)}`,host:j,nativeKind:"hook",normalizedKind:"lifecycle_hook",source:`${a}:hooks.${d}`,schemaHash:Gn})}if(l)for(let u of fe(l.mcpServers))t.push({uid:`grok:mcp:${w(u)}`,host:j,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${n}:mcpServers.${u}`,schemaHash:ao});await _l(C.join(e,"commands"),t)}async function yl(e,t){let r=C.join(e,"plugins");if(!await T(r))return;let o=await Wn(r,{withFileTypes:!0});for(let a of o)a.isDirectory()&&await Yn(C.join(r,a.name),t)}async function _l(e,t){if(!await T(e))return;let r=await Wn(e,{withFileTypes:!0});for(let o of r){if(!o.isFile()||C.extname(o.name)!==".md")continue;let a=C.basename(o.name,".md");t.push({uid:`grok:command:${w(a,{allowSlash:!0})}`,host:j,nativeKind:"command",normalizedKind:"command",source:C.join(e,o.name),schemaHash:zn})}}function bl(e){let t=new Set,r=[];for(let o of e)t.has(o.uid)||(t.add(o.uid),r.push(o));return r}function Qn(){return new no}import{mkdir as Sf,readFile as vl,rm as kf,writeFile as wf}from"node:fs/promises";import{existsSync as Rl}from"node:fs";import Pf from"node:path";function Sl(e){return{start:`<!-- nativesoul:${e}:start v1 -->`,end:`<!-- nativesoul:${e}:end -->`}}async function Zn(e){let t=Rl(e.targetPath),r=[];if(!t)return r.push({code:"MANAGED_BLOCK_TARGET_MISSING",severity:"warn",message:`Managed block target is missing: ${e.targetPath}`,remediation:"Run nativesoul install --host <host> --apply"}),{host:e.host,targetPath:e.targetPath,target_exists:!1,configured:!1,markers_valid:!1,issues:r};let o=await vl(e.targetPath,"utf8"),a=Sl(e.host),n=o.indexOf(a.start),s=o.indexOf(a.end),i=n>=0,c=s>=0,l=i&&c&&s>n;return!i&&!c?r.push({code:"MANAGED_BLOCK_MISSING",severity:"warn",message:"NativeSoul managed block is not configured.",remediation:"Run nativesoul install --host <host> --apply"}):l||r.push({code:"MANAGED_BLOCK_MARKERS_INVALID",severity:"error",message:"NativeSoul managed block markers are incomplete or out of order.",remediation:"Fix the managed block markers or restore from a backup snapshot"}),{host:e.host,targetPath:e.targetPath,target_exists:!0,configured:l,markers_valid:l,issues:r}}var kl=["codex","claude","grok","antigravity","gemini"],wl={codex:$n,claude:On,grok:Qn,antigravity:on,gemini:Bn};function Ue(e){return e==="all"?kl:[e]}function es(e){return Ue(e)}function so(e){return wl[e]()}async function io(e){let t=[];for(let r of es(e)){let o=so(r);t.push({host:r,diagnostics:await o.doctor({})})}return t}async function Ve(e){let t=e.readOnly?p(e.home):await b(e.home);if(e.readOnly&&!await y(t.database))return[];let r=h(t.database,{readOnly:e.readOnly}),o=as(e.limit);try{return r.listCapabilities({host:e.host,readyOnly:e.readyOnly,limit:o,includeShared:e.includeShared})}finally{r.close()}}async function co(e){let t=await b(e.home),r=h(t.database),o=as(e.limit);try{return r.searchCapabilities({query:e.query,host:e.host,readyOnly:e.readyOnly,limit:o,includeShared:e.includeShared})}finally{r.close()}}async function lo(e){let t=await b(e.home),r=h(t.database);try{return r.getCapability(e.uid)}finally{r.close()}}async function uo(e){let t=e.readOnly?p(e.home):await b(e.home),r=ts.join(t.home,"capabilities","cards"),o=[];if(!await y(r))return{cards:[],warnings:o};let a=(await Al(r)).filter(l=>l.endsWith(".json")).sort(),n=Il(e.query??""),s=[];for(let l of a){let u=ts.join(r,l),d;try{d=await El(u,"utf8")}catch{o.push(`CAPABILITY_CARD_UNREADABLE:${l}`);continue}let f=xl(d);if(!f){o.push(`CAPABILITY_CARD_MALFORMED:${l}`);continue}let m=Tl(f,e.host);s.push({card:m,score:jl(f,e.host,n)})}let i=Ol(e.limit),c=s.sort((l,u)=>u.score-l.score||l.card.uid.localeCompare(u.card.uid));return{cards:Pl(c,i).map(l=>l.card),warnings:o}}function Pl(e,t){let r=e.slice(0,t);if(t<=1||r.some(a=>a.card.alternative_host))return r;let o=e.find(a=>a.card.alternative_host);return o?[...r.slice(0,t-1),o].sort((a,n)=>n.score-a.score||a.card.uid.localeCompare(n.card.uid)):r}function xl(e){let t;try{t=JSON.parse(e)}catch{return null}if(!rs(t))return null;let r=t.readiness;return t.card_version!==1||typeof t.id!="string"||typeof t.uid!="string"||typeof t.host!="string"||typeof t.native_kind!="string"||typeof t.normalized_kind!="string"||typeof t.source!="string"||typeof t.schema_hash!="string"||!Array.isArray(t.use_when)||!Array.isArray(t.requires)||!Array.isArray(t.side_effects)||typeof t.approval!="string"||!Array.isArray(t.examples)||!Cl(r)?null:t}function Tl(e,t){let r=e.host!==t,o=e.host!==t&&e.host!=="all";return{id:e.id,uid:e.uid,host:e.host,ready:e.readiness.ready,source:e.source,schema_hash:e.schema_hash,use_when:et(e.use_when).slice(0,2),requires:et(e.requires).slice(0,4),approval:e.approval,alternative_host:r,available_on_other_host:o}}function jl(e,t,r){let o=os([e.uid,e.host,e.native_kind,e.normalized_kind,e.source,e.schema_hash,...et(e.use_when),...et(e.requires),e.approval,...et(e.examples)].join(" ")),a=r.reduce((n,s)=>n+(o.includes(s)?10:0),0);return(e.host===t?100:0)+(e.readiness.ready?5:0)+a}function et(e){return e.filter(t=>typeof t=="string")}function rs(e){return typeof e=="object"&&e!==null}function Cl(e){return rs(e)?["installed","enabled","active","authenticated","healthy","allowed","ready"].every(t=>typeof e[t]=="boolean"):!1}function Il(e){return os(e).split(/\s+/u).map(t=>t.trim()).filter(t=>t.length>=2)}function os(e){return e.toLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/gu,"")}function as(e){return Math.min(Math.max(e??50,1),100)}function Ol(e){return Math.min(Math.max(e??5,1),8)}async function po(e){let t=await b(e.home),r=H(e.summary).value,o=new Date,a=e.ttlSeconds?new Date(o.getTime()+Ml(e.ttlSeconds)*1e3).toISOString():null,n=K(e.source??{host:"cli",session_id:"local"}),s=h(t.database),i;try{i=s.createOpenCommitmentIfMissing({id:P("commitment"),project_id:e.project,summary:r,status:"open",due_at:e.dueAt??null,ttl_expires_at:a,source:n,created_at:o.toISOString(),updated_at:o.toISOString()},o.toISOString())}finally{s.close()}return await g({home:t.home,type:i.created?"commitment_created":"commitment_deduped",details:{id:i.commitment.id,project:i.commitment.project_id,redacted:r!==e.summary,created:i.created}}),i}async function mo(e){let t=e.readOnly?p(e.home):await b(e.home);if(e.readOnly&&!await y(t.database))return[];let r=h(t.database,{readOnly:e.readOnly}),o;try{o=r.listCommitments({project:e.project,status:e.status??(e.includeExpired?void 0:"open"),includeExpired:e.includeExpired,limit:Math.min(Math.max(e.limit??50,1),200),now:new Date().toISOString(),skipExpire:e.readOnly})}finally{r.close()}return e.readOnly||await g({home:t.home,type:"commitments_listed",details:{project:e.project??null,status:e.status??null,includeExpired:e.includeExpired===!0,count:o.length}}),o}async function go(e,t){return Nl(e,t,"completed","commitment_completed")}async function Nl(e,t,r,o){let a=await b(e),n=h(a.database),s;try{s=n.updateCommitmentStatus(t,r,new Date().toISOString())}finally{n.close()}if(!s)throw new Error(`Commitment not found: ${t}`);return await g({home:a.home,type:o,details:{id:s.id,project:s.project_id,status:s.status}}),s}function Ml(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),365*24*60*60):1440*60}import{createHash as Ll}from"node:crypto";import{existsSync as Gt,mkdirSync as Dl,realpathSync as Hl,readFileSync as ss,writeFileSync as $l}from"node:fs";import{spawnSync as is}from"node:child_process";import se from"node:path";function pe(e,t){let r=fo(e),o=Bl(r),a=o?Jl(o):null,n=a?ns(a):o??r,s=Kl(n),i=a?"git-remote":o?"git-root":"path",c=Ul(s,n),l=Fl(r),u=l?cs(l):null,d=ds(t),f=[u,c,a?ns(a):null,o,r].find(m=>m&&d[m]);if(f){let m=u??c;return{id:d[f]??m,source:"alias",cwd:r,git_root:o,remote:a,base_id:m,alias_key:f,marker_path:l}}return u?{id:u,source:"marker",cwd:r,git_root:o,remote:a,base_id:u,alias_key:null,marker_path:l}:{id:c,source:i,cwd:r,git_root:o,remote:a,base_id:c,alias_key:null,marker_path:null}}function cs(e){if(!Gt(e))return null;let t=ss(e,"utf8").trim();if(t.length===0)return null;let r=t.match(/^(?:project_id|id):\s*([a-z0-9._-]+)\s*$/imu);if(r?.[1])return r[1];let o=t.split(/\r?\n/u).map(a=>a.trim()).find(a=>a.length>0&&!a.startsWith("#"));return o?Vl(o):null}function ls(e,t){let r=se.join(e,".nativesoul","project");return Dl(se.dirname(r),{recursive:!0,mode:448}),$l(r,`${t}
761
- `,{encoding:"utf8",mode:384}),r}async function Wt(e){let t=pe(e.cwd,e.home);if(t.source!=="git-root"&&t.source!=="path")return{written:!1,marker_path:t.marker_path,base_id:t.base_id};let r=t.git_root??t.cwd,o=se.join(r,".nativesoul","project");return Gt(o)?{written:!1,marker_path:o,base_id:t.base_id}:(ls(r,t.base_id),{written:!0,marker_path:o,base_id:t.base_id})}function Fl(e){let t=fo(e);for(;;){let r=se.join(t,".nativesoul","project");if(Gt(r))return r;let o=se.dirname(t);if(o===t)return null;t=o}}function Ul(e,t){let r=Ll("sha256").update(t).digest("hex").slice(0,10);return`${ql(e)}-${r}`}function Vl(e){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"workspace"}function fo(e){try{return Hl(se.resolve(e))}catch{return se.resolve(e)}}function Bl(e){let t=is("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(t.status!==0)return null;let r=t.stdout.trim();return r.length>0?fo(r):null}function Jl(e){let t=is("git",["-C",e,"remote","get-url","origin"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(t.status!==0)return null;let r=t.stdout.trim();return r.length>0?r:null}function ns(e){return e.trim().replace(/^git@([^:]+):/,"https://$1/").replace(/^ssh:\/\/git@([^/]+)\//,"https://$1/").replace(/^https?:\/\/([^/]+)\//,"https://$1/").replace(/\.git$/u,"").toLowerCase()}function Kl(e){let t=e.replace(/\/+$/u,"");return se.basename(t)||"workspace"}function ql(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"workspace"}function ds(e){if(!e)return{};let t=se.join(se.resolve(e),"config.yaml");if(!Gt(t))return{};let r=ss(t,"utf8"),o={},a=!1,n=!1,s="";for(let i of r.split(/\r?\n/u)){if(/^\S/u.test(i)){a=/^project:\s*$/u.test(i),n=!1;continue}let c=i.match(/^([ \t]+)aliases:\s*(?:\{\}\s*)?$/u);if(a&&c?.[1]){n=!0,s=c[1];continue}if(n){if(i.trim().length===0||i.trim().startsWith("#"))continue;let l=i.match(/^([ \t]+)(?:"([^"]+)"|'([^']+)'|([^:]+)):\s*(?:"([^"]+)"|'([^']+)'|(.+))\s*$/u);(l?.[1]??"").length<=s.length&&(n=!1);let d=l?.[2]??l?.[3]??l?.[4],f=l?.[5]??l?.[6]??l?.[7];n&&d&&f?o[d.trim()]=f.trim():/^[ \t]+\S/u.test(i)&&i.trim().length>0&&(n=!1)}}return o}import{readFile as fh,writeFile as hh}from"node:fs/promises";import _h from"node:path";import jh from"node:path";var Gl={minLength:1,removeStopwords:!1,normalizeDiacritics:!1};function zt(e,t={}){let r={...Gl,...t},o=r.normalizeDiacritics?e.normalize("NFKD").replace(new RegExp("\\p{Diacritic}","gu"),""):e;return Array.from(new Set(o.toLowerCase().match(/[\p{L}\p{N}_-]+/gu)?.filter(a=>a.length>=r.minLength).filter(a=>!r.removeStopwords||!Wl.has(a))??[]))}function us(e,t={}){return new Set(zt(e,t))}function ho(e,t){let r=zt(e);if(r.length===0)return 0;let o=us(t),a=r.filter(n=>o.has(n)).length;return Number((a/r.length).toFixed(6))}function ps(e,t){let r=Math.min(e.length,t.length),o=0;for(let a=0;a<r;a+=1)o+=(e[a]??0)*(t[a]??0);return Number(Math.max(o,0).toFixed(6))}var Wl=new Set(["the","and","for","with","this","that","uma","com","para","por","que","deve","esta","este","essa","isso"]);var Xt=1,Yt="local-hash",Qt="local-hash-bow-v1";function gs(e){let t=h(e,{readOnly:!0});try{let r=t.semanticIndexStats({providerId:Yt,modelId:Qt,schemaVersion:Xt});return{provider_id:Yt,model_id:Qt,schema_version:Xt,available:!0,indexable_count:r.indexable_count,indexed_count:r.indexed_count,stale_count:r.stale_count,healthy:r.stale_count===0,remediation:r.stale_count===0?null:"Run nativesoul memory index"}}finally{t.close()}}function Zt(e){let t=h(e.database,{readOnly:e.readOnly}),r=Math.min(Math.max(e.limit,1),8);try{let o=t.searchMemories(e.query,e.project,r),a=t.semanticIndexStatsForProject({project:e.project,providerId:Yt,modelId:Qt,schemaVersion:Xt});if(a.indexable_count===0||a.indexed_count===0||a.stale_count>0)return{mode:"fts",reason:a.stale_count>0?"semantic_index_stale":"semantic_index_unavailable",memories:ms(o.length>0?o:t.recentMemories(e.project,r),e.query)};let n=t.listCurrentSemanticIndexesForProject({project:e.project,providerId:Yt,modelId:Qt,schemaVersion:Xt,limit:1e3}),s=t.listActiveMemoriesForProject(e.project,1e3),i=new Map(s.map(d=>[d.id,d])),c=new Map(o.map(d=>[d.id,ho(e.query,`${d.summary}
762
- ${d.content}`)])),l=zl(e.query),u=n.map(d=>{let f=i.get(d.memory_id);if(!f)return null;let m=c.get(f.id)??0,E=ps(l,d.embedding);return{memory:f,ftsScore:m,semanticScore:E,score:Number((m*.55+E*.45).toFixed(6))}}).filter(d=>d!==null).filter(d=>d.ftsScore>0||d.semanticScore>0).sort((d,f)=>f.score-d.score||f.semanticScore-d.semanticScore||d.memory.id.localeCompare(f.memory.id)).slice(0,r).map((d,f)=>({...d.memory,recall:{mode:"hybrid",fts_score:d.ftsScore,semantic_score:d.semanticScore,final_rank:f+1,reason:d.ftsScore>0&&d.semanticScore>0?"fts_and_semantic":d.semanticScore>0?"semantic_neighbor":"fts_match"}}));return{mode:"hybrid",reason:"semantic_index_ready",memories:u.length>0?u:ms(o,e.query)}}finally{t.close()}}function zl(e){let r=Array.from({length:32},()=>0);for(let a of zt(e)){let n=Xl(a),s=n%32,i=n%2===0?1:-1;r[s]=(r[s]??0)+i}let o=Math.hypot(...r)||1;return r.map(a=>Number((a/o).toFixed(6)))}function ms(e,t){return e.map((r,o)=>({...r,recall:{mode:"fts",fts_score:ho(t,`${r.summary}
763
- ${r.content}`),semantic_score:0,final_rank:o+1,reason:"fts_fallback"}}))}function Xl(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return t>>>0}function tt(e,t=160){let r=e.replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-3)}...`}function rt(e){return Math.ceil(e.length/4)}function er(e,t){return e.length<=t?e:`${e.slice(0,Math.max(t-3,0))}...`}var xe=class extends Error{code="MEMORY_TRANSITION_BLOCKED";id;from;to;constructor(t){super(`Invalid memory transition for ${t.id}: ${t.from} -> ${t.to}`),this.name="MemoryTransitionError",this.id=t.id,this.from=t.from,this.to=t.to}},Yl=new Map([["candidate",new Set(["active","rejected"])],["active",new Set(["forgotten","expired"])],["superseded",new Set],["rejected",new Set],["forgotten",new Set],["expired",new Set]]);async function ye(e,t){let r=await b(e),o=await Ql(r.database,t,"candidate");return await g({home:r.home,type:"memory_proposed",details:{id:o.id,project:o.scope.project,redacted:o.sensitivity==="restricted"}}),o}async function at(e,t){return rr(e,t,"active","memory_promoted")}async function nt(e,t){return rr(e,t,"rejected","memory_rejected")}async function st(e,t){return rr(e,t,"forgotten","memory_forgotten")}async function yo(e,t){return rr(e,t,"expired","memory_expired")}async function tr(e){let t=await b(e.home),r=h(t.database),o;try{o=r.listMemories({project:e.project,status:e.status,includeForgotten:e.includeForgotten,limit:Math.min(Math.max(e.limit??100,1),1e3)})}finally{r.close()}return await g({home:t.home,type:"memory_exported",details:{project:e.project??null,status:e.status??null,includeForgotten:e.includeForgotten===!0,count:o.length}}),o}async function Ql(e,t,r){let o=H(t.content),a=new Date().toISOString(),n=tt(o.value),s={id:P("mem"),type:t.type??"note",scope:{user:"default",project:t.project},content:o.value,summary:n,source:t.source??{host:"cli",session_id:"local"},confidence:t.confidence??.9,authority:t.authority??"user_explicit",sensitivity:o.redacted?"restricted":t.sensitivity??"internal",status:r,created_at:a,expires_at:null,hash:Ee({type:t.type??"note",project:t.project,content:o.value,status:r,created_at:a})},i=h(e);try{i.insertMemory(s)}finally{i.close()}return s}async function rr(e,t,r,o){let a=await b(e),n=h(a.database),s,i;try{if(s=n.getMemory(t),s&&!_o(s.status,r))throw new xe({id:t,from:s.status,to:r});i=s?n.updateMemoryStatus(t,r):null}catch(c){throw c instanceof xe&&await Zl({home:a.home,id:c.id,from:c.from,to:c.to}),c}finally{n.close()}if(!i)throw new Error(`Memory not found: ${t}`);return await g({home:a.home,type:o,details:{id:i.id,project:i.scope.project,status:r}}),i}function _o(e,t){return Yl.get(e)?.has(t)??!1}async function Zl(e){await g({home:e.home,type:"memory_transition_blocked",result:"blocked",details:{id:e.id,from:e.from,to:e.to,code:"MEMORY_TRANSITION_BLOCKED"}})}async function it(e,t,r,o=5){let a=await b(e),n=Zt({database:a.database,query:t,project:r,limit:Math.min(Math.max(o,1),8)});return await g({home:a.home,type:"memory_searched",details:{query:t,project:r,count:n.memories.length,recall_mode:n.mode,recall_reason:n.reason}}),n.memories}async function bo(e){let t=p(e.home),r=null;try{r=h(t.database);let o=r.upsertProject({id:e.resolution.id,display_name:e.resolution.id,base_id:e.resolution.base_id,source:e.resolution.source,first_basis:fs(e.resolution),status:"active",now:e.now});return r.close(),r=null,o.inserted&&await g({home:t.home,type:"project_seen",details:{id:e.resolution.id,base_id:e.resolution.base_id,source:e.resolution.source,first_basis:fs(e.resolution)}}),{touched:!0,inserted:o.inserted,degraded:!1,warning:null}}catch(o){return{touched:!1,inserted:!1,degraded:!0,warning:`PROJECT_REGISTRY_UNAVAILABLE:${ed(o)}`}}finally{r?.close()}}function fs(e){return e.remote??e.git_root??e.cwd}function ed(e){return(e instanceof Error?e.message:String(e)).replace(/[^a-zA-Z0-9_.:-]+/g,"_").slice(0,120)}var td=/^-\s*\*\*([^:*]+):\*\*\s*(.*)$/u;function Te(e,t){let r=rd(e,t);if(r)return r;let o=e.split(/\r?\n/u);for(let a=0;a<o.length;a+=1){let s=(o[a]?.trim()??"").match(td);if(!s||s[1]?.trim()!==t)continue;let i=s[2]?.trim()??"";if(i.length>0&&!i.startsWith("_("))return i;for(let c=a+1;c<o.length;c+=1){let l=o[c]?.trim()??"";if(!l||l.startsWith("#")||l.startsWith("- **"))break;if(!l.startsWith("_("))return l}}return null}function hs(e,t=200){let r=e.split(/\r?\n/u).map(o=>o.trim()).filter(o=>o.length>0&&!o.startsWith("#")&&!o.startsWith("---")&&!o.startsWith("_")).join(" ").replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-3)}...`}function ys(e,t=1600){let r=e.split(/\r?\n/u).map(o=>o.trim()).filter(o=>o.length>0&&!o.startsWith("---")&&!o.startsWith("_")).map(o=>o.replace(/^#+\s*/u,"").replace(/^-\s*/u,"")).join(" ").replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-3)}...`}function rd(e,t){let r=`${t}:`,o=e.split(/\r?\n/u).map(a=>a.trim()).find(a=>a.startsWith(r));return o?o.slice(r.length).trim():null}async function ct(e){let t=e.readOnly?p(e.home):await b(e.home),r=await nd(t.home),o=Math.min(Math.max(e.tokensMax??r.defaultTokens,1),3e3),a=[];e.readOnly!==!0&&await Wt({cwd:e.cwd,home:t.home});let n=pe(e.cwd,t.home),s=n.id;if(e.readOnly!==!0){let I=await bo({home:t.home,resolution:n});I.warning&&a.push(I.warning)}let i=sd({explicitQuery:e.query,project:s,host:e.host,cwd:e.cwd,seed:r.memoryQuerySeed}),c=await od({database:t.database,readOnly:e.readOnly===!0,memoryQuery:i,project:s,limit:r.recallLimit,warnings:a}),l=await Ve({home:t.home,host:e.host,readyOnly:!0,limit:8,readOnly:e.readOnly}),u=await ld(t.home,e.host,e.readOnly===!0),d=await uo({home:t.home,host:e.host,query:e.query??`${je.basename(e.cwd)} ${e.host}`,limit:8,readOnly:e.readOnly}),f=await mo({home:t.home,project:s,status:"open",limit:8,readOnly:e.readOnly}),m=await X(t.home,"IDENTITY.md"),E=await X(t.home,"SOUL.md"),te=await X(t.home,"AGENTS.md"),J=await X(t.home,"USER.md"),Me=await X(t.home,"BOOTSTRAP.md"),Le=new Date().toISOString().slice(0,10),Pt=je.join(t.home,"memory","daily",`${Le}.md`);a.push(...u?[]:[`HOST_ADAPTER_UNAVAILABLE:${e.host}`,"CAPABILITY_REFRESH_STALE"],...d.warnings),!await y(je.join(t.home,"state","onboarding.complete"))&&Me.trim().length>0&&a.push("BOOTSTRAP_RITUAL_PENDING"),await y(Pt)&&a.push(`DAILY_MEMORY_AVAILABLE:${Pt}`),r.warnEmptyMemories&&c.length===0&&a.push("PROJECT_MEMORY_EMPTY");let xt={bootstrap_schema:2,identity:{name:Te(m,"Name")??"NativeSoul",mission:Te(m,"Mission")??"Provide local continuity across native coding-agent hosts.",creature:Te(m,"Creature"),role:Te(m,"Role"),vibe:Te(m,"Vibe"),emoji:Te(m,"Emoji")},soul_summary:hs(E||"Continuity, clarity, and safe local-first operation.",500),agents_operating_summary:ys(te||"Load NativeSoul context before continuity-sensitive work. Use MCP when available and CLI fallback when needed."),tool_hints:id(),user:{preferences_summary:cd(J)},project:{id:s,cwd:je.resolve(e.cwd),state:"local-bootstrap"},commitments:f.map(I=>({id:I.id,status:I.status,summary:I.summary,due_at:I.due_at,ttl_expires_at:I.ttl_expires_at})),relevant_memories:c.map(I=>({id:I.id,summary:I.summary,scope:I.scope})),capabilities:l.map(I=>({uid:I.uid,host:I.host,ready:I.ready,source:I.source})),capability_cards:d.cards,policy:{mode:"safe",approval_required:["external_write","destructive","identity_policy_change"]},warnings:a},R=dd(xt,o),ha=rt(JSON.stringify(R)),hi={...R,context_budget:{tokens_used:ha,tokens_max:o}};return e.readOnly||await g({home:t.home,type:"bootstrap_created",details:{host:e.host,cwd:je.resolve(e.cwd),project:s,tokens:ha}}),hi}async function od(e){if(!await y(e.database))return e.warnings.push("BOOTSTRAP_DATABASE_MISSING"),[];let t=null;try{t=h(e.database,{readOnly:e.readOnly});let r=Zt({database:e.database,query:e.memoryQuery,project:e.project,limit:e.limit,readOnly:e.readOnly}).memories;return r.length===0?t.recentMemories(e.project,e.limit):r}catch(r){return e.warnings.push(`BOOTSTRAP_DATABASE_UNAVAILABLE:${ad(r)}`),[]}finally{t?.close()}}function ad(e){return(e instanceof Error?e.message:String(e)).replace(/[^a-zA-Z0-9_.:-]+/g,"_").slice(0,120)}async function nd(e){let t=await X(e,"config.yaml"),r=t.match(/^\s*default_tokens:\s*(\d+)\s*$/mu),o=t.match(/^\s*(?:bootstrap_recall_limit|recall_limit):\s*(\d+)\s*$/mu),a=t.match(/^\s*memory_query_seed:\s*["']?(.+?)["']?\s*$/mu),n=t.match(/^\s*warn_empty_memories:\s*(true|false)\s*$/imu),s=r?.[1]?Number(r[1]):1900,i=o?.[1]?Number(o[1]):5;return{defaultTokens:Number.isFinite(s)?s:1900,recallLimit:Number.isFinite(i)?Math.min(Math.max(i,1),8):5,memoryQuerySeed:a?.[1]?.trim()||null,warnEmptyMemories:n?.[1]?.toLowerCase()==="true"}}function sd(e){return[e.explicitQuery,e.project,e.host,je.basename(je.resolve(e.cwd)),e.seed].filter(t=>typeof t=="string"&&t.trim().length>0).join(" ")}function id(){return[{tool:"life_bootstrap",use_when:"Start a new session or refresh NativeSoul identity, project context, memories, and capability cards."},{tool:"life_recall",use_when:"Search local memories for project-specific continuity before making assumptions."},{tool:"life_remember_propose",use_when:"Propose durable memory from user-approved facts, outcomes, or preferences."},{tool:"life_onboarding_status",use_when:"Check whether onboarding is pending before drafting or applying identity files."}]}function cd(e){let t=e.trim();return t.length===0?"No curated user preferences yet.":t.length<=160?t:`${t.slice(0,157)}...`}async function ld(e,t,r=!1){let o=await Ve({home:e,host:t,includeShared:!1,limit:20,readOnly:r});if(t==="codex"&&!o.some(i=>i.source.startsWith("codex app server ")))return!1;let a=o[0]?.last_seen_at;if(!a)return!1;let n=Date.parse(a);if(!Number.isFinite(n))return!1;let s=1440*60*1e3;return Date.now()-n<=s}function dd(e,t){let r=[e,_e(e,1200,420,150),_e(e,900,320,130),_e(e,650,240,110),_e(e,420,180,90),_e(e,240,120,80),vo(_e(e,240,120,80),8,8),vo(_e(e,240,120,80),5,5),vo(_e(e,240,120,80),3,3)];return r.find(o=>rt(JSON.stringify(o))<=t)??r[r.length-1]??e}function vo(e,t,r){return{...e,capabilities:e.capabilities.slice(0,t),capability_cards:e.capability_cards.slice(0,r),relevant_memories:e.relevant_memories.slice(0,t),commitments:e.commitments.slice(0,t)}}function _e(e,t,r,o){return{...e,soul_summary:er(e.soul_summary,r),agents_operating_summary:er(e.agents_operating_summary,t),user:{...e.user,preferences_summary:er(e.user.preferences_summary,o)}}}import{existsSync as Ko}from"node:fs";import zs from"node:path";import{mkdir as cy,readFile as ud,writeFile as ly}from"node:fs/promises";import _s from"node:path";var Ro={heartbeat_enabled:!0,scheduler_host:"auto-native-supported",heartbeat_cadence:"daily",memory_candidates:!0,memory_candidate_policy:"candidate",auto_promotion:!1,promotion_policy:"explicit_approval",recall_auto_trigger_keywords:["como combinamos","como decidimos","o que combinamos","decisao anterior","decis\xE3o anterior","prior decision","previous decision","remember","lembr","memoria","mem\xF3ria","contexto anterior","last time"],recall_auto_trigger_denylist:["lint","format","typecheck","test","build"],candidate_auto_promotion_threshold:.6,recall_auto_trigger:!1,standing_order_templates:[]};async function bs(e,t){let r=await Be(e),o=await y(lt(e));return{phase:t?"identity_pending":r&&o?"active":"pending",configured:r!==null,complete_marker_present:o,existing_profile:r,available_profiles:["quickstart","advanced"],quickstart_defaults:Ro,apply_defaults:{dry_run:!0,user_confirmed:!1,reset:!1}}}function pd(e){return _s.join(e,"state","activation-profile.json")}function lt(e){return _s.join(e,"state","activation.complete")}async function Be(e){try{let t=JSON.parse(await ud(pd(e),"utf8"));return md(t)?t:null}catch{return null}}function md(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return(t.profile==="quickstart"||t.profile==="advanced")&&typeof t.heartbeat_enabled=="boolean"&&(typeof t.scheduler_host=="string"||t.scheduler_host===null)&&typeof t.heartbeat_cadence=="string"&&typeof t.memory_candidates=="boolean"&&(t.memory_candidate_policy==="candidate"||t.memory_candidate_policy==="off")&&typeof t.auto_promotion=="boolean"&&(t.promotion_policy==="manual"||t.promotion_policy==="explicit_approval")&&Array.isArray(t.recall_auto_trigger_keywords)&&t.recall_auto_trigger_keywords.every(r=>typeof r=="string")&&Array.isArray(t.recall_auto_trigger_denylist)&&t.recall_auto_trigger_denylist.every(r=>typeof r=="string")&&typeof t.candidate_auto_promotion_threshold=="number"&&Number.isFinite(t.candidate_auto_promotion_threshold)&&t.candidate_auto_promotion_threshold>=0&&t.candidate_auto_promotion_threshold<=1&&typeof t.recall_auto_trigger=="boolean"&&Array.isArray(t.standing_order_templates)&&t.standing_order_templates.every(r=>typeof r=="string")&&typeof t.updated_at=="string"}function So(e){let t={bootstrap:gd(e),mcp:fd(e),plugins_hooks:hd(e),heartbeat:yd(e),recall_auto_trigger:_d(e),memory_candidate_hooks:bd(e),memory_promotion_policy:vd(e),cross_host_verification:Rd(e)},r=Object.values(t),o=Sd(r),a=r.flatMap(s=>s.plan_actions),n=kd(e.profile,o,r);return{schema_version:1,home:e.home,target_root:e.targetRoot,host:e.host,profile:e.profile,overall_status:o,components:t,plan:a,summary:n}}function vs(e){return So(e).summary}function gd(e){return e.onboardingComplete&&e.activationComplete&&e.profile?x("bootstrap","active","Identity onboarding and activation marker are present.",{onboarding_complete:!0,activation_complete:!0}):x("bootstrap",e.onboardingComplete?"approval_required":"not_configured",e.onboardingComplete?"Activation profile still needs explicit approval.":"Identity onboarding is not complete.",{onboarding_complete:e.onboardingComplete,activation_complete:e.activationComplete},[Ce("activation-profile","bootstrap","approval_required","Write activation profile and completion marker.",`${e.home}/state/activation-profile.json`,!0,"17.1 activation apply is explicit-approval only.")])}function fd(e){let t=e.hosts.filter(r=>r.mcp_registration.configured);if(t.length>0){let r=t.some(o=>o.mcp_registration.issues.length>0);return x("mcp",r?"degraded":"active",r?"MCP is configured but doctor reported warnings.":"MCP registration is configured.",{configured_hosts:t.map(G),checked_hosts:e.hosts.map(G)})}return x("mcp","not_configured","No MCP registration was detected for the selected host scope.",{checked_hosts:e.hosts.map(G)},[Ce("mcp-registration","mcp","not_configured","Install MCP registration for selected hosts.",`nativesoul mcp install --host ${e.host} --apply`,!0,"MCP registration changes host config files.")])}function hd(e){let t=e.hosts.filter(o=>o.plugin.enabled||o.plugin.hook_registered);if(t.length>0){let o=t.some(a=>a.provider_parity.hooks==="official-fallback");return x("plugins_hooks",o?"degraded":"active",o?"Plugin/hooks are available through fallback support.":"Native plugin or hook support is active.",{enabled_hosts:t.map(G),hook_modes:Object.fromEntries(e.hosts.map(a=>[G(a),a.provider_parity.hooks]))})}let r=e.hosts.length>0&&e.hosts.every(o=>o.plugin.package_kind==="unsupported-native");return x("plugins_hooks",r?"blocked_by_host":"not_configured",r?"Selected hosts do not expose a native plugin path.":"No plugin or hook registration was detected.",{checked_hosts:e.hosts.map(G)},[Ce("plugin-install","plugins_hooks",r?"blocked_by_host":"not_configured","Install NativeSoul plugin/hook package where the host supports it.",`nativesoul install --host ${e.host} --apply`,!0,"Host plugin/hook setup modifies host-specific config.")])}function yd(e){if(!e.profile||!e.profile.heartbeat_enabled)return x("heartbeat","not_configured","Heartbeat is not enabled in the activation profile.",{profile_present:e.profile!==null});let t=e.hosts.filter(r=>r.full_native_evidence.blocked_by_host);return t.length>0?x("heartbeat","blocked_by_host","At least one selected host lacks native scheduler support.",{blocked_hosts:t.map(G),heartbeat_modes:Object.fromEntries(e.hosts.map(r=>[G(r),r.provider_parity.heartbeat]))},[Ce("heartbeat-scheduler","heartbeat","blocked_by_host","Choose a native scheduler-capable host or keep external fallback explicit.",`nativesoul schedule reconcile --host ${e.host} --mode leader --apply`,!0,"Scheduler writes must remain explicit and host-aware.")]):e.hosts.some(r=>r.provider_parity.heartbeat==="native")?x("heartbeat","active","Heartbeat has native scheduler support in the selected scope.",{native_hosts:e.hosts.filter(r=>r.provider_parity.heartbeat==="native").map(G)}):e.hosts.some(r=>r.provider_parity.heartbeat==="official-fallback")?x("heartbeat","degraded","Heartbeat is available only through fallback scheduling in the selected scope.",{fallback_hosts:e.hosts.filter(r=>r.provider_parity.heartbeat==="official-fallback").map(G)}):x("heartbeat","approval_required","Heartbeat profile is enabled, but no scheduler desired state is active yet.",{checked_hosts:e.hosts.map(G)},[Ce("heartbeat-enable","heartbeat","approval_required","Create/reconcile recurring heartbeat schedule.",`nativesoul schedule reconcile --host ${e.host} --mode leader --apply`,!0,"Recurring automation requires explicit approval.")])}function _d(e){return e.profile?e.profile.recall_auto_trigger?x("recall_auto_trigger","active","Automatic recall trigger is enabled in the activation profile.",{keywords:e.profile.recall_auto_trigger_keywords,denylist:e.profile.recall_auto_trigger_denylist,auto_promotion_threshold:e.profile.candidate_auto_promotion_threshold}):x("recall_auto_trigger","approval_required","Automatic recall trigger is intentionally disabled until explicit approval.",{recall_auto_trigger:!1},[Ce("recall-auto-trigger","recall_auto_trigger","approval_required","Set recall_auto_trigger=true in activation profile.","state/activation-profile.json:recall_auto_trigger",!0,"Prompt injection into host sessions must be explicitly approved.")]):x("recall_auto_trigger","not_configured","No activation profile is present.",{})}function bd(e){if(!e.profile||!e.profile.memory_candidates)return x("memory_candidate_hooks","not_configured","Memory candidate hooks are not enabled in the activation profile.",{});let t=e.hosts.every(r=>r.provider_parity.hooks==="unsupported-native");return x("memory_candidate_hooks",t?"degraded":"active",t?"Memory candidates are enabled, but hooks are not native on every selected host.":"Memory candidate capture is enabled with candidate-only policy.",{memory_candidate_policy:e.profile.memory_candidate_policy,hook_modes:Object.fromEntries(e.hosts.map(r=>[G(r),r.provider_parity.hooks]))})}function vd(e){return e.profile?e.profile.auto_promotion?x("memory_promotion_policy","active","Automatic promotion is enabled by activation policy.",{promotion_policy:e.profile.promotion_policy,candidate_auto_promotion_threshold:e.profile.candidate_auto_promotion_threshold,sensitive_auto_promotion_allowed:!1}):x("memory_promotion_policy","approval_required","Memory promotion requires explicit approval.",{auto_promotion:!1,promotion_policy:e.profile.promotion_policy}):x("memory_promotion_policy","not_configured","No activation profile is present.",{})}function Rd(e){let t=new Set(e.hosts.map(o=>o.host)).size,r=e.hosts.reduce((o,a)=>o+a.cross_host_inventory_summary.ready_other_hosts,0);return t>1&&e.hosts.every(o=>o.status==="ready")?x("cross_host_verification","active","Multiple selected hosts were verified by deep doctor.",{host_count:t,ready_other_hosts:r}):x("cross_host_verification",r>0?"degraded":"approval_required","Cross-host verification needs an all-host deep doctor pass before full activation claims.",{host_count:t,ready_other_hosts:r},[Ce("cross-host-verify","cross_host_verification","approval_required","Run all-host deep verification.","nativesoul doctor --deep --all-hosts --json",!1,"Verification is read-only but must be run against every host.")])}function x(e,t,r,o,a=[]){return{key:e,status:t,summary:r,evidence:o,plan_actions:a}}function Ce(e,t,r,o,a,n,s){return{id:e,component:t,status:r,action:o,target:a,dry_run:!0,requires_user_confirmed:n,reason:s}}function Sd(e){let t=e.map(r=>r.status);return t.includes("blocked_by_host")?"blocked_by_host":t.includes("degraded")?"degraded":t.includes("approval_required")?"approval_required":t.includes("not_configured")?"not_configured":"active"}function kd(e,t,r){return{overall_status:t,profile:e?.profile??null,active:dt(r,"active"),not_configured:dt(r,"not_configured"),approval_required:dt(r,"approval_required"),blocked_by_host:dt(r,"blocked_by_host"),degraded:dt(r,"degraded"),full_native_claimed:!1}}function dt(e,t){return e.filter(r=>r.status===t).length}function G(e){return e.surface==="default"?e.host:`${e.host}:${e.surface}`}import{existsSync as wd}from"node:fs";import Ad from"node:path";async function ko(e){let t=p(e),r=[],o=["AGENTS.md","SOUL.md","IDENTITY.md","USER.md","POLICY.md","MEMORY.md","HEARTBEAT.md","config.yaml"];for(let n of o)await y(Ad.join(t.home,n))||r.push({code:"MISSING_HUMAN_FILE",severity:"warn",message:`${n} is missing`,remediation:"Run nativesoul init"});if(!wd(t.database))return r.push({code:"MISSING_DATABASE",severity:"error",message:"SQLite state database is missing",remediation:"Run nativesoul init"}),{home:t.home,healthy:!1,integrity:"missing",issues:r};let a=(()=>{let n=h(t.database,{readOnly:!0});try{return n.integrityCheck()}finally{n.close()}})();a!=="ok"&&r.push({code:"SQLITE_INTEGRITY",severity:"error",message:`SQLite integrity check returned ${a}`,remediation:"Restore from backup or rebuild the workspace"}),r.push(...Ed(t.home,t.database));try{await g({home:t.home,type:"doctor_completed",details:{integrity:a,issueCount:r.length}})}catch{}return{home:t.home,healthy:r.every(n=>n.severity!=="error"),integrity:a,issues:r}}function Ed(e,t){let r=pe(process.cwd(),e),o=h(t,{readOnly:!0});try{let a=new Set(o.listMemories({limit:200,includeForgotten:!0}).map(n=>n.scope.project).filter(n=>n!==r.id));return a.size===0?[]:[{code:"PROJECT_ID_RECONCILE_AVAILABLE",severity:"info",message:`Found ${a.size} memory project id(s) different from normalized current project ${r.id}.`,remediation:"Review with nativesoul memory export --project <old-id>; a future reconcile command will migrate aliases after approval."}]}finally{o.close()}}import Z from"node:os";import N from"node:path";function Rs(e){switch(e){case"grok":return"Agents.md";case"codex":return"AGENTS.md";case"claude":return"CLAUDE.md";case"antigravity":case"gemini":return"GEMINI.md"}}function Ss(e){return e==="claude"?".claude.json":e==="gemini"?"settings.json":e==="antigravity"?"mcp_config.json":"mcp.json"}function or(e,t){if(t==null||t==="default")return e==="claude"?"claude-code":"default";if(e!=="claude")throw new Error(`--surface ${t} is only supported for --host claude`);return t}function ut(e,t){return t&&t!=="default"?[or(e,t)]:e==="claude"?["claude-code","claude-desktop"]:["default"]}function pt(e,t){return t==="default"?e:t}function ks(e){switch(e){case"codex":return N.join(Z.homedir(),".codex","AGENTS.md");case"claude":return N.join(Z.homedir(),".claude","CLAUDE.md");case"grok":return N.join(Z.homedir(),".grok","Agents.md");case"antigravity":case"gemini":return N.join(Z.homedir(),".gemini","GEMINI.md")}}function ar(e){switch(e){case"codex":return N.join(Z.homedir(),".codex","mcp.json");case"claude":return N.join(Z.homedir(),".claude.json");case"grok":return N.join(Z.homedir(),".grok","mcp.json");case"antigravity":return N.join(Z.homedir(),".gemini","antigravity-cli","mcp_config.json");case"gemini":return N.join(Z.homedir(),".gemini","settings.json")}}function ws(){return As({platform:process.platform,home:Z.homedir(),env:process.env})}function As(e){let t=e.platform==="win32"?N.win32:N.posix;if(e.platform==="darwin")return t.join(e.home,"Library","Application Support","Claude","claude_desktop_config.json");if(e.platform==="win32"){let o=e.env?.APPDATA&&e.env.APPDATA.trim().length>0?e.env.APPDATA:t.join(e.home,"AppData","Roaming");return t.join(o,"Claude","claude_desktop_config.json")}let r=e.env?.XDG_CONFIG_HOME&&e.env.XDG_CONFIG_HOME.trim().length>0?e.env.XDG_CONFIG_HOME:t.join(e.home,".config");return t.join(r,"Claude","claude_desktop_config.json")}function Es(e,t){if(e!=="claude")return null;if(!t)return N.join(Z.homedir(),".claude","mcp.json");let r=N.resolve(t),o=N.dirname(r);return N.basename(o)==="claude"?N.join(o,"mcp.json"):N.join(o,".claude","mcp.json")}import{mkdir as Ps,rename as Pd,writeFile as Ts}from"node:fs/promises";import W from"node:path";var xd=["entity","soul","human","collaboration","continuity"],Td=["SOUL.md","POLICY.md"],js=new Set(["IDENTITY.md","SOUL.md","USER.md","AGENTS.md"]),Je=64*1024,jd="<!-- nativesoul:start v1 -->",xs="<!-- nativesoul:end -->",Cd={"IDENTITY.md":{writable:!0,requires_user_confirmed:!1,required_fields:["Name","Creature","Role","Vibe","Emoji","Mission"],field_format:"- **Field:** value (Markdown list)",merge_strategy:"replace",max_bytes:Je},"SOUL.md":{writable:!0,requires_user_confirmed:!0,required_sections:["Core truths","Boundaries","Vibe","Continuity"],field_format:"Prose Markdown sections \u2014 not template slot-fill",merge_strategy:"replace",max_bytes:Je},"USER.md":{writable:!0,requires_user_confirmed:!1,required_fields:["Name","What to call them","Timezone","Languages"],field_format:"- **Field:** value (Markdown list)",merge_strategy:"replace",max_bytes:Je},"AGENTS.md":{writable:!0,requires_user_confirmed:!1,required_sections:["Session start","Safety"],field_format:"Operating instructions in Markdown",merge_strategy:"merge_managed_block",max_bytes:Je},"POLICY.md":{writable:!1,requires_user_confirmed:!1,field_format:"Use policy propose-change after onboarding",merge_strategy:"replace",max_bytes:0}};async function wo(e){let t=await b(e),o=(await X(t.home,"BOOTSTRAP.md")).trim().length>0;return{ritual_pending:o,files_present:{soul:await y(W.join(t.home,"SOUL.md")),identity:await y(W.join(t.home,"IDENTITY.md")),user:await y(W.join(t.home,"USER.md")),agents:await y(W.join(t.home,"AGENTS.md")),bootstrap:await y(W.join(t.home,"BOOTSTRAP.md"))},protected_targets:[...Td],writable_files:[...js],interview_themes:[...xd],instruction_doc:"llm-install.txt",apply_defaults:{dry_run:!0,user_confirmed:!1},file_generation_rules:Cd,activation:await bs(t.home,o)}}async function Ao(e){let t=await b(e.home),r=e.dry_run!==!1,o=e.user_confirmed===!0,a=[],n=[];for(let[s,i]of Object.entries(e.files)){let c=s.trim(),l=c.toUpperCase();if(l==="POLICY.MD"){a.push({file:c,action:"rejected",before_hash:null,after_hash:null,warning:"POLICY_VIOLATION: POLICY.md requires proposal flow"});continue}if(!js.has(c)){a.push({file:c,action:"rejected",before_hash:null,after_hash:null,warning:`UNSUPPORTED_FILE: ${c}`});continue}if(l==="SOUL.MD"&&!o){a.push({file:c,action:"rejected",before_hash:null,after_hash:null,warning:"POLICY_VIOLATION: SOUL.md requires user_confirmed: true"});continue}let u=typeof i=="string"?i:"";if(Buffer.byteLength(u,"utf8")>Je){a.push({file:c,action:"rejected",before_hash:null,after_hash:null,warning:`FILE_TOO_LARGE: ${c} exceeds ${Je} bytes`});continue}let d=W.join(t.home,c),f=await X(t.home,c),m=c==="AGENTS.md"?Id(f,u):u,E=f.length>0?U(f):null,te=U(m);if(E===te){a.push({file:c,action:"noop",before_hash:E,after_hash:te});continue}let J=f.length===0?"create":"update";a.push({file:c,action:J,before_hash:E,after_hash:te}),r||await Ts(d,m,{encoding:"utf8",mode:384})}return!r&&e.config_patch?.hosts?.length&&n.push(`CONFIG_PATCH_NOT_APPLIED_V1: hosts=${e.config_patch.hosts.join(",")}`),r||await g({home:t.home,type:"onboarding.applied",details:{user_confirmed:o,files:a.map(s=>({file:s.file,action:s.action}))}}),{dry_run:r,applied:!r,user_confirmed:o,files:a,warnings:n}}async function Eo(e){let t=p(e?.home),r=W.join(t.home,"BOOTSTRAP.md");if(!await y(r))return{already_complete:!0,archived_bootstrap:!1,archive_path:null};let o=e?.archive!==!1,a=null;if(o){let s=W.join(t.home,"memory","archive");await Ps(s,{recursive:!0,mode:448});let i=new Date().toISOString().replace(/[:.]/gu,"-");a=W.join(s,`bootstrap-${i}.md`),await Pd(r,a)}else{let{rm:s}=await import("node:fs/promises");await s(r,{force:!0})}let n=W.join(t.home,"state","onboarding.complete");return await Ps(W.join(t.home,"state"),{recursive:!0,mode:448}),await Ts(n,`${new Date().toISOString()}
764
- `,{encoding:"utf8",mode:384}),await g({home:t.home,type:"onboarding.completed",details:{archived:o,archive_path:a}}),{already_complete:!1,archived_bootstrap:o,archive_path:a}}function nr(e){return W.join(e,"state","onboarding.complete")}function Id(e,t){let r=t.trim();if(!e.trim())return`${r}
765
- `;if(e.includes(r))return e;let o=Od(e);if(o){let n=o.after.trimEnd(),s=n.length>0?`${n}
822
+ `}var Tc=["memory/daily","memory/projects","memory/archive","commitments","standing-orders","capabilities/cards","generated","state","logs","backups","proposals"],jc=$t;function Rs(e){return se.resolve(e??process.env.NATIVESOUL_HOME??se.join(Ic.homedir(),".nativesoul"))}function p(e){let t=Rs(e);return{home:t,database:se.join(t,"state","nativesoul.sqlite"),auditLog:se.join(t,"logs","audit.jsonl")}}async function y(e){try{return await xc(e,Pc.F_OK),!0}catch{return!1}}async function _(e){let t=p(e),r=[],o=[],n=[];ks(t.home)||(await vs(t.home,{recursive:!0,mode:448}),r.push(t.home));for(let i of Tc){let c=se.join(t.home,i);ks(c)||(await vs(c,{recursive:!0,mode:448}),r.push(c))}let s=await y(se.join(t.home,"state","onboarding.complete"));for(let[i,c]of Object.entries(jc)){if(i==="BOOTSTRAP.md"&&s)continue;let l=se.join(t.home,i);if(await y(l)){n.push(l);continue}try{await eo(l,c,{encoding:"utf8",mode:384,flag:"wx"}),o.push(l)}catch(u){if(Cc(u)){n.push(l);continue}throw u}}let a=await Nc(t.home);return o.push(...a.createdFiles),n.push(...a.preservedFiles),{home:t.home,database:t.database,createdDirectories:r,createdFiles:o,preservedFiles:n}}function Cc(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}async function Nc(e){let t=[],r=[],o=new Date().toISOString().slice(0,10),n=se.join(e,"memory","daily",`${o}.md`);await y(n)?r.push(n):(await eo(n,bs(o),{encoding:"utf8",mode:384,flag:"wx"}),t.push(n));let s=se.join(e,"standing-orders","example.yaml");return await y(s)?r.push(s):(await eo(s,_s,{encoding:"utf8",mode:384,flag:"wx"}),t.push(s)),{createdFiles:t,preservedFiles:r}}async function z(e,t){let r=se.join(e,t);return await y(r)?Ac(r,"utf8"):""}async function m(e){let t=p(e.home),r=new Date().toISOString(),o=ro(C(e.details??{}),t.home),n={id:A("evt"),type:e.type,actor:e.actor??"cli",origin:e.origin??"nativesoul",result:e.result??"ok",details:o,created_at:r,hash:Te({type:e.type,actor:e.actor??"cli",origin:e.origin??"nativesoul",result:e.result??"ok",details:o,created_at:r})},s=f(t.database);try{s.insertEvent(n)}finally{s.close()}return await Mc(Dc.dirname(t.auditLog),{recursive:!0,mode:448}),await Oc(t.auditLog,`${JSON.stringify(n)}
823
+ `,{encoding:"utf8",mode:384}),n}function ro(e,t){if(typeof e=="string")return Hc(e,t);if(Array.isArray(e))return e.map(r=>ro(r,t));if(e&&typeof e=="object"){let r={};for(let[o,n]of Object.entries(e))r[o]=ro(n,t);return r}return e}function Hc(e,t){return[[new RegExp(to(t),"gu"),"[REDACTED_NATIVESOUL_HOME]"],[new RegExp(to(process.cwd()),"gu"),"[REDACTED_WORKSPACE]"],[new RegExp(to(Lc.homedir()),"gu"),"[REDACTED_USER_HOME]"],[/\/Users\/[A-Za-z0-9._-]+/gu,"[REDACTED_USER_HOME]"],[/\/home\/[A-Za-z0-9._-]+/gu,"[REDACTED_USER_HOME]"],[/[A-Z]:[\\/]+Users[\\/]+[A-Za-z0-9._-]+/gu,"[REDACTED_USER_HOME]"]].reduce((o,[n,s])=>o.replace(n,s),e)}function to(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}import Oe from"node:path";import{mkdir as Xh,readdir as fd,readFile as hd,writeFile as zh}from"node:fs/promises";import{existsSync as Qh}from"node:fs";import Ta from"node:path";je();W();ue();W();import{readdir as Gc}from"node:fs/promises";import K from"node:path";var Y="antigravity",Xc="~/.gemini/GEMINI.md",zc="~/.antigravity",no="official:antigravity-plugin-config:v1",Ps="official:antigravity-hooks-config:v1",xs="official:antigravity-mcp-config:v1",Is="official:antigravity-command-config:v1",Yc="official:antigravity-context-config:v1",Qc="official:antigravity-features:v1",Zc=[{uid:"antigravity:plugins",nativeKind:"plugins",normalizedKind:"package",relativePath:"plugins"}];function so(){let e=process.env.NATIVESOUL_ANTIGRAVITY_INVENTORY_ROOT?.trim();return e?K.resolve(e):v(zc)}function el(){let e=so();return{root:e,globalInstruction:process.env.NATIVESOUL_ANTIGRAVITY_INVENTORY_ROOT?.trim()?K.join(e,"GEMINI.md"):v(Xc)}}async function Ts(){let e=[],t=el();await b(t.globalInstruction)&&e.push({uid:"antigravity:global-gemini-md",host:Y,nativeKind:"global_context",normalizedKind:"instruction",source:t.globalInstruction,schemaHash:Yc}),await tl(t.root,e),await rl(t.root,e);for(let r of Zc){let o=K.join(t.root,r.relativePath);await I(o)&&e.push({uid:r.uid,host:Y,nativeKind:r.nativeKind,normalizedKind:r.normalizedKind,source:o,schemaHash:no})}return e}async function tl(e,t){let r=K.join(e,"plugin.json"),o=K.join(e,"nativesoul-package.json"),n=K.join(e,"hooks.json"),s=K.join(e,"mcp_config.json"),[a,i,c,l]=await Promise.all([H(r),H(o),H(n),H(s)]);if(a){let u=R(a,["name","id"])??"unknown";t.push({uid:`antigravity:plugin:${E(u)}`,host:Y,nativeKind:"plugin",normalizedKind:"extension",source:r,schemaHash:no})}if(i){let u=R(i,["name","id"])??"unknown";t.push({uid:`antigravity:package:${E(u)}`,host:Y,nativeKind:"native_plugin_package",normalizedKind:"package",source:o,schemaHash:no});let d=w(i.nativeSoul)?i.nativeSoul:{};for(let x of Ut(d.commands))t.push({uid:`antigravity:command:${E(x)}`,host:Y,nativeKind:"command",normalizedKind:"command",source:`${o}:nativeSoul.commands.${x}`,schemaHash:Is});let h=w(d.mcpServer)?d.mcpServer:null,g=R(h,["name"]);g&&t.push({uid:`antigravity:mcp:${E(g)}`,host:Y,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${o}:nativeSoul.mcpServer.${g}`,schemaHash:xs})}if(c){t.push({uid:"antigravity:hooks:manifest",host:Y,nativeKind:"hooks",normalizedKind:"lifecycle_hooks",source:n,schemaHash:Ps});let u=w(c.hooks)?c.hooks:{};for(let d of Object.keys(u))t.push({uid:`antigravity:hook:${E(d)}`,host:Y,nativeKind:"hook",normalizedKind:"lifecycle_hook",source:`${n}:hooks.${d}`,schemaHash:Ps})}if(l)for(let u of ye(l.mcpServers))t.push({uid:`antigravity:mcp:${E(u)}`,host:Y,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${s}:mcpServers.${u}`,schemaHash:xs});await ol(K.join(e,"commands"),t)}async function rl(e,t){let r=K.join(e,"features-evidence.json"),o=await H(r);if(!o)return;let n=["scheduled_tasks","cron_schedules","background_agents","subagents","skills","mcps","json_hooks"];for(let s of n)o[s]===!0&&t.push({uid:`antigravity:feature:${s.replace(/_/gu,"-")}`,host:Y,nativeKind:"product_feature",normalizedKind:"feature_evidence",source:`${r}:${s}`,schemaHash:Qc})}async function ol(e,t){if(!await I(e))return;let r=await Gc(e,{withFileTypes:!0});for(let o of r){if(!o.isFile()||K.extname(o.name)!==".md")continue;let n=K.basename(o.name,".md");t.push({uid:`antigravity:command:${E(n,{allowSlash:!0})}`,host:Y,nativeKind:"command",normalizedKind:"command",source:K.join(e,o.name),schemaHash:Is})}}W();ue();import Vt from"node:path";async function js(e){let t=await nl(e);if(!t)return null;let r=await H(t);return r?{product_features_verified:r.product_features_verified===!0,write_contract_verified:r.write_contract_verified===!0,native_id:typeof r.native_id=="string"&&r.native_id.trim().length>0?r.native_id.trim():void 0,enabled:typeof r.enabled=="boolean"?r.enabled:void 0,updated_at:typeof r.updated_at=="string"?r.updated_at:void 0,contract:w(r.contract)?{schedule:R(r.contract,["schedule"])??void 0,status:R(r.contract,["status"])??void 0,cancel:R(r.contract,["cancel"])??void 0,list:R(r.contract,["list"])??void 0,project_binding:R(r.contract,["project_binding"])??void 0}:void 0}:null}async function nl(e){let t=process.env.NATIVESOUL_ANTIGRAVITY_SCHEDULER_MANIFEST?.trim();if(t)return t;let r=process.env.NATIVESOUL_ANTIGRAVITY_INVENTORY_ROOT?.trim();if(r)return Vt.join(Vt.resolve(r),"scheduler-proof.json");let o=e??v("~/.antigravity"),n=[Vt.join(o,"scheduler-proof.json"),Vt.join(o,"native-scheduler-proof.json")];for(let s of n)if(await b(s))return s;return null}function Cs(e){if(!e)return!1;let t=Date.parse(e);return Number.isFinite(t)?Date.now()-t>10080*60*1e3:!0}var Be="antigravity",ao="~/.gemini/GEMINI.md",io=class{async detect(){let t=v(ao),r=so(),[o,n,s]=await Promise.all([b(t),I(r),le("agy")]);return{host:Be,detected:n||s!==null,path:n?r:s??(o?t:void 0),capabilities:{installed:n||s!==null,enabled:n,active:!1,authenticated:!1,healthy:s!==null||n,allowed:!0,ready:!1}}}async install(t){return{status:"unsupported",reason:"Antigravity direct adapter writes are disabled; use the install orchestrator to install the NativeSoul native hook plugin, MCP registration, and managed block."}}async uninstall(t){return{status:"unsupported",reason:"Antigravity direct adapter uninstall is disabled; use the uninstall orchestrator for reversible package removal."}}async coldScan(){return Ts()}async hotProbe(){let t=await this.coldScan();return{host:Be,checkedAt:new Date().toISOString(),capabilities:t.map(r=>({...r,installed:!0,enabled:!0,active:r.nativeKind==="global_context",authenticated:!1,healthy:!0,allowed:!0,ready:r.schemaHash?.startsWith("official:")===!0}))}}async bootstrap(){return{tier:"A",mechanism:"hook",supported:!0}}async reload(t){return{status:"unsupported",reason:"Antigravity reload is host-driven; use the installed NativeSoul command package or restart the host if needed."}}async update(t){return{status:"unsupported",reason:"Antigravity package updates are handled by the NativeSoul install orchestrator."}}async scheduleReconcile(t){let r=await js(t.hostConfigRoot);if(!r?.product_features_verified)return{status:"unsupported",reason:"Antigravity Scheduled Tasks product-level evidence was not detected; no hidden cron fallback installed."};if(!r.write_contract_verified)return{status:"unsupported",reason:"Antigravity product-level Scheduled Tasks are documented, but scheduler write/list/cancel/status contract proof is missing; keep full-native blocked_by_host:scheduler_write_contract_missing."};if(!r.contract?.schedule||!r.contract.status||!r.contract.cancel||!r.contract.list)return{status:"unsupported",reason:"Antigravity scheduler proof is missing one or more required commands: schedule, status, cancel, list."};if(r.enabled===!1)return{status:"degraded",reason:"Antigravity scheduler contract was detected, but the NativeSoul scheduled task is disabled."};if(!r.native_id)return{status:"degraded",reason:"Antigravity scheduler contract was detected, but no native task id mapping was returned."};if(Cs(r.updated_at))return{status:"degraded",reason:"Antigravity scheduler proof is stale; re-run scheduler status/list before claiming full-native."};let o=t.apply?"reconciled":"reconcile planned";return{status:"ok",nativeId:r.native_id,message:`Antigravity Scheduled Task ${o}: ${r.native_id}`}}async doctor(){let t=await this.detect(),r=v(ao),o=await M(r),n=[];return t.detected||n.push({code:"ANTIGRAVITY_NOT_DETECTED",severity:"warn",message:"No Antigravity CLI or ~/.antigravity directory was detected. A shared ~/.gemini/GEMINI.md alone is not treated as Antigravity readiness.",remediation:"Install Antigravity CLI or review `nativesoul adapters managed-block --host antigravity --json`."}),o&&!$(o,Be)&&n.push({code:"ANTIGRAVITY_MANAGED_BLOCK_MISSING",severity:"info",message:"GEMINI.md exists but has no NativeSoul managed block for Antigravity.",remediation:"Review `nativesoul adapters managed-block --host antigravity --json`."}),n}async managedBlockPreview(){let t=v(ao),r=await M(t);return{host:Be,targetPath:t,startMarker:"<!-- nativesoul:antigravity:start v1 -->",endMarker:"<!-- nativesoul:antigravity:end -->",content:ae(Be),wouldCreate:r===null,wouldUpdate:r!==null&&!$(r,Be)}}};function Ns(){return new io}je();ue();W();import We from"node:path";import{readFile as Zs}from"node:fs/promises";ue();import{readFile as Ks}from"node:fs/promises";import hl from"node:path";var Xs="life:heartbeat";function zs(e){if(!e||typeof e!="object"||Array.isArray(e))return{kind:"unknown",mode:"leader",apply:!1,skill:Xs};let t=e;return{kind:typeof t.kind=="string"?t.kind:"unknown",mode:typeof t.mode=="string"?t.mode:"leader",apply:t.apply===!0,skill:vl(t),surface:Gs(t.surface)??Gs(w(t.desired)?t.desired.surface:void 0)}}async function Ys(e={}){let t=process.env.NATIVESOUL_CLAUDE_SCHEDULED_TASKS_FIXTURES;if(t)try{return qs(await Ks(hl.join(t,"scheduled-tasks.json"),"utf8"))}catch{return null}let r=process.env.NATIVESOUL_CLAUDE_SCHEDULED_TASKS_MANIFEST;if(r)try{return qs(await Ks(r,"utf8"))}catch{return null}if(process.env.NATIVESOUL_CLAUDE_SCHEDULED_TASKS_SUPPORTED==="1")return{supported:!0,native_id:process.env.NATIVESOUL_CLAUDE_SCHEDULED_TASKS_NATIVE_ID,surface:"claude-desktop",scheduler_kind:"unknown",creation_surface:"unknown",evidence_source:"env"};let{discoverClaudeScheduledTasksManifest:o}=await Promise.resolve().then(()=>(Js(),Ws));return o({apply:e.apply,surface:e.surface,hostConfigRoot:e.hostConfigRoot})}function Qs(e,t){return!e||e==="default"||!t?!0:e===t}function qs(e){let t=de(e);if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,o=yl(r.surface),n=_l(r.scheduler_kind??r.kind);return{supported:r.supported===!0,native_id:typeof r.native_id=="string"&&r.native_id.length>0?r.native_id:void 0,surface:o??(n==="cloud_routine"?"cloud":"claude-desktop"),scheduler_kind:n,creation_surface:bl(r.creation_surface),evidence_source:typeof r.evidence_source=="string"&&r.evidence_source.trim().length>0?r.evidence_source.trim():void 0,enabled:typeof r.enabled=="boolean"?r.enabled:void 0}}function Gs(e){return e==="default"||e==="claude-code"||e==="claude-desktop"?e:void 0}function yl(e){return e==="claude-code"||e==="claude-desktop"||e==="cloud"?e:void 0}function _l(e){return e==="local_scheduled_task"||e==="cloud_routine"||e==="ui_only"?e:"unknown"}function bl(e){return e==="official_machine_readable"||e==="ui_only"||e==="unknown"?e:void 0}function vl(e){return w(e.desired)&&typeof e.desired.skill=="string"&&e.desired.skill.trim().length>0?e.desired.skill.trim():Xs}var J="claude",Bt="~/.claude/CLAUDE.md",ea="CLAUDE.md",ta=".claude/CLAUDE.md",ra="life:heartbeat",na="official:claude-cli-hot-scan:v1",lo=class{async detect(){let t=v(Bt),r=We.resolve(ea),o=We.resolve(ta),[n,s,a,i]=await Promise.all([b(t),b(r),b(o),Ft("claude",["--version"])]);return{host:J,detected:n||s||a||i!==null,version:i??void 0,path:n?t:s?r:a?o:void 0,capabilities:{installed:n||s||a||i!==null,enabled:n||s||a,active:s||a,authenticated:!1,healthy:i!==null||n||s||a,allowed:!0,ready:!1}}}async install(t){return{status:"unsupported",reason:"Claude install writes are not implemented in M2.1; use managed-block preview first."}}async uninstall(t){return{status:"unsupported",reason:"Claude uninstall writes are not implemented in M2.1."}}async coldScan(){let t=v(Bt),r=We.resolve(ea),o=We.resolve(ta),n=[];return await b(t)&&n.push({uid:"claude:global-claude-md",host:J,nativeKind:"global_context",normalizedKind:"instruction",source:t}),await b(r)&&n.push({uid:"claude:project-claude-md",host:J,nativeKind:"project_context",normalizedKind:"instruction",source:r}),await b(o)&&n.push({uid:"claude:project-dot-claude-md",host:J,nativeKind:"project_context",normalizedKind:"instruction",source:o}),n}async hotProbe(t){let r=new Date().toISOString(),o=process.env.NATIVESOUL_CLAUDE_HOT_SCAN_FIXTURES?.trim();if(o){let c=await kl(o,r);if(c.status==="ready")return c}let[n,s]=await Promise.all([oo("claude",["mcp","list","--json"],1200),oo("claude",["plugin","list","--json"],1200)]),a=[],i=[];return n.status==="ok"?i.push(...sa(n.stdout)):a.push(oa("CLAUDE_HOT_SCAN_JSON_UNSUPPORTED","claude mcp list --json",n.stderr)),s.status==="ok"?i.push(...aa(s.stdout)):a.push(oa("CLAUDE_HOT_SCAN_JSON_UNSUPPORTED","claude plugin list --json",s.stderr)),{host:J,checkedAt:r,status:a.length===0?"ready":"degraded",warnings:a.map(c=>c.code),remediation:a.length===0?void 0:"Upgrade Claude Code CLI if JSON hot-scan commands are unavailable.",capabilities:i.map(c=>({...c,installed:c.installed??!0,enabled:c.enabled??!0,active:c.active??!0,authenticated:c.authenticated??!1,healthy:c.healthy??!0,allowed:!0,ready:c.ready??!1})),diagnostics:a}}async bootstrap(){return{tier:"B",mechanism:"global-instruction",supported:!0}}async reload(t){return{status:"unsupported",reason:"Claude reload is deferred until plugin lifecycle integration story."}}async update(t){return{status:"unsupported",reason:"Claude update is deferred until plugin lifecycle integration story."}}async scheduleReconcile(t){let r=zs(t),o=await Ys({apply:r.apply,surface:r.surface,hostConfigRoot:t.hostConfigRoot});return o?.supported?r.kind!=="heartbeat"?{status:"unsupported",reason:"Claude adapter only supports NativeSoul heartbeat scheduled tasks."}:r.skill!==ra?{status:"error",code:"CLAUDE_HEARTBEAT_SKILL_MISMATCH",message:`Claude heartbeat Scheduled Task must invoke ${ra}.`}:o.scheduler_kind==="cloud_routine"||o.surface==="cloud"?{status:"unsupported",reason:"Claude cloud routines were detected, but they are out-of-scope for local native Scheduled Tasks evidence."}:o.scheduler_kind==="ui_only"||o.creation_surface==="ui_only"?{status:"unsupported",reason:"Claude task creation is UI-only for this surface; keep status blocked_by_host until a documented machine-readable surface returns a local task id."}:Qs(r.surface,o.surface)?o.enabled===!1?{status:"degraded",reason:"Claude Scheduled Tasks support was detected, but the NativeSoul task is disabled."}:o.native_id?{status:"ok",nativeId:o.native_id,message:r.apply?`Claude Scheduled Task reconciled: ${o.native_id}`:`Claude Scheduled Task reconcile planned: ${o.native_id}`}:{status:"degraded",reason:"Claude Scheduled Tasks support was detected, but no native task id mapping was returned."}:{status:"unsupported",reason:`Claude Scheduled Tasks evidence is for ${o.surface??"unknown"} and does not satisfy ${r.surface}.`}:{status:"unsupported",reason:"Claude Scheduled Tasks native interface was not detected; no cron fallback installed."}}async doctor(){let t=await this.detect(),r=v(Bt),o=await M(r),n=[];return t.detected||n.push({code:"CLAUDE_NOT_DETECTED",severity:"warn",message:"No Claude CLI or CLAUDE.md instruction file was detected.",remediation:"Install Claude Code or create a managed block preview before enabling writes."}),o&&!$(o,J)&&n.push({code:"CLAUDE_MANAGED_BLOCK_MISSING",severity:"info",message:"Claude global CLAUDE.md exists but has no NativeSoul managed block.",remediation:"Review `nativesoul adapters managed-block --host claude --json`."}),n}async managedBlockPreview(){let t=v(Bt),r=await M(t);return{host:J,targetPath:t,startMarker:"<!-- nativesoul:claude:start v1 -->",endMarker:"<!-- nativesoul:claude:end -->",content:ae(J),wouldCreate:r===null,wouldUpdate:r!==null&&!$(r,J)}}};async function kl(e,t){try{let[r,o]=await Promise.all([Zs(We.join(e,"mcp-list.json"),"utf8"),Zs(We.join(e,"plugin-list.json"),"utf8")]),n=[...sa(r),...aa(o)];return{host:J,checkedAt:t,status:"ready",warnings:[],capabilities:n.map(s=>({...s,installed:s.installed??!0,enabled:s.enabled??!0,active:s.active??!0,authenticated:s.authenticated??!1,healthy:s.healthy??!0,allowed:!0,ready:s.ready??!1}))}}catch{return{host:J,checkedAt:t,status:"degraded",warnings:["CLAUDE_HOT_SCAN_FIXTURES_UNAVAILABLE"],remediation:"Set NATIVESOUL_CLAUDE_HOT_SCAN_FIXTURES to a directory containing mcp-list.json and plugin-list.json.",capabilities:[],diagnostics:[{code:"CLAUDE_HOT_SCAN_FIXTURES_UNAVAILABLE",severity:"warn",message:"Claude hot-scan fixtures were configured but could not be read.",remediation:"Verify NATIVESOUL_CLAUDE_HOT_SCAN_FIXTURES points at mcp-list.json and plugin-list.json."}]}}}function sa(e){let t=de(e);return _e(t,["servers","mcps","items"]).flatMap(r=>{let o=R(r,["name","id","server","server_name"]);if(!o)return[];let n=R(r,["status","state"]),s=n!=="disabled",a=n==="connected"||n==="ready"||n==="active"||n==="ok"||n==="authenticated";return[{uid:`claude:mcp:${E(o)}`,host:J,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`claude mcp list:${o}`,schemaHash:na,enabled:s,active:s,authenticated:U(r,["authenticated"])??a,healthy:s,ready:ia(n)}]})}function aa(e){let t=de(e);return _e(t,["plugins","items"]).flatMap(r=>{let o=R(r,["id","plugin","package"])??R(r,["name"]);if(!o)return[];let n=R(r,["status","state"]),s=U(r,["enabled"])??n!=="disabled",a=U(r,["installed"])??!0;return[{uid:`claude:plugin:${Rl(o)}`,host:J,nativeKind:"plugin",normalizedKind:"extension",source:`claude plugin list --json:${o}`,schemaHash:na,installed:a,enabled:s,active:s,authenticated:U(r,["authenticated"])??s,healthy:a,ready:s&&(n===null||ia(n)||U(r,["enabled"])===!0)}]})}function oa(e,t,r){let o=Sl(r.trim()||"command unavailable or unsupported by installed Claude CLI");return{code:e,severity:"warn",message:`${t} did not return supported JSON output: ${o}`,remediation:"Upgrade Claude Code CLI or run `claude mcp list --json` / `claude plugin list --json` manually to confirm support."}}function ia(e){return e==="ready"||e==="enabled"||e==="active"||e==="ok"||e==="authenticated"||e==="connected"}function Rl(e){return E(e,{allowSlash:!0})}function Sl(e){return e.replace(/\b[A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|API[_-]?KEY)[A-Z0-9_]*\s*=\s*\S+/giu,"[REDACTED_SECRET]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/gu,"[REDACTED_SECRET]")}function ca(){return new lo}je();ue();W();import go from"node:path";var V="codex",Jt="~/.codex/AGENTS.md",pa="AGENTS.md",Ul=1e3,ma="life:heartbeat",qt="official:codex-app-server:v1",fo=class{async detect(){let t=v(Jt),r=go.resolve(pa),[o,n,s]=await Promise.all([b(t),b(r),le("codex")]);return{host:V,detected:o||n||s!==null,path:o?t:n?r:s??void 0,capabilities:{installed:o||n||s!==null,enabled:o||n,active:n,authenticated:!1,healthy:s!==null||o||n,allowed:!0,ready:!1}}}async install(t){return{status:"unsupported",reason:"Codex install writes are not implemented in M2.1; use managed-block preview first."}}async uninstall(t){return{status:"unsupported",reason:"Codex uninstall writes are not implemented in M2.1."}}async coldScan(){let t=v(Jt),r=go.resolve(pa),o=[];return await b(t)&&o.push({uid:"codex:global-agents-md",host:V,nativeKind:"global_context",normalizedKind:"instruction",source:t}),await b(r)&&o.push({uid:"codex:project-agents-md",host:V,nativeKind:"project_context",normalizedKind:"instruction",source:r}),o}async hotProbe(t){let r=new Date().toISOString(),o=ql(t);if(o){let i=await mo(o,r);if(i.status==="ready")return i}let n=process.env.NATIVESOUL_CODEX_APP_SERVER_FIXTURES?.trim();if(n){let i=await mo(Xl(n),r);if(i.status==="ready")return i}let s=Gl(t);if(s){let i=await mo(zl(s),r);if(i.status==="ready")return i}let a=await this.coldScan();return{host:V,checkedAt:r,status:"degraded",warnings:["CODEX_APP_SERVER_UNAVAILABLE"],remediation:"Start Codex App Server and set NATIVESOUL_CODEX_APP_SERVER_URL before running `nativesoul adapters hot-scan --host codex`.",capabilities:a.map(i=>({...i,source:`codex app server fallback config scan:${i.source}`,installed:!0,enabled:!0,active:i.uid.includes("project"),authenticated:!1,healthy:!0,allowed:!0,ready:!1})),diagnostics:[{code:"CODEX_APP_SERVER_UNAVAILABLE",severity:"warn",message:"Codex App Server inventory endpoint is not configured or did not respond with supported JSON.",remediation:"Set NATIVESOUL_CODEX_APP_SERVER_URL to a reachable Codex App Server endpoint."}]}}async bootstrap(){return{tier:"B",mechanism:"global-instruction",supported:!0}}async reload(t){return{status:"unsupported",reason:"Codex reload is deferred until App Server integration story."}}async update(t){return{status:"unsupported",reason:"Codex update is deferred until marketplace/App Server integration story."}}async scheduleReconcile(t){let{discoverCodexAutomationsManifest:r}=await Promise.resolve().then(()=>(ua(),da)),o=await r({apply:t.apply,hostConfigRoot:t.hostConfigRoot});return o?.supported?t.kind!=="heartbeat"?{status:"unsupported",reason:"Codex adapter only supports NativeSoul heartbeat automations."}:t.desired.skill!==ma?{status:"error",code:"CODEX_HEARTBEAT_SKILL_MISMATCH",message:`Codex heartbeat Automation must invoke ${ma}.`}:o.native_id?{status:"ok",nativeId:o.native_id,message:t.apply?`Codex Automation reconciled: ${o.native_id}`:`Codex Automation reconcile planned: ${o.native_id}`}:{status:"degraded",reason:"Codex Automations support was detected, but no native automation id mapping was returned."}:{status:"unsupported",reason:"Codex Automations native interface was not detected; no cron fallback installed."}}async doctor(){let t=await this.detect(),r=v(Jt),o=await M(r),n=[];return t.detected||n.push({code:"CODEX_NOT_DETECTED",severity:"warn",message:"No Codex CLI or AGENTS.md instruction file was detected.",remediation:"Install Codex or create a managed block preview before enabling writes."}),o&&!$(o,V)&&n.push({code:"CODEX_MANAGED_BLOCK_MISSING",severity:"info",message:"Codex global AGENTS.md exists but has no NativeSoul managed block.",remediation:"Review `nativesoul adapters managed-block --host codex --json`."}),n}async managedBlockPreview(){let t=v(Jt),r=await M(t);return{host:V,targetPath:t,startMarker:"<!-- nativesoul:codex:start v1 -->",endMarker:"<!-- nativesoul:codex:end -->",content:ae(V),wouldCreate:r===null,wouldUpdate:r!==null&&!$(r,V)}}};async function mo(e,t){let[r,o,n,s]=await Promise.all([Kt(e,"mcpServerStatus/list"),Kt(e,"plugin/list"),Kt(e,"skills/list"),Kt(e,"app/list")]);if([r,o,n,s].some(c=>c===null))return{host:V,checkedAt:t,status:"degraded",warnings:["CODEX_APP_SERVER_UNAVAILABLE"],remediation:"Ensure Codex App Server is running and supports mcpServerStatus/list, plugin/list, skills/list, and app/list.",capabilities:[],diagnostics:[{code:"CODEX_APP_SERVER_UNAVAILABLE",severity:"warn",message:"Codex App Server did not return supported JSON inventory for all required methods.",remediation:"Check NATIVESOUL_CODEX_APP_SERVER_URL and Codex App Server version."}]};let i=[...Bl(r),...Wl(o),...Jl(n),...Kl(s)];return{host:V,checkedAt:t,status:"ready",warnings:[],capabilities:i.map(c=>({...c,installed:c.installed??!0,enabled:c.enabled??!0,active:c.active??!0,authenticated:c.authenticated??!1,healthy:c.healthy??!0,allowed:!0,ready:c.ready??!1}))}}async function Kt(e,t){try{return await e.call(t)}catch{return null}}async function Vl(e,t){let r=new AbortController,o=setTimeout(()=>r.abort(),Ul);try{let n=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:t,method:t,params:{}}),signal:r.signal});if(!n.ok)return null;let s=await n.json();return w(s)&&"error"in s?null:w(s)&&"result"in s?s.result:s}catch{return null}finally{clearTimeout(o)}}function Bl(e){return _e(e,["servers","mcpServers","items"]).flatMap(t=>{let r=R(t,["id","name","server","server_name"]);if(!r)return[];let o=R(t,["status","state"]),n=Gt(t,o);return[{uid:`codex:mcp:${E(r)}`,host:V,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`codex app server mcpServerStatus/list:${r}`,schemaHash:qt,...n}]})}function Wl(e){return _e(e,["plugins","items"]).flatMap(t=>{let r=R(t,["id","plugin","package"])??R(t,["name"]);if(!r)return[];let o=R(t,["status","state"]),n=Gt(t,o);return[{uid:`codex:plugin:${ho(r)}`,host:V,nativeKind:"plugin",normalizedKind:"extension",source:`codex app server plugin/list:${r}`,schemaHash:qt,...n}]})}function Jl(e){return _e(e,["skills","items"]).flatMap(t=>{let r=R(t,["id","name","path"]);if(!r)return[];let o=R(t,["status","state"]),n=Gt(t,o);return[{uid:`codex:skill:${ho(r)}`,host:V,nativeKind:"skill",normalizedKind:"skill",source:`codex app server skills/list:${r}`,schemaHash:qt,...n}]})}function Kl(e){return _e(e,["apps","items"]).flatMap(t=>{let r=R(t,["id","name","app"]);if(!r)return[];let o=R(t,["status","state"]),n=Gt(t,o);return[{uid:`codex:app:${ho(r)}`,host:V,nativeKind:"app_server_app",normalizedKind:"app",source:`codex app server app/list:${r}`,schemaHash:qt,...n}]})}function Gt(e,t){let r=U(e,["installed"])??!0,o=t==="disabled"||t==="unavailable",n=t==="error"||t==="unhealthy",s=U(e,["enabled"])??!o,a=U(e,["active"])??s,i=U(e,["healthy"])??(!o&&!n),c=U(e,["authenticated"])??U(e,["auth"])??!1,l=U(e,["ready"])??(r&&s&&a&&i);return{installed:r,enabled:s,active:a,authenticated:c,healthy:i,ready:l}}function ql(e){if(w(e)){let t=e.appServer;if(w(t)&&typeof t.call=="function")return{call:r=>Promise.resolve(t.call(r))}}return null}function Gl(e){if(w(e)){let t=e.appServerUrl;if(typeof t=="string"&&t.trim().length>0)return t.trim()}return process.env.NATIVESOUL_CODEX_APP_SERVER_URL?.trim()||process.env.CODEX_APP_SERVER_URL?.trim()||null}function Xl(e){return{async call(t){try{let{readFile:r}=await import("node:fs/promises"),o=t.replace(/\//gu,"-");return JSON.parse(await r(go.join(e,`${o}.json`),"utf8"))}catch(r){let o=r instanceof Error?r.message:"unknown error";throw new Error(`Codex App Server fixture unavailable for ${t}: ${o}`,{cause:r})}}}}function zl(e){return{call:t=>Vl(e,t)}}function ho(e){return E(e,{allowSlash:!0})}function ga(){return new fo}je();ue();W();import{readdir as ha}from"node:fs/promises";import Q from"node:path";var F="gemini",_o="~/.gemini/GEMINI.md",Yl="~/.gemini/extensions",Ql="~/.gemini/settings.json",nt="official:gemini-extension-config:v1",yo="official:gemini-settings-config:v1",Zl="official:gemini-memory-config:v1",bo=class{async detect(){let t=fa(),r=t.globalInstruction,o=t.extensionsDirectory,[n,s,a]=await Promise.all([b(r),I(o),Ft("gemini",["--version"])]);return{host:F,detected:n||s||a!==null,version:a??void 0,path:n?r:s?o:void 0,capabilities:{installed:n||s||a!==null,enabled:n||s,active:n,authenticated:!1,healthy:a!==null||n||s,allowed:!0,ready:!1}}}async install(t){return{status:"unsupported",reason:"Gemini direct adapter writes are disabled; use the install orchestrator to install the NativeSoul Gemini extension, MCP registration, and managed block."}}async uninstall(t){return{status:"unsupported",reason:"Gemini direct adapter uninstall is disabled; use the uninstall orchestrator for reversible package removal."}}async coldScan(){let t=[],r=fa(),o=r.globalInstruction;await b(o)&&t.push({uid:"gemini:global-gemini-md",host:F,nativeKind:"global_context",normalizedKind:"memory",source:o,schemaHash:Zl}),await ed(r.settingsFile,t);let n=r.extensionsDirectory;if(await I(n)){t.push({uid:"gemini:extensions",host:F,nativeKind:"extensions",normalizedKind:"package",source:n,schemaHash:nt});let s=await ha(n,{withFileTypes:!0});for(let a of s)a.isDirectory()&&await td(Q.join(n,a.name),a.name,t)}return t}async hotProbe(){let t=await this.coldScan();return{host:F,checkedAt:new Date().toISOString(),capabilities:t.map(r=>({...r,installed:!0,enabled:!0,active:r.nativeKind==="global_context"||r.schemaHash?.startsWith("official:")===!0,authenticated:!1,healthy:!0,allowed:!0,ready:r.schemaHash?.startsWith("official:")===!0}))}}async bootstrap(){return{tier:"A",mechanism:"hook",supported:!0}}async reload(t){return{status:"unsupported",reason:"Gemini extension reload is host-driven; run /memory refresh or restart Gemini after installing NativeSoul."}}async update(t){return{status:"unsupported",reason:"Gemini package updates are handled by the NativeSoul install orchestrator."}}async scheduleReconcile(t){return{status:"unsupported",reason:"Gemini does not expose a documented native scheduler for NativeSoul; use the packaged heartbeat command manually or host-supported commands, with no hidden cron."}}async doctor(){let t=await this.detect(),r=v(_o),o=await M(r),n=[];return t.detected||n.push({code:"GEMINI_NOT_DETECTED",severity:"warn",message:"No Gemini CLI, GEMINI.md, or extensions directory was detected.",remediation:"Install Gemini CLI or review `nativesoul adapters managed-block --host gemini --json`."}),o&&!$(o,F)&&n.push({code:"GEMINI_MANAGED_BLOCK_MISSING",severity:"info",message:"GEMINI.md exists but has no NativeSoul managed block.",remediation:"Review `nativesoul adapters managed-block --host gemini --json`."}),n}async managedBlockPreview(){let t=v(_o),r=await M(t);return{host:F,targetPath:t,startMarker:"<!-- nativesoul:gemini:start v1 -->",endMarker:"<!-- nativesoul:gemini:end -->",content:ae(F),wouldCreate:r===null,wouldUpdate:r!==null&&!$(r,F)}}};function fa(){let e=process.env.NATIVESOUL_GEMINI_INVENTORY_ROOT?.trim();if(e){let t=Q.resolve(e);return{globalInstruction:Q.join(t,"GEMINI.md"),settingsFile:Q.join(t,"settings.json"),extensionsDirectory:Q.join(t,"extensions")}}return{globalInstruction:v(_o),settingsFile:v(Ql),extensionsDirectory:v(Yl)}}async function ed(e,t){let r=await H(e);if(r){t.push({uid:"gemini:settings",host:F,nativeKind:"settings",normalizedKind:"config",source:e,schemaHash:yo});for(let o of ye(r.mcpServers))t.push({uid:`gemini:mcp:${E(o)}`,host:F,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${e}:mcpServers.${o}`,schemaHash:yo});for(let o of ya(r.tools))t.push({uid:`gemini:tool:${E(o)}`,host:F,nativeKind:"tool",normalizedKind:"tool",source:`${e}:tools.${o}`,schemaHash:yo})}}async function td(e,t,r){let o=Q.join(e,"gemini-extension.json"),n=await H(o),s=R(n,["name","id"])??t;if(r.push({uid:`gemini:extension:${E(s)}`,host:F,nativeKind:"extension",normalizedKind:"package",source:n?o:e,schemaHash:n?nt:void 0}),n){for(let a of ye(n.mcpServers))r.push({uid:`gemini:mcp:${E(a)}`,host:F,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${o}:mcpServers.${a}`,schemaHash:nt});for(let a of ya(n.tools))r.push({uid:`gemini:tool:${E(a)}`,host:F,nativeKind:"tool",normalizedKind:"tool",source:`${o}:tools.${a}`,schemaHash:nt})}await rd(Q.join(e,"commands"),r)}async function rd(e,t){if(!await I(e))return;let r=await ha(e,{withFileTypes:!0});for(let o of r){if(!o.isFile()||![".toml",".md"].includes(Q.extname(o.name)))continue;let n=Q.basename(o.name,Q.extname(o.name));t.push({uid:`gemini:command:${E(n,{allowSlash:!0})}`,host:F,nativeKind:"command",normalizedKind:"command",source:Q.join(e,o.name),schemaHash:nt})}}function ya(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):ye(e)}function _a(){return new bo}je();ue();W();import{readdir as Sa}from"node:fs/promises";import j from"node:path";var T="grok",Xt="~/.grok/Agents.md",ba="AGENTS.md",va="Agents.md",ka="CLAUDE.md",od="~/.grok",vo="official:grok-plugin-config:v1",Ra="official:grok-hooks-config:v1",ko="official:grok-mcp-config:v1",wa="official:grok-command-config:v1",nd="official:grok-context-config:v1",sd=[{uid:"grok:plugins",nativeKind:"plugins",normalizedKind:"package",relativePath:"plugins"},{uid:"grok:skills",nativeKind:"skills",normalizedKind:"capability",relativePath:"skills"},{uid:"grok:hooks",nativeKind:"hooks",normalizedKind:"capability",relativePath:"hooks"},{uid:"grok:mcps",nativeKind:"mcp",normalizedKind:"capability",relativePath:"mcps"}],Ro=class{async detect(){let t=v(Xt),r=j.resolve(ba),o=j.resolve(va),n=j.resolve(ka),s=Ea(),[a,i,c,l,u,d]=await Promise.all([b(t),b(r),b(o),b(n),I(s),le("grok")]),h=i||c;return{host:T,detected:a||h||l||u||d!==null,path:a?t:c?o:i?r:l?n:d??void 0,capabilities:{installed:a||h||l||u||d!==null,enabled:a||h||l||u,active:h||l,authenticated:!1,healthy:d!==null||a||u,allowed:!0,ready:!1}}}async install(t){return{status:"unsupported",reason:"Grok direct adapter writes are disabled; use the install orchestrator to install the NativeSoul native hook plugin, MCP registration, and managed block."}}async uninstall(t){return{status:"unsupported",reason:"Grok direct adapter uninstall is disabled; use the uninstall orchestrator for reversible package removal."}}async coldScan(){let t=[],r=ad(),o=r.globalInstruction;await b(o)&&t.push({uid:"grok:global-agents-md",host:T,nativeKind:"global_context",normalizedKind:"instruction",source:o,schemaHash:nd});let n=j.resolve(ba);await b(n)&&t.push({uid:"grok:project-agents-md",host:T,nativeKind:"project_context",normalizedKind:"instruction",source:n});let s=j.resolve(va);await b(s)&&t.push({uid:"grok:project-agents-titlecase-md",host:T,nativeKind:"project_context",normalizedKind:"instruction",source:s});let a=j.resolve(ka);await b(a)&&t.push({uid:"grok:project-claude-md",host:T,nativeKind:"project_context",normalizedKind:"instruction",source:a});let i=r.root;await Aa(r.root,t),await id(i,t);for(let c of sd){let l=j.join(i,c.relativePath);await I(l)&&t.push({uid:c.uid,host:T,nativeKind:c.nativeKind,normalizedKind:c.normalizedKind,source:l,schemaHash:c.relativePath==="mcps"?ko:vo})}return ld(t)}async hotProbe(){let t=await this.coldScan();return{host:T,checkedAt:new Date().toISOString(),capabilities:t.map(r=>({...r,installed:!0,enabled:!0,active:r.uid.includes("project"),authenticated:!1,healthy:!0,allowed:!0,ready:r.schemaHash?.startsWith("official:")===!0}))}}async bootstrap(){return{tier:"A",mechanism:"hook",supported:!0}}async reload(t){return{status:"unsupported",reason:"Grok reload is host-driven; use the installed NativeSoul command package or restart the host if needed."}}async update(t){return{status:"unsupported",reason:"Grok package updates are handled by the NativeSoul install orchestrator."}}async scheduleReconcile(t){return{status:"unsupported",reason:"Grok has no documented native scheduler or recurring task surface for NativeSoul; headless grok -p, cron, GitHub Actions, systemd, and Windows Task Scheduler are external schedulers and do not satisfy full-native capability."}}async doctor(){let t=await this.detect(),r=v(Xt),o=await M(r),n=[];return t.detected||n.push({code:"GROK_NOT_DETECTED",severity:"warn",message:"No Grok CLI, ~/.grok directory, or project instruction file was detected.",remediation:"Install Grok Build or review `nativesoul adapters managed-block --host grok --json`."}),o&&!$(o,T)&&n.push({code:"GROK_MANAGED_BLOCK_MISSING",severity:"info",message:"Grok global Agents.md exists but has no NativeSoul managed block.",remediation:"Review `nativesoul adapters managed-block --host grok --json`."}),n}async managedBlockPreview(){let t=v(Xt),r=await M(t);return{host:T,targetPath:t,startMarker:"<!-- nativesoul:grok:start v1 -->",endMarker:"<!-- nativesoul:grok:end -->",content:ae(T),wouldCreate:r===null,wouldUpdate:r!==null&&!$(r,T)}}};function Ea(){let e=process.env.NATIVESOUL_GROK_INVENTORY_ROOT?.trim();return e?j.resolve(e):v(od)}function ad(){let e=Ea();return{root:e,globalInstruction:process.env.NATIVESOUL_GROK_INVENTORY_ROOT?.trim()?j.join(e,"Agents.md"):v(Xt)}}async function Aa(e,t){let r=j.join(e,"plugin.json"),o=j.join(e,"nativesoul-package.json"),n=j.join(e,"hooks","hooks.json"),s=j.join(e,".mcp.json"),[a,i,c,l]=await Promise.all([H(r),H(o),H(n),H(s)]);if(a){let u=R(a,["name","id"])??"unknown";t.push({uid:`grok:plugin:${E(u)}`,host:T,nativeKind:"plugin",normalizedKind:"extension",source:r,schemaHash:vo})}if(i){let u=R(i,["name","id"])??"unknown";t.push({uid:`grok:package:${E(u)}`,host:T,nativeKind:"native_plugin_package",normalizedKind:"package",source:o,schemaHash:vo});let d=w(i.nativeSoul)?i.nativeSoul:{};for(let x of Ut(d.commands))t.push({uid:`grok:command:${E(x)}`,host:T,nativeKind:"command",normalizedKind:"command",source:`${o}:nativeSoul.commands.${x}`,schemaHash:wa});let h=w(d.mcpServer)?d.mcpServer:null,g=R(h,["name"]);g&&t.push({uid:`grok:mcp:${E(g)}`,host:T,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${o}:nativeSoul.mcpServer.${g}`,schemaHash:ko})}if(c){t.push({uid:"grok:hooks:manifest",host:T,nativeKind:"hooks",normalizedKind:"lifecycle_hooks",source:n,schemaHash:Ra});let u=w(c.hooks)?c.hooks:{};for(let d of Object.keys(u))t.push({uid:`grok:hook:${E(d)}`,host:T,nativeKind:"hook",normalizedKind:"lifecycle_hook",source:`${n}:hooks.${d}`,schemaHash:Ra})}if(l)for(let u of ye(l.mcpServers))t.push({uid:`grok:mcp:${E(u)}`,host:T,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${s}:mcpServers.${u}`,schemaHash:ko});await cd(j.join(e,"commands"),t)}async function id(e,t){let r=j.join(e,"plugins");if(!await I(r))return;let o=await Sa(r,{withFileTypes:!0});for(let n of o)n.isDirectory()&&await Aa(j.join(r,n.name),t)}async function cd(e,t){if(!await I(e))return;let r=await Sa(e,{withFileTypes:!0});for(let o of r){if(!o.isFile()||j.extname(o.name)!==".md")continue;let n=j.basename(o.name,".md");t.push({uid:`grok:command:${E(n,{allowSlash:!0})}`,host:T,nativeKind:"command",normalizedKind:"command",source:j.join(e,o.name),schemaHash:wa})}}function ld(e){let t=new Set,r=[];for(let o of e)t.has(o.uid)||(t.add(o.uid),r.push(o));return r}function Pa(){return new Ro}import{mkdir as xh,readFile as dd,rm as Ih,writeFile as Th}from"node:fs/promises";import{existsSync as ud}from"node:fs";import Nh from"node:path";function pd(e){return{start:`<!-- nativesoul:${e}:start v1 -->`,end:`<!-- nativesoul:${e}:end -->`}}async function xa(e){let t=ud(e.targetPath),r=[];if(!t)return r.push({code:"MANAGED_BLOCK_TARGET_MISSING",severity:"warn",message:`Managed block target is missing: ${e.targetPath}`,remediation:"Run nativesoul install --host <host> --apply"}),{host:e.host,targetPath:e.targetPath,target_exists:!1,configured:!1,markers_valid:!1,issues:r};let o=await dd(e.targetPath,"utf8"),n=pd(e.host),s=o.indexOf(n.start),a=o.indexOf(n.end),i=s>=0,c=a>=0,l=i&&c&&a>s;return!i&&!c?r.push({code:"MANAGED_BLOCK_MISSING",severity:"warn",message:"NativeSoul managed block is not configured.",remediation:"Run nativesoul install --host <host> --apply"}):l||r.push({code:"MANAGED_BLOCK_MARKERS_INVALID",severity:"error",message:"NativeSoul managed block markers are incomplete or out of order.",remediation:"Fix the managed block markers or restore from a backup snapshot"}),{host:e.host,targetPath:e.targetPath,target_exists:!0,configured:l,markers_valid:l,issues:r}}var md=["codex","claude","grok","antigravity","gemini"],gd={codex:ga,claude:ca,grok:Pa,antigravity:Ns,gemini:_a};function Je(e){return e==="all"?md:[e]}function Ia(e){return Je(e)}function So(e){return gd[e]()}async function wo(e){let t=[];for(let r of Ia(e)){let o=So(r);t.push({host:r,diagnostics:await o.doctor({})})}return t}async function Ke(e){let t=e.readOnly?p(e.home):await _(e.home);if(e.readOnly&&!await y(t.database))return[];let r=f(t.database,{readOnly:e.readOnly}),o=Na(e.limit);try{return r.listCapabilities({host:e.host,readyOnly:e.readyOnly,limit:o,includeShared:e.includeShared})}finally{r.close()}}async function Eo(e){let t=await _(e.home),r=f(t.database),o=Na(e.limit);try{return r.searchCapabilities({query:e.query,host:e.host,readyOnly:e.readyOnly,limit:o,includeShared:e.includeShared})}finally{r.close()}}async function Ao(e){let t=await _(e.home),r=f(t.database);try{return r.getCapability(e.uid)}finally{r.close()}}async function Po(e){let t=e.readOnly?p(e.home):await _(e.home),r=Ta.join(t.home,"capabilities","cards"),o=[];if(!await y(r))return{cards:[],warnings:o};let n=(await fd(r)).filter(l=>l.endsWith(".json")).sort(),s=Rd(e.query??""),a=[];for(let l of n){let u=Ta.join(r,l),d;try{d=await hd(u,"utf8")}catch{o.push(`CAPABILITY_CARD_UNREADABLE:${l}`);continue}let h=_d(d);if(!h){o.push(`CAPABILITY_CARD_MALFORMED:${l}`);continue}let g=bd(h,e.host);a.push({card:g,score:vd(h,e.host,s)})}let i=Sd(e.limit),c=a.sort((l,u)=>u.score-l.score||l.card.uid.localeCompare(u.card.uid));return{cards:yd(c,i).map(l=>l.card),warnings:o}}function yd(e,t){let r=e.slice(0,t);if(t<=1||r.some(n=>n.card.alternative_host))return r;let o=e.find(n=>n.card.alternative_host);return o?[...r.slice(0,t-1),o].sort((n,s)=>s.score-n.score||n.card.uid.localeCompare(s.card.uid)):r}function _d(e){let t;try{t=JSON.parse(e)}catch{return null}if(!ja(t))return null;let r=t.readiness;return t.card_version!==1||typeof t.id!="string"||typeof t.uid!="string"||typeof t.host!="string"||typeof t.native_kind!="string"||typeof t.normalized_kind!="string"||typeof t.source!="string"||typeof t.schema_hash!="string"||!Array.isArray(t.use_when)||!Array.isArray(t.requires)||!Array.isArray(t.side_effects)||typeof t.approval!="string"||!Array.isArray(t.examples)||!kd(r)?null:t}function bd(e,t){let r=e.host!==t,o=e.host!==t&&e.host!=="all";return{id:e.id,uid:e.uid,host:e.host,ready:e.readiness.ready,source:e.source,schema_hash:e.schema_hash,use_when:st(e.use_when).slice(0,2),requires:st(e.requires).slice(0,4),approval:e.approval,alternative_host:r,available_on_other_host:o}}function vd(e,t,r){let o=Ca([e.uid,e.host,e.native_kind,e.normalized_kind,e.source,e.schema_hash,...st(e.use_when),...st(e.requires),e.approval,...st(e.examples)].join(" ")),n=r.reduce((s,a)=>s+(o.includes(a)?10:0),0);return(e.host===t?100:0)+(e.readiness.ready?5:0)+n}function st(e){return e.filter(t=>typeof t=="string")}function ja(e){return typeof e=="object"&&e!==null}function kd(e){return ja(e)?["installed","enabled","active","authenticated","healthy","allowed","ready"].every(t=>typeof e[t]=="boolean"):!1}function Rd(e){return Ca(e).split(/\s+/u).map(t=>t.trim()).filter(t=>t.length>=2)}function Ca(e){return e.toLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/gu,"")}function Na(e){return Math.min(Math.max(e??50,1),100)}function Sd(e){return Math.min(Math.max(e??5,1),8)}async function xo(e){let t=await _(e.home),r=N(e.summary).value,o=new Date,n=e.ttlSeconds?new Date(o.getTime()+Ed(e.ttlSeconds)*1e3).toISOString():null,s=C(e.source??{host:"cli",session_id:"local"}),a=f(t.database),i;try{i=a.createOpenCommitmentIfMissing({id:A("commitment"),project_id:e.project,summary:r,status:"open",due_at:e.dueAt??null,ttl_expires_at:n,source:s,created_at:o.toISOString(),updated_at:o.toISOString()},o.toISOString())}finally{a.close()}return await m({home:t.home,type:i.created?"commitment_created":"commitment_deduped",details:{id:i.commitment.id,project:i.commitment.project_id,redacted:r!==e.summary,created:i.created}}),i}async function Io(e){let t=e.readOnly?p(e.home):await _(e.home);if(e.readOnly&&!await y(t.database))return[];let r=f(t.database,{readOnly:e.readOnly}),o;try{o=r.listCommitments({project:e.project,status:e.status??(e.includeExpired?void 0:"open"),includeExpired:e.includeExpired,limit:Math.min(Math.max(e.limit??50,1),200),now:new Date().toISOString(),skipExpire:e.readOnly})}finally{r.close()}return e.readOnly||await m({home:t.home,type:"commitments_listed",details:{project:e.project??null,status:e.status??null,includeExpired:e.includeExpired===!0,count:o.length}}),o}async function To(e,t){return wd(e,t,"completed","commitment_completed")}async function wd(e,t,r,o){let n=await _(e),s=f(n.database),a;try{a=s.updateCommitmentStatus(t,r,new Date().toISOString())}finally{s.close()}if(!a)throw new Error(`Commitment not found: ${t}`);return await m({home:n.home,type:o,details:{id:a.id,project:a.project_id,status:a.status}}),a}function Ed(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),365*24*60*60):1440*60}import{createHash as Ad}from"node:crypto";import{existsSync as zt,mkdirSync as Pd,realpathSync as xd,readFileSync as Ma,writeFileSync as Id}from"node:fs";import{spawnSync as La}from"node:child_process";import ie from"node:path";function pe(e,t){let r=jo(e),o=Nd(r),n=o?Od(o):null,s=n?Oa(n):o??r,a=Md(s),i=n?"git-remote":o?"git-root":"path",c=jd(a,s),l=Td(r),u=l?Da(l):null,d=$a(t),h=[u,c,n?Oa(n):null,o,r].find(g=>g&&d[g]);if(h){let g=u??c;return{id:d[h]??g,source:"alias",cwd:r,git_root:o,remote:n,base_id:g,alias_key:h,marker_path:l}}return u?{id:u,source:"marker",cwd:r,git_root:o,remote:n,base_id:u,alias_key:null,marker_path:l}:{id:c,source:i,cwd:r,git_root:o,remote:n,base_id:c,alias_key:null,marker_path:null}}function Da(e){if(!zt(e))return null;let t=Ma(e,"utf8").trim();if(t.length===0)return null;let r=t.match(/^(?:project_id|id):\s*([a-z0-9._-]+)\s*$/imu);if(r?.[1])return r[1];let o=t.split(/\r?\n/u).map(n=>n.trim()).find(n=>n.length>0&&!n.startsWith("#"));return o?Cd(o):null}function Ha(e,t){let r=ie.join(e,".nativesoul","project");return Pd(ie.dirname(r),{recursive:!0,mode:448}),Id(r,`${t}
824
+ `,{encoding:"utf8",mode:384}),r}async function Yt(e){let t=pe(e.cwd,e.home);if(t.source!=="git-root"&&t.source!=="path")return{written:!1,marker_path:t.marker_path,base_id:t.base_id};let r=t.git_root??t.cwd,o=ie.join(r,".nativesoul","project");return zt(o)?{written:!1,marker_path:o,base_id:t.base_id}:(Ha(r,t.base_id),{written:!0,marker_path:o,base_id:t.base_id})}function Td(e){let t=jo(e);for(;;){let r=ie.join(t,".nativesoul","project");if(zt(r))return r;let o=ie.dirname(t);if(o===t)return null;t=o}}function jd(e,t){let r=Ad("sha256").update(t).digest("hex").slice(0,10);return`${Ld(e)}-${r}`}function Cd(e){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"workspace"}function jo(e){try{return xd(ie.resolve(e))}catch{return ie.resolve(e)}}function Nd(e){let t=La("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(t.status!==0)return null;let r=t.stdout.trim();return r.length>0?jo(r):null}function Od(e){let t=La("git",["-C",e,"remote","get-url","origin"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(t.status!==0)return null;let r=t.stdout.trim();return r.length>0?r:null}function Oa(e){return e.trim().replace(/^git@([^:]+):/,"https://$1/").replace(/^ssh:\/\/git@([^/]+)\//,"https://$1/").replace(/^https?:\/\/([^/]+)\//,"https://$1/").replace(/\.git$/u,"").toLowerCase()}function Md(e){let t=e.replace(/\/+$/u,"");return ie.basename(t)||"workspace"}function Ld(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"workspace"}function $a(e){if(!e)return{};let t=ie.join(ie.resolve(e),"config.yaml");if(!zt(t))return{};let r=Ma(t,"utf8"),o={},n=!1,s=!1,a="";for(let i of r.split(/\r?\n/u)){if(/^\S/u.test(i)){n=/^project:\s*$/u.test(i),s=!1;continue}let c=i.match(/^([ \t]+)aliases:\s*(?:\{\}\s*)?$/u);if(n&&c?.[1]){s=!0,a=c[1];continue}if(s){if(i.trim().length===0||i.trim().startsWith("#"))continue;let l=i.match(/^([ \t]+)(?:"([^"]+)"|'([^']+)'|([^:]+)):\s*(?:"([^"]+)"|'([^']+)'|(.+))\s*$/u);(l?.[1]??"").length<=a.length&&(s=!1);let d=l?.[2]??l?.[3]??l?.[4],h=l?.[5]??l?.[6]??l?.[7];s&&d&&h?o[d.trim()]=h.trim():/^[ \t]+\S/u.test(i)&&i.trim().length>0&&(s=!1)}}return o}import{readFile as ky,writeFile as Ry}from"node:fs/promises";import wy from"node:path";import Ly from"node:path";var Dd={minLength:1,removeStopwords:!1,normalizeDiacritics:!1};function Qt(e,t={}){let r={...Dd,...t},o=r.normalizeDiacritics?e.normalize("NFKD").replace(new RegExp("\\p{Diacritic}","gu"),""):e;return Array.from(new Set(o.toLowerCase().match(/[\p{L}\p{N}_-]+/gu)?.filter(n=>n.length>=r.minLength).filter(n=>!r.removeStopwords||!Hd.has(n))??[]))}function Fa(e,t={}){return new Set(Qt(e,t))}function Co(e,t){let r=Qt(e);if(r.length===0)return 0;let o=Fa(t),n=r.filter(s=>o.has(s)).length;return Number((n/r.length).toFixed(6))}function Ua(e,t){let r=Math.min(e.length,t.length),o=0;for(let n=0;n<r;n+=1)o+=(e[n]??0)*(t[n]??0);return Number(Math.max(o,0).toFixed(6))}var Hd=new Set(["the","and","for","with","this","that","uma","com","para","por","que","deve","esta","este","essa","isso"]);var Zt=1,er="local-hash",tr="local-hash-bow-v1";function Ba(e){let t=f(e,{readOnly:!0});try{let r=t.semanticIndexStats({providerId:er,modelId:tr,schemaVersion:Zt});return{provider_id:er,model_id:tr,schema_version:Zt,available:!0,indexable_count:r.indexable_count,indexed_count:r.indexed_count,stale_count:r.stale_count,healthy:r.stale_count===0,remediation:r.stale_count===0?null:"Run nativesoul memory index"}}finally{t.close()}}function rr(e){let t=f(e.database,{readOnly:e.readOnly}),r=Math.min(Math.max(e.limit,1),8);try{let o=t.searchMemories(e.query,e.project,r),n=t.semanticIndexStatsForProject({project:e.project,providerId:er,modelId:tr,schemaVersion:Zt});if(n.indexable_count===0||n.indexed_count===0||n.stale_count>0)return{mode:"fts",reason:n.stale_count>0?"semantic_index_stale":"semantic_index_unavailable",memories:Va(o.length>0?o:t.recentMemories(e.project,r),e.query)};let s=t.listCurrentSemanticIndexesForProject({project:e.project,providerId:er,modelId:tr,schemaVersion:Zt,limit:1e3}),a=t.listActiveMemoriesForProject(e.project,1e3),i=new Map(a.map(d=>[d.id,d])),c=new Map(o.map(d=>[d.id,Co(e.query,`${d.summary}
825
+ ${d.content}`)])),l=$d(e.query),u=s.map(d=>{let h=i.get(d.memory_id);if(!h)return null;let g=c.get(h.id)??0,x=Ua(l,d.embedding);return{memory:h,ftsScore:g,semanticScore:x,score:Number((g*.55+x*.45).toFixed(6))}}).filter(d=>d!==null).filter(d=>d.ftsScore>0||d.semanticScore>0).sort((d,h)=>h.score-d.score||h.semanticScore-d.semanticScore||d.memory.id.localeCompare(h.memory.id)).slice(0,r).map((d,h)=>({...d.memory,recall:{mode:"hybrid",fts_score:d.ftsScore,semantic_score:d.semanticScore,final_rank:h+1,reason:d.ftsScore>0&&d.semanticScore>0?"fts_and_semantic":d.semanticScore>0?"semantic_neighbor":"fts_match"}}));return{mode:"hybrid",reason:"semantic_index_ready",memories:u.length>0?u:Va(o,e.query)}}finally{t.close()}}function $d(e){let r=Array.from({length:32},()=>0);for(let n of Qt(e)){let s=Fd(n),a=s%32,i=s%2===0?1:-1;r[a]=(r[a]??0)+i}let o=Math.hypot(...r)||1;return r.map(n=>Number((n/o).toFixed(6)))}function Va(e,t){return e.map((r,o)=>({...r,recall:{mode:"fts",fts_score:Co(t,`${r.summary}
826
+ ${r.content}`),semantic_score:0,final_rank:o+1,reason:"fts_fallback"}}))}function Fd(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return t>>>0}function at(e,t=160){let r=e.replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-3)}...`}function it(e){return Math.ceil(e.length/4)}function or(e,t){return e.length<=t?e:`${e.slice(0,Math.max(t-3,0))}...`}var Ce=class extends Error{code="MEMORY_TRANSITION_BLOCKED";id;from;to;constructor(t){super(`Invalid memory transition for ${t.id}: ${t.from} -> ${t.to}`),this.name="MemoryTransitionError",this.id=t.id,this.from=t.from,this.to=t.to}},Ud=new Map([["candidate",new Set(["active","rejected"])],["active",new Set(["forgotten","expired"])],["superseded",new Set],["rejected",new Set],["forgotten",new Set],["expired",new Set]]);async function be(e,t){let r=await _(e),o=await Vd(r.database,t,"candidate");return await m({home:r.home,type:"memory_proposed",details:{id:o.id,project:o.scope.project,redacted:o.sensitivity==="restricted"}}),o}async function lt(e,t){return sr(e,t,"active","memory_promoted")}async function dt(e,t){return sr(e,t,"rejected","memory_rejected")}async function ut(e,t){return sr(e,t,"forgotten","memory_forgotten")}async function No(e,t){return sr(e,t,"expired","memory_expired")}async function nr(e){let t=await _(e.home),r=f(t.database),o;try{o=r.listMemories({project:e.project,status:e.status,includeForgotten:e.includeForgotten,limit:Math.min(Math.max(e.limit??100,1),1e3)})}finally{r.close()}return await m({home:t.home,type:"memory_exported",details:{project:e.project??null,status:e.status??null,includeForgotten:e.includeForgotten===!0,count:o.length}}),o}async function Vd(e,t,r){let o=N(t.content),n=new Date().toISOString(),s=at(o.value),a={id:A("mem"),type:t.type??"note",scope:{user:"default",project:t.project},content:o.value,summary:s,source:t.source??{host:"cli",session_id:"local"},confidence:t.confidence??.9,authority:t.authority??"user_explicit",sensitivity:o.redacted?"restricted":t.sensitivity??"internal",status:r,created_at:n,expires_at:null,hash:Te({type:t.type??"note",project:t.project,content:o.value,status:r,created_at:n})},i=f(e);try{i.insertMemory(a)}finally{i.close()}return a}async function sr(e,t,r,o){let n=await _(e),s=f(n.database),a,i;try{if(a=s.getMemory(t),a&&!Oo(a.status,r))throw new Ce({id:t,from:a.status,to:r});i=a?s.updateMemoryStatus(t,r):null}catch(c){throw c instanceof Ce&&await Bd({home:n.home,id:c.id,from:c.from,to:c.to}),c}finally{s.close()}if(!i)throw new Error(`Memory not found: ${t}`);return await m({home:n.home,type:o,details:{id:i.id,project:i.scope.project,status:r}}),i}function Oo(e,t){return Ud.get(e)?.has(t)??!1}async function Bd(e){await m({home:e.home,type:"memory_transition_blocked",result:"blocked",details:{id:e.id,from:e.from,to:e.to,code:"MEMORY_TRANSITION_BLOCKED"}})}async function pt(e,t,r,o=5){let n=await _(e),s=rr({database:n.database,query:t,project:r,limit:Math.min(Math.max(o,1),8)});return await m({home:n.home,type:"memory_searched",details:{query:t,project:r,count:s.memories.length,recall_mode:s.mode,recall_reason:s.reason}}),s.memories}async function Mo(e){let t=p(e.home),r=null;try{r=f(t.database);let o=r.upsertProject({id:e.resolution.id,display_name:e.resolution.id,base_id:e.resolution.base_id,source:e.resolution.source,first_basis:Wa(e.resolution),status:"active",now:e.now});return r.close(),r=null,o.inserted&&await m({home:t.home,type:"project_seen",details:{id:e.resolution.id,base_id:e.resolution.base_id,source:e.resolution.source,first_basis:Wa(e.resolution)}}),{touched:!0,inserted:o.inserted,degraded:!1,warning:null}}catch(o){return{touched:!1,inserted:!1,degraded:!0,warning:`PROJECT_REGISTRY_UNAVAILABLE:${Wd(o)}`}}finally{r?.close()}}function Wa(e){return e.remote??e.git_root??e.cwd}function Wd(e){return(e instanceof Error?e.message:String(e)).replace(/[^a-zA-Z0-9_.:-]+/g,"_").slice(0,120)}var Jd=/^-\s*\*\*([^:*]+):\*\*\s*(.*)$/u;function Ne(e,t){let r=Kd(e,t);if(r)return r;let o=e.split(/\r?\n/u);for(let n=0;n<o.length;n+=1){let a=(o[n]?.trim()??"").match(Jd);if(!a||a[1]?.trim()!==t)continue;let i=a[2]?.trim()??"";if(i.length>0&&!i.startsWith("_("))return i;for(let c=n+1;c<o.length;c+=1){let l=o[c]?.trim()??"";if(!l||l.startsWith("#")||l.startsWith("- **"))break;if(!l.startsWith("_("))return l}}return null}function Ja(e,t=200){let r=e.split(/\r?\n/u).map(o=>o.trim()).filter(o=>o.length>0&&!o.startsWith("#")&&!o.startsWith("---")&&!o.startsWith("_")).join(" ").replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-3)}...`}function Ka(e,t=1600){let r=e.split(/\r?\n/u).map(o=>o.trim()).filter(o=>o.length>0&&!o.startsWith("---")&&!o.startsWith("_")).map(o=>o.replace(/^#+\s*/u,"").replace(/^-\s*/u,"")).join(" ").replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-3)}...`}function Kd(e,t){let r=`${t}:`,o=e.split(/\r?\n/u).map(n=>n.trim()).find(n=>n.startsWith(r));return o?o.slice(r.length).trim():null}async function mt(e){let t=e.readOnly?p(e.home):await _(e.home),r=await Xd(t.home),o=Math.min(Math.max(e.tokensMax??r.defaultTokens,1),3e3),n=[];e.readOnly!==!0&&await Yt({cwd:e.cwd,home:t.home});let s=pe(e.cwd,t.home),a=s.id;if(e.readOnly!==!0){let O=await Mo({home:t.home,resolution:s});O.warning&&n.push(O.warning)}let i=zd({explicitQuery:e.query,project:a,host:e.host,cwd:e.cwd,seed:r.memoryQuerySeed}),c=await qd({database:t.database,readOnly:e.readOnly===!0,memoryQuery:i,project:a,limit:r.recallLimit,warnings:n}),l=await Ke({home:t.home,host:e.host,readyOnly:!0,limit:8,readOnly:e.readOnly}),u=await Zd(t.home,e.host,e.readOnly===!0),d=await Po({home:t.home,host:e.host,query:e.query??`${Oe.basename(e.cwd)} ${e.host}`,limit:8,readOnly:e.readOnly}),h=await Io({home:t.home,project:a,status:"open",limit:8,readOnly:e.readOnly}),g=await z(t.home,"IDENTITY.md"),x=await z(t.home,"SOUL.md"),te=await z(t.home,"AGENTS.md"),he=await z(t.home,"USER.md"),re=await z(t.home,"BOOTSTRAP.md"),$e=new Date().toISOString().slice(0,10),Ee=Oe.join(t.home,"memory","daily",`${$e}.md`);n.push(...u?[]:[`HOST_ADAPTER_UNAVAILABLE:${e.host}`,"CAPABILITY_REFRESH_STALE"],...d.warnings),!await y(Oe.join(t.home,"state","onboarding.complete"))&&re.trim().length>0&&n.push("BOOTSTRAP_RITUAL_PENDING"),await y(Ee)&&n.push(`DAILY_MEMORY_AVAILABLE:${Ee}`),r.warnEmptyMemories&&c.length===0&&n.push("PROJECT_MEMORY_EMPTY");let jt={bootstrap_schema:2,identity:{name:Ne(g,"Name")??"NativeSoul",mission:Ne(g,"Mission")??"Provide local continuity across native coding-agent hosts.",creature:Ne(g,"Creature"),role:Ne(g,"Role"),vibe:Ne(g,"Vibe"),emoji:Ne(g,"Emoji")},soul_summary:Ja(x||"Continuity, clarity, and safe local-first operation.",500),agents_operating_summary:Ka(te||"Load NativeSoul context before continuity-sensitive work. Use MCP when available and CLI fallback when needed."),tool_hints:Yd(),user:{preferences_summary:Qd(he)},project:{id:a,cwd:Oe.resolve(e.cwd),state:"local-bootstrap"},commitments:h.map(O=>({id:O.id,status:O.status,summary:O.summary,due_at:O.due_at,ttl_expires_at:O.ttl_expires_at})),relevant_memories:c.map(O=>({id:O.id,summary:O.summary,scope:O.scope})),capabilities:l.map(O=>({uid:O.uid,host:O.host,ready:O.ready,source:O.source})),capability_cards:d.cards,policy:{mode:"safe",approval_required:["external_write","destructive","identity_policy_change"]},warnings:n},k=eu(jt,o),Fn=it(JSON.stringify(k)),oc={...k,context_budget:{tokens_used:Fn,tokens_max:o}};return e.readOnly||await m({home:t.home,type:"bootstrap_created",details:{host:e.host,cwd:Oe.resolve(e.cwd),project:a,tokens:Fn}}),oc}async function qd(e){if(!await y(e.database))return e.warnings.push("BOOTSTRAP_DATABASE_MISSING"),[];let t=null;try{t=f(e.database,{readOnly:e.readOnly});let r=rr({database:e.database,query:e.memoryQuery,project:e.project,limit:e.limit,readOnly:e.readOnly}).memories;return r.length===0?t.recentMemories(e.project,e.limit):r}catch(r){return e.warnings.push(`BOOTSTRAP_DATABASE_UNAVAILABLE:${Gd(r)}`),[]}finally{t?.close()}}function Gd(e){return(e instanceof Error?e.message:String(e)).replace(/[^a-zA-Z0-9_.:-]+/g,"_").slice(0,120)}async function Xd(e){let t=await z(e,"config.yaml"),r=t.match(/^\s*default_tokens:\s*(\d+)\s*$/mu),o=t.match(/^\s*(?:bootstrap_recall_limit|recall_limit):\s*(\d+)\s*$/mu),n=t.match(/^\s*memory_query_seed:\s*["']?(.+?)["']?\s*$/mu),s=t.match(/^\s*warn_empty_memories:\s*(true|false)\s*$/imu),a=r?.[1]?Number(r[1]):1900,i=o?.[1]?Number(o[1]):5;return{defaultTokens:Number.isFinite(a)?a:1900,recallLimit:Number.isFinite(i)?Math.min(Math.max(i,1),8):5,memoryQuerySeed:n?.[1]?.trim()||null,warnEmptyMemories:s?.[1]?.toLowerCase()==="true"}}function zd(e){return[e.explicitQuery,e.project,e.host,Oe.basename(Oe.resolve(e.cwd)),e.seed].filter(t=>typeof t=="string"&&t.trim().length>0).join(" ")}function Yd(){return[{tool:"life_bootstrap",use_when:"Start a new session or refresh NativeSoul identity, project context, memories, and capability cards."},{tool:"life_recall",use_when:"Search local memories for project-specific continuity before making assumptions."},{tool:"life_remember_propose",use_when:"Propose durable memory from user-approved facts, outcomes, or preferences."},{tool:"life_onboarding_status",use_when:"Check whether onboarding is pending before drafting or applying identity files."}]}function Qd(e){let t=e.trim();return t.length===0?"No curated user preferences yet.":t.length<=160?t:`${t.slice(0,157)}...`}async function Zd(e,t,r=!1){let o=await Ke({home:e,host:t,includeShared:!1,limit:20,readOnly:r});if(t==="codex"&&!o.some(i=>i.source.startsWith("codex app server ")))return!1;let n=o[0]?.last_seen_at;if(!n)return!1;let s=Date.parse(n);if(!Number.isFinite(s))return!1;let a=1440*60*1e3;return Date.now()-s<=a}function eu(e,t){let r=[e,ve(e,1200,420,150),ve(e,900,320,130),ve(e,650,240,110),ve(e,420,180,90),ve(e,240,120,80),Lo(ve(e,240,120,80),8,8),Lo(ve(e,240,120,80),5,5),Lo(ve(e,240,120,80),3,3)];return r.find(o=>it(JSON.stringify(o))<=t)??r[r.length-1]??e}function Lo(e,t,r){return{...e,capabilities:e.capabilities.slice(0,t),capability_cards:e.capability_cards.slice(0,r),relevant_memories:e.relevant_memories.slice(0,t),commitments:e.commitments.slice(0,t)}}function ve(e,t,r,o){return{...e,soul_summary:or(e.soul_summary,r),agents_operating_summary:or(e.agents_operating_summary,t),user:{...e.user,preferences_summary:or(e.user.preferences_summary,o)}}}import{existsSync as cn}from"node:fs";import xi from"node:path";import{mkdir as g_,readFile as tu,writeFile as f_}from"node:fs/promises";import qa from"node:path";var Do={heartbeat_enabled:!0,scheduler_host:"auto-native-supported",heartbeat_cadence:"daily",memory_candidates:!0,memory_candidate_policy:"candidate",auto_promotion:!1,promotion_policy:"explicit_approval",recall_auto_trigger_keywords:["como combinamos","como decidimos","o que combinamos","decisao anterior","decis\xE3o anterior","prior decision","previous decision","remember","lembr","memoria","mem\xF3ria","contexto anterior","last time"],recall_auto_trigger_denylist:["lint","format","typecheck","test","build"],candidate_auto_promotion_threshold:.6,recall_auto_trigger:!1,standing_order_templates:[]};async function Ga(e,t){let r=await qe(e),o=await y(gt(e));return{phase:t?"identity_pending":r&&o?"active":"pending",configured:r!==null,complete_marker_present:o,existing_profile:r,available_profiles:["quickstart","advanced"],quickstart_defaults:Do,apply_defaults:{dry_run:!0,user_confirmed:!1,reset:!1}}}function ru(e){return qa.join(e,"state","activation-profile.json")}function gt(e){return qa.join(e,"state","activation.complete")}async function qe(e){try{let t=JSON.parse(await tu(ru(e),"utf8"));return ou(t)?t:null}catch{return null}}function ou(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return(t.profile==="quickstart"||t.profile==="advanced")&&typeof t.heartbeat_enabled=="boolean"&&(typeof t.scheduler_host=="string"||t.scheduler_host===null)&&typeof t.heartbeat_cadence=="string"&&typeof t.memory_candidates=="boolean"&&(t.memory_candidate_policy==="candidate"||t.memory_candidate_policy==="off")&&typeof t.auto_promotion=="boolean"&&(t.promotion_policy==="manual"||t.promotion_policy==="explicit_approval")&&Array.isArray(t.recall_auto_trigger_keywords)&&t.recall_auto_trigger_keywords.every(r=>typeof r=="string")&&Array.isArray(t.recall_auto_trigger_denylist)&&t.recall_auto_trigger_denylist.every(r=>typeof r=="string")&&typeof t.candidate_auto_promotion_threshold=="number"&&Number.isFinite(t.candidate_auto_promotion_threshold)&&t.candidate_auto_promotion_threshold>=0&&t.candidate_auto_promotion_threshold<=1&&typeof t.recall_auto_trigger=="boolean"&&Array.isArray(t.standing_order_templates)&&t.standing_order_templates.every(r=>typeof r=="string")&&typeof t.updated_at=="string"}function Ho(e){let t={bootstrap:nu(e),mcp:su(e),plugins_hooks:au(e),heartbeat:iu(e),recall_auto_trigger:cu(e),memory_candidate_hooks:lu(e),memory_promotion_policy:du(e),cross_host_verification:uu(e)},r=Object.values(t),o=pu(r),n=r.flatMap(a=>a.plan_actions),s=mu(e.profile,o,r);return{schema_version:1,home:e.home,target_root:e.targetRoot,host:e.host,profile:e.profile,overall_status:o,components:t,plan:n,summary:s}}function Xa(e){return Ho(e).summary}function nu(e){return e.onboardingComplete&&e.activationComplete&&e.profile?P("bootstrap","active","Identity onboarding and activation marker are present.",{onboarding_complete:!0,activation_complete:!0}):P("bootstrap",e.onboardingComplete?"approval_required":"not_configured",e.onboardingComplete?"Activation profile still needs explicit approval.":"Identity onboarding is not complete.",{onboarding_complete:e.onboardingComplete,activation_complete:e.activationComplete},[Me("activation-profile","bootstrap","approval_required","Write activation profile and completion marker.",`${e.home}/state/activation-profile.json`,!0,"17.1 activation apply is explicit-approval only.")])}function su(e){let t=e.hosts.filter(r=>r.mcp_registration.configured);if(t.length>0){let r=t.some(o=>o.mcp_registration.issues.length>0);return P("mcp",r?"degraded":"active",r?"MCP is configured but doctor reported warnings.":"MCP registration is configured.",{configured_hosts:t.map(q),checked_hosts:e.hosts.map(q)})}return P("mcp","not_configured","No MCP registration was detected for the selected host scope.",{checked_hosts:e.hosts.map(q)},[Me("mcp-registration","mcp","not_configured","Install MCP registration for selected hosts.",`nativesoul mcp install --host ${e.host} --apply`,!0,"MCP registration changes host config files.")])}function au(e){let t=e.hosts.filter(o=>o.plugin.enabled||o.plugin.hook_registered);if(t.length>0){let o=t.some(n=>n.provider_parity.hooks==="official-fallback");return P("plugins_hooks",o?"degraded":"active",o?"Plugin/hooks are available through fallback support.":"Native plugin or hook support is active.",{enabled_hosts:t.map(q),hook_modes:Object.fromEntries(e.hosts.map(n=>[q(n),n.provider_parity.hooks]))})}let r=e.hosts.length>0&&e.hosts.every(o=>o.plugin.package_kind==="unsupported-native");return P("plugins_hooks",r?"blocked_by_host":"not_configured",r?"Selected hosts do not expose a native plugin path.":"No plugin or hook registration was detected.",{checked_hosts:e.hosts.map(q)},[Me("plugin-install","plugins_hooks",r?"blocked_by_host":"not_configured","Install NativeSoul plugin/hook package where the host supports it.",`nativesoul install --host ${e.host} --apply`,!0,"Host plugin/hook setup modifies host-specific config.")])}function iu(e){if(!e.profile||!e.profile.heartbeat_enabled)return P("heartbeat","not_configured","Heartbeat is not enabled in the activation profile.",{profile_present:e.profile!==null});let t=e.hosts.filter(r=>r.full_native_evidence.blocked_by_host);return t.length>0?P("heartbeat","blocked_by_host","At least one selected host lacks native scheduler support.",{blocked_hosts:t.map(q),heartbeat_modes:Object.fromEntries(e.hosts.map(r=>[q(r),r.provider_parity.heartbeat]))},[Me("heartbeat-scheduler","heartbeat","blocked_by_host","Choose a native scheduler-capable host or keep external fallback explicit.",`nativesoul schedule reconcile --host ${e.host} --mode leader --apply`,!0,"Scheduler writes must remain explicit and host-aware.")]):e.hosts.some(r=>r.provider_parity.heartbeat==="native")?P("heartbeat","active","Heartbeat has native scheduler support in the selected scope.",{native_hosts:e.hosts.filter(r=>r.provider_parity.heartbeat==="native").map(q)}):e.hosts.some(r=>r.provider_parity.heartbeat==="official-fallback")?P("heartbeat","degraded","Heartbeat is available only through fallback scheduling in the selected scope.",{fallback_hosts:e.hosts.filter(r=>r.provider_parity.heartbeat==="official-fallback").map(q)}):P("heartbeat","approval_required","Heartbeat profile is enabled, but no scheduler desired state is active yet.",{checked_hosts:e.hosts.map(q)},[Me("heartbeat-enable","heartbeat","approval_required","Create/reconcile recurring heartbeat schedule.",`nativesoul schedule reconcile --host ${e.host} --mode leader --apply`,!0,"Recurring automation requires explicit approval.")])}function cu(e){return e.profile?e.profile.recall_auto_trigger?P("recall_auto_trigger","active","Automatic recall trigger is enabled in the activation profile.",{keywords:e.profile.recall_auto_trigger_keywords,denylist:e.profile.recall_auto_trigger_denylist,auto_promotion_threshold:e.profile.candidate_auto_promotion_threshold}):P("recall_auto_trigger","approval_required","Automatic recall trigger is intentionally disabled until explicit approval.",{recall_auto_trigger:!1},[Me("recall-auto-trigger","recall_auto_trigger","approval_required","Set recall_auto_trigger=true in activation profile.","state/activation-profile.json:recall_auto_trigger",!0,"Prompt injection into host sessions must be explicitly approved.")]):P("recall_auto_trigger","not_configured","No activation profile is present.",{})}function lu(e){if(!e.profile||!e.profile.memory_candidates)return P("memory_candidate_hooks","not_configured","Memory candidate hooks are not enabled in the activation profile.",{});let t=e.hosts.every(r=>r.provider_parity.hooks==="unsupported-native");return P("memory_candidate_hooks",t?"degraded":"active",t?"Memory candidates are enabled, but hooks are not native on every selected host.":"Memory candidate capture is enabled with candidate-only policy.",{memory_candidate_policy:e.profile.memory_candidate_policy,hook_modes:Object.fromEntries(e.hosts.map(r=>[q(r),r.provider_parity.hooks]))})}function du(e){return e.profile?e.profile.auto_promotion?P("memory_promotion_policy","active","Automatic promotion is enabled by activation policy.",{promotion_policy:e.profile.promotion_policy,candidate_auto_promotion_threshold:e.profile.candidate_auto_promotion_threshold,sensitive_auto_promotion_allowed:!1}):P("memory_promotion_policy","approval_required","Memory promotion requires explicit approval.",{auto_promotion:!1,promotion_policy:e.profile.promotion_policy}):P("memory_promotion_policy","not_configured","No activation profile is present.",{})}function uu(e){let t=new Set(e.hosts.map(o=>o.host)).size,r=e.hosts.reduce((o,n)=>o+n.cross_host_inventory_summary.ready_other_hosts,0);return t>1&&e.hosts.every(o=>o.status==="ready")?P("cross_host_verification","active","Multiple selected hosts were verified by deep doctor.",{host_count:t,ready_other_hosts:r}):P("cross_host_verification",r>0?"degraded":"approval_required","Cross-host verification needs an all-host deep doctor pass before full activation claims.",{host_count:t,ready_other_hosts:r},[Me("cross-host-verify","cross_host_verification","approval_required","Run all-host deep verification.","nativesoul doctor --deep --all-hosts --json",!1,"Verification is read-only but must be run against every host.")])}function P(e,t,r,o,n=[]){return{key:e,status:t,summary:r,evidence:o,plan_actions:n}}function Me(e,t,r,o,n,s,a){return{id:e,component:t,status:r,action:o,target:n,dry_run:!0,requires_user_confirmed:s,reason:a}}function pu(e){let t=e.map(r=>r.status);return t.includes("blocked_by_host")?"blocked_by_host":t.includes("degraded")?"degraded":t.includes("approval_required")?"approval_required":t.includes("not_configured")?"not_configured":"active"}function mu(e,t,r){return{overall_status:t,profile:e?.profile??null,active:ft(r,"active"),not_configured:ft(r,"not_configured"),approval_required:ft(r,"approval_required"),blocked_by_host:ft(r,"blocked_by_host"),degraded:ft(r,"degraded"),full_native_claimed:!1}}function ft(e,t){return e.filter(r=>r.status===t).length}function q(e){return e.surface==="default"?e.host:`${e.host}:${e.surface}`}import{existsSync as gu}from"node:fs";import fu from"node:path";async function $o(e){let t=p(e),r=[],o=["AGENTS.md","SOUL.md","IDENTITY.md","USER.md","POLICY.md","MEMORY.md","HEARTBEAT.md","config.yaml"];for(let s of o)await y(fu.join(t.home,s))||r.push({code:"MISSING_HUMAN_FILE",severity:"warn",message:`${s} is missing`,remediation:"Run nativesoul init"});if(!gu(t.database))return r.push({code:"MISSING_DATABASE",severity:"error",message:"SQLite state database is missing",remediation:"Run nativesoul init"}),{home:t.home,healthy:!1,integrity:"missing",issues:r};let n=(()=>{let s=f(t.database,{readOnly:!0});try{return s.integrityCheck()}finally{s.close()}})();n!=="ok"&&r.push({code:"SQLITE_INTEGRITY",severity:"error",message:`SQLite integrity check returned ${n}`,remediation:"Restore from backup or rebuild the workspace"}),r.push(...hu(t.home,t.database));try{await m({home:t.home,type:"doctor_completed",details:{integrity:n,issueCount:r.length}})}catch{}return{home:t.home,healthy:r.every(s=>s.severity!=="error"),integrity:n,issues:r}}function hu(e,t){let r=pe(process.cwd(),e),o=f(t,{readOnly:!0});try{let n=new Set(o.listMemories({limit:200,includeForgotten:!0}).map(s=>s.scope.project).filter(s=>s!==r.id));return n.size===0?[]:[{code:"PROJECT_ID_RECONCILE_AVAILABLE",severity:"info",message:`Found ${n.size} memory project id(s) different from normalized current project ${r.id}.`,remediation:"Review with nativesoul memory export --project <old-id>; a future reconcile command will migrate aliases after approval."}]}finally{o.close()}}import Z from"node:os";import L from"node:path";function za(e){switch(e){case"grok":return"Agents.md";case"codex":return"AGENTS.md";case"claude":return"CLAUDE.md";case"antigravity":case"gemini":return"GEMINI.md"}}function Ya(e){return e==="claude"?".claude.json":e==="gemini"?"settings.json":e==="antigravity"?"mcp_config.json":"mcp.json"}function ar(e,t){if(t==null||t==="default")return e==="claude"?"claude-code":"default";if(e!=="claude")throw new Error(`--surface ${t} is only supported for --host claude`);return t}function ht(e,t){return t&&t!=="default"?[ar(e,t)]:e==="claude"?["claude-code","claude-desktop"]:["default"]}function yt(e,t){return t==="default"?e:t}function Qa(e){switch(e){case"codex":return L.join(Z.homedir(),".codex","AGENTS.md");case"claude":return L.join(Z.homedir(),".claude","CLAUDE.md");case"grok":return L.join(Z.homedir(),".grok","Agents.md");case"antigravity":case"gemini":return L.join(Z.homedir(),".gemini","GEMINI.md")}}function ir(e){switch(e){case"codex":return L.join(Z.homedir(),".codex","mcp.json");case"claude":return L.join(Z.homedir(),".claude.json");case"grok":return L.join(Z.homedir(),".grok","mcp.json");case"antigravity":return L.join(Z.homedir(),".gemini","antigravity-cli","mcp_config.json");case"gemini":return L.join(Z.homedir(),".gemini","settings.json")}}function Za(){return ei({platform:process.platform,home:Z.homedir(),env:process.env})}function ei(e){let t=e.platform==="win32"?L.win32:L.posix;if(e.platform==="darwin")return t.join(e.home,"Library","Application Support","Claude","claude_desktop_config.json");if(e.platform==="win32"){let o=e.env?.APPDATA&&e.env.APPDATA.trim().length>0?e.env.APPDATA:t.join(e.home,"AppData","Roaming");return t.join(o,"Claude","claude_desktop_config.json")}let r=e.env?.XDG_CONFIG_HOME&&e.env.XDG_CONFIG_HOME.trim().length>0?e.env.XDG_CONFIG_HOME:t.join(e.home,".config");return t.join(r,"Claude","claude_desktop_config.json")}function ti(e,t){if(e!=="claude")return null;if(!t)return L.join(Z.homedir(),".claude","mcp.json");let r=L.resolve(t),o=L.dirname(r);return L.basename(o)==="claude"?L.join(o,"mcp.json"):L.join(o,".claude","mcp.json")}import{mkdir as ri,rename as yu,writeFile as ni}from"node:fs/promises";import G from"node:path";var _u=["entity","soul","human","collaboration","continuity"],bu=["SOUL.md","POLICY.md"],si=new Set(["IDENTITY.md","SOUL.md","USER.md","AGENTS.md"]),Ge=64*1024,vu="<!-- nativesoul:start v1 -->",oi="<!-- nativesoul:end -->",ku={"IDENTITY.md":{writable:!0,requires_user_confirmed:!1,required_fields:["Name","Creature","Role","Vibe","Emoji","Mission"],field_format:"- **Field:** value (Markdown list)",merge_strategy:"replace",max_bytes:Ge},"SOUL.md":{writable:!0,requires_user_confirmed:!0,required_sections:["Core truths","Boundaries","Vibe","Continuity"],field_format:"Prose Markdown sections \u2014 not template slot-fill",merge_strategy:"replace",max_bytes:Ge},"USER.md":{writable:!0,requires_user_confirmed:!1,required_fields:["Name","What to call them","Timezone","Languages"],field_format:"- **Field:** value (Markdown list)",merge_strategy:"replace",max_bytes:Ge},"AGENTS.md":{writable:!0,requires_user_confirmed:!1,required_sections:["Session start","Safety"],field_format:"Operating instructions in Markdown",merge_strategy:"merge_managed_block",max_bytes:Ge},"POLICY.md":{writable:!1,requires_user_confirmed:!1,field_format:"Use policy propose-change after onboarding",merge_strategy:"replace",max_bytes:0}};async function Fo(e){let t=await _(e),o=(await z(t.home,"BOOTSTRAP.md")).trim().length>0;return{ritual_pending:o,files_present:{soul:await y(G.join(t.home,"SOUL.md")),identity:await y(G.join(t.home,"IDENTITY.md")),user:await y(G.join(t.home,"USER.md")),agents:await y(G.join(t.home,"AGENTS.md")),bootstrap:await y(G.join(t.home,"BOOTSTRAP.md"))},protected_targets:[...bu],writable_files:[...si],interview_themes:[..._u],instruction_doc:"llm-install.txt",apply_defaults:{dry_run:!0,user_confirmed:!1},file_generation_rules:ku,activation:await Ga(t.home,o)}}async function Uo(e){let t=await _(e.home),r=e.dry_run!==!1,o=e.user_confirmed===!0,n=[],s=[];for(let[a,i]of Object.entries(e.files)){let c=a.trim(),l=c.toUpperCase();if(l==="POLICY.MD"){n.push({file:c,action:"rejected",before_hash:null,after_hash:null,warning:"POLICY_VIOLATION: POLICY.md requires proposal flow"});continue}if(!si.has(c)){n.push({file:c,action:"rejected",before_hash:null,after_hash:null,warning:`UNSUPPORTED_FILE: ${c}`});continue}if(l==="SOUL.MD"&&!o){n.push({file:c,action:"rejected",before_hash:null,after_hash:null,warning:"POLICY_VIOLATION: SOUL.md requires user_confirmed: true"});continue}let u=typeof i=="string"?i:"";if(Buffer.byteLength(u,"utf8")>Ge){n.push({file:c,action:"rejected",before_hash:null,after_hash:null,warning:`FILE_TOO_LARGE: ${c} exceeds ${Ge} bytes`});continue}let d=G.join(t.home,c),h=await z(t.home,c),g=c==="AGENTS.md"?Ru(h,u):u,x=h.length>0?B(h):null,te=B(g);if(x===te){n.push({file:c,action:"noop",before_hash:x,after_hash:te});continue}let he=h.length===0?"create":"update";n.push({file:c,action:he,before_hash:x,after_hash:te}),r||await ni(d,g,{encoding:"utf8",mode:384})}return!r&&e.config_patch?.hosts?.length&&s.push(`CONFIG_PATCH_NOT_APPLIED_V1: hosts=${e.config_patch.hosts.join(",")}`),r||await m({home:t.home,type:"onboarding.applied",details:{user_confirmed:o,files:n.map(a=>({file:a.file,action:a.action}))}}),{dry_run:r,applied:!r,user_confirmed:o,files:n,warnings:s}}async function Vo(e){let t=p(e?.home),r=G.join(t.home,"BOOTSTRAP.md");if(!await y(r))return{already_complete:!0,archived_bootstrap:!1,archive_path:null};let o=e?.archive!==!1,n=null;if(o){let a=G.join(t.home,"memory","archive");await ri(a,{recursive:!0,mode:448});let i=new Date().toISOString().replace(/[:.]/gu,"-");n=G.join(a,`bootstrap-${i}.md`),await yu(r,n)}else{let{rm:a}=await import("node:fs/promises");await a(r,{force:!0})}let s=G.join(t.home,"state","onboarding.complete");return await ri(G.join(t.home,"state"),{recursive:!0,mode:448}),await ni(s,`${new Date().toISOString()}
827
+ `,{encoding:"utf8",mode:384}),await m({home:t.home,type:"onboarding.completed",details:{archived:o,archive_path:n}}),{already_complete:!1,archived_bootstrap:o,archive_path:n}}function cr(e){return G.join(e,"state","onboarding.complete")}function Ru(e,t){let r=t.trim();if(!e.trim())return`${r}
828
+ `;if(e.includes(r))return e;let o=Su(e);if(o){let s=o.after.trimEnd(),a=s.length>0?`${s}
766
829
 
767
830
  ${r}
768
831
  `:`${r}
769
- `;return`${o.before}${o.block}${s}`}let a=Lt["AGENTS.md"]??"";return e.trim()===a.trim()?`${r}
832
+ `;return`${o.before}${o.block}${a}`}let n=$t["AGENTS.md"]??"";return e.trim()===n.trim()?`${r}
770
833
  `:`${e.trimEnd()}
771
834
 
772
835
  ## Onboarding Update
773
836
 
774
837
  ${r}
775
- `}function Od(e){let t=e.indexOf(jd),r=e.indexOf(xs);if(t<0||r<0||r<t)return null;let o=r+xs.length;return{before:e.slice(0,t),block:e.slice(t,o),after:e.slice(o)}}function Cs(e,t){return t?gs(e):Nd()}function Nd(){return{provider_id:"local-hash",model_id:"local-hash-bow-v1",schema_version:1,available:!1,indexable_count:0,indexed_count:0,stale_count:0,healthy:!1,remediation:"Run nativesoul init, then nativesoul memory index"}}function Is(e){return!e.available||e.stale_count===0?[]:[{code:"SEMANTIC_INDEX_STALE",severity:"warn",message:`${e.stale_count} memory record(s) need semantic indexing.`,remediation:e.remediation??"Run nativesoul memory index"}]}function Os(e){let t=new Map;for(let o of e){let a=t.get(o.host)??{capability_count:0,ready_capability_count:0};t.set(o.host,{capability_count:a.capability_count+1,ready_capability_count:a.ready_capability_count+(o.ready?1:0)})}let r=Array.from(t.entries()).map(([o,a])=>({host:o,...a}));return{host_count:r.length,capability_count:r.reduce((o,a)=>o+a.capability_count,0),ready_capability_count:r.reduce((o,a)=>o+a.ready_capability_count,0),hosts:r}}function sr(e){let t=h(e,{readOnly:!0});try{return t.listCapabilities({limit:1e4}).map(r=>({host:r.host,ready:r.ready}))}finally{t.close()}}import{existsSync as hu}from"node:fs";import{readFile as yu,stat as _u}from"node:fs/promises";import Gs from"node:path";import{mkdir as Md,readFile as Ld,rename as Dd,writeFile as Hd}from"node:fs/promises";import mt from"node:path";var $d=1440*60*1e3;async function Ie(e){let t=p(e.home),r=await Po(t.home),o={host:e.host,outcome:e.outcome,tier:e.tier,cwd:e.cwd?mt.resolve(e.cwd):null,project:e.project??null,tokens_used:e.tokensUsed??null,tokens_max:e.tokensMax??null,source:e.source??"nativesoul",warnings:(e.warnings??[]).map(a=>H(a).value),error:Bd(e.error),recorded_at:e.recordedAt??new Date().toISOString()};return r.hosts[e.host]=o,await Ud(t.home,r),await g({home:t.home,type:Vd(e.outcome),result:e.outcome==="failed"?"error":"ok",details:o}),o}async function Po(e){let t=p(e),r=To(t.home);if(!await y(r))return Fd();let o=JSON.parse(await Ld(r,"utf8"));return{schema:1,hosts:typeof o.hosts=="object"&&o.hosts!==null?o.hosts:{}}}async function xo(e){let t=p(e.home),o=(await Po(t.home)).hosts[e.host]??null,a=(e.now??new Date).getTime(),n=o?Date.parse(o.recorded_at):Number.NaN,s=Number.isFinite(n)?Math.max(a-n,0):null;return{state_path:To(t.home),last:o,age_ms:s,age_hours:s===null?null:Math.round(s/(3600*1e3)*10)/10,stale:s!==null&&s>$d}}function Fd(){return{schema:1,hosts:{}}}async function Ud(e,t){let r=To(e);await Md(mt.dirname(r),{recursive:!0,mode:448});let o=mt.join(mt.dirname(r),`.last-handshake-${P("tmp")}.tmp`);await Hd(o,`${JSON.stringify(t,null,2)}
776
- `,{encoding:"utf8",mode:384}),await Dd(o,r)}function To(e){return mt.join(e,"state","last-handshake.json")}function Vd(e){return`handshake_${e}`}function Bd(e){if(e==null)return null;let t=e instanceof Error?e.message:String(e);return H(t).value.slice(0,500)}import yt from"node:path";import{existsSync as _b}from"node:fs";import{cp as vb,mkdir as Rb,rm as Sb}from"node:fs/promises";import wb from"node:path";import{existsSync as ve}from"node:fs";import{readFile as dr}from"node:fs/promises";import me from"node:path";import Jd from"node:path";function ir(e){return e.split(/[\\/]/u).join("/")}function gt(e,t){return ir(Jd.relative(e,t))}import{existsSync as Ns}from"node:fs";import jo from"node:path";function Co(e){if(jo.isAbsolute(e))return Ns(e)?e:null;let t=(process.env.PATH??"").split(jo.delimiter).filter(Boolean),r=process.platform==="win32"?(process.env.PATHEXT??".EXE;.CMD;.BAT").split(";"):[""];for(let o of t)for(let a of r){let n=jo.join(o,`${e}${a}`);if(Ns(n))return n}return null}import{spawnSync as r_}from"node:child_process";import{existsSync as Kd}from"node:fs";import{mkdir as n_,readFile as qd,writeFile as s_}from"node:fs/promises";import Gd from"node:os";import ht from"node:path";import{existsSync as zy}from"node:fs";import ft from"node:os";import ee from"node:path";import{fileURLToPath as Zy}from"node:url";function be(e,t,r){return cr(e,t)?r?ee.join(ee.resolve(r),e,"plugins","nativesoul"):e==="claude"?ee.join(ft.homedir(),".claude","plugins","nativesoul"):e==="codex"?ee.join(ft.homedir(),".codex","plugins","nativesoul"):e==="gemini"?ee.join(ft.homedir(),".gemini","extensions","nativesoul"):e==="grok"?ee.join(ft.homedir(),".grok","plugins","nativesoul"):e==="antigravity"?ee.join(ft.homedir(),".antigravity","plugins","nativesoul"):null:null}function cr(e,t){return e==="codex"||e==="gemini"||e==="grok"||e==="antigravity"||e==="claude"&&(t==="claude-code"||t==="claude-desktop")}function lr(e,t){return e==="claude"?ee.join(t,".claude-plugin","plugin.json"):e==="gemini"?ee.join(t,"gemini-extension.json"):e==="grok"||e==="antigravity"?ee.join(t,"plugin.json"):ee.join(t,".codex-plugin","plugin.json")}var Ms="nativesoul";async function Hs(e){let t=e?Wd(e):ht.join(Gd.homedir(),".grok","config.toml");if(!Kd(t))return null;let r=await qd(t,"utf8");return Ls(r,"disabled",Ms)?!1:Ls(r,"enabled",Ms)?!0:null}function Ls(e,t,r){let n=(e.match(/\[plugins\][\s\S]*?(?=\n\[|$)/u)?.[0]??e).match(new RegExp(`${t}\\s*=\\s*\\[([^\\]]*)\\]`,"u"))?.[1];return n?n.split(",").some(s=>s.replace(/["'\s]/gu,"")===r):!1}function Wd(e){let t=ht.resolve(e),r=ht.basename(t);return r==="grok"||r===".grok"?ht.join(t,"config.toml"):ht.join(t,".grok","config.toml")}import zd from"node:path";var Io=[{event:"SessionStart",commandFragment:"hooks/session-start.cjs",fileName:"session-start.cjs"},{event:"PreToolUse",commandFragment:"hooks/pre-tool-use.cjs",fileName:"pre-tool-use.cjs"},{event:"Stop",commandFragment:"hooks/memory-flush.cjs",fileName:"memory-flush.cjs"},{event:"PreCompact",commandFragment:"hooks/memory-flush.cjs",fileName:"memory-flush.cjs"},{event:"UserPromptSubmit",commandFragment:"hooks/user-prompt-submit.cjs",fileName:"user-prompt-submit.cjs"}],Xd={grok:[{event:"SessionStart",commandFragment:"host-hook.cjs"},{event:"UserPromptSubmit",commandFragment:"prompt-bootstrap --host grok"},{event:"PreToolUse",commandFragment:"pre-tool-use --host grok"},{event:"Stop",commandFragment:"memory-flush --host grok"},{event:"PreCompact",commandFragment:"memory-flush --host grok"}],gemini:[{event:"SessionStart",commandFragment:"host-hook.cjs"},{event:"BeforeAgent",commandFragment:"prompt-bootstrap --host gemini"},{event:"BeforeTool",commandFragment:"pre-tool-use --host gemini"},{event:"AfterAgent",commandFragment:"memory-flush --host gemini"},{event:"PreCompress",commandFragment:"memory-flush --host gemini"}],antigravity:[{event:"SessionStart",commandFragment:"host-hook.cjs"},{event:"UserPromptSubmit",commandFragment:"prompt-bootstrap --host antigravity"},{event:"PreToolUse",commandFragment:"pre-tool-use --host antigravity"},{event:"Stop",commandFragment:"memory-flush --host antigravity"},{event:"PreCompact",commandFragment:"memory-flush --host antigravity"}]};function Oo(e,t){return e==="codex"||e==="claude"||e==="grok"||e==="antigravity"?{packageKind:"native-plugin",nativeHooksSupported:!0}:e==="gemini"?{packageKind:"official-extension",nativeHooksSupported:!0}:{packageKind:"unsupported-native",nativeHooksSupported:!1}}function Yd(e){return e==="grok"||e==="gemini"||e==="antigravity"?Xd[e]:Io}function No(e){return e==="grok"||e==="gemini"?["hooks/hooks.json"]:e==="antigravity"?["hooks.json"]:[...new Set(Io.map(t=>t.fileName).filter(t=>!!t))].map(t=>zd.join("hooks",t))}function $s(e,t){return t==="official-extension"?typeof e.name=="string"&&e.name==="nativesoul":typeof e.name=="string"&&e.name.includes("nativesoul")}function Fs(e,t){return Mo(e,t).length===0}function Mo(e,t){return Yd(e).filter(({event:r,commandFragment:o})=>!Qd(t,r,o)).map(({event:r})=>r)}function Lo(e){return e==="claude"?[".claude-plugin/plugin.json"]:e==="codex"?[".mcp.json"]:e==="gemini"?["gemini-extension.json"]:e==="grok"?[".mcp.json"]:e==="antigravity"?["mcp_config.json"]:[]}function Do(e){return e==="claude"?[".claude-plugin/plugin.json"]:e==="codex"?[".codex-plugin/plugin.json"]:e==="gemini"||e==="grok"?["hooks/hooks.json"]:e==="antigravity"?["hooks.json"]:[]}function Qd(e,t,r){if(!e.hooks||Array.isArray(e.hooks)||typeof e.hooks!="object")return!1;let a=e.hooks[t];return!Array.isArray(a)||a.length===0?!1:a.some(n=>{if(!n||Array.isArray(n)||typeof n!="object")return!1;let s=n.hooks;return!Array.isArray(s)||s.length===0?!1:s.some(i=>{if(!i||Array.isArray(i)||typeof i!="object")return!1;let c=i.command;return typeof c=="string"&&ir(c).includes(r)})})}async function Ke(e){if(!e.targetPath||!cr(e.host,e.surface))return{host:e.host,surface:e.surface,targetPath:e.targetPath,target_exists:!1,manifest_exists:!1,enabled:!1,hook_registered:!1,package_kind:"unsupported-native",native_hooks_supported:!1,native_scheduler_supported:!1,issues:[]};let t=Oo(e.host,e.surface),r=ve(e.targetPath),o=lr(e.host,e.targetPath),a=ve(o),n=t.nativeHooksSupported&&e.targetPath?No(e.host).filter(J=>!ve(me.join(e.targetPath,J))):No(e.host),s=t.nativeHooksSupported?n.length===0:!0,i=[],c=!1,l=!t.nativeHooksSupported;if(!r)i.push({code:"PLUGIN_NOT_INSTALLED",severity:"warn",message:`NativeSoul plugin is not installed for ${e.host}:${e.surface}.`,remediation:`Run nativesoul install --host ${e.host} --apply`});else if(!a)i.push({code:"PLUGIN_MANIFEST_MISSING",severity:"error",message:`NativeSoul plugin manifest is missing: ${o}`,remediation:"Reinstall the NativeSoul plugin"});else{let J=JSON.parse(await dr(o,"utf8")),Me=t.nativeHooksSupported?await Zd(e.host,e.targetPath,J):J;if(c=t.nativeHooksSupported?Fs(e.host,Me):$s(J,t.packageKind),l=!t.nativeHooksSupported||await eu({host:e.host,targetPath:e.targetPath,manifest:J}),t.nativeHooksSupported&&!l&&i.push({code:"PLUGIN_MCP_COMMAND_UNRESOLVED",severity:"error",message:"NativeSoul plugin MCP server command is not resolved for daemon-safe startup.",remediation:"Reinstall the NativeSoul plugin so its MCP server command is rendered with an absolute or executable command"}),!c&&t.nativeHooksSupported){let Le=Mo(e.host,Me);i.push({code:"PLUGIN_HOOK_MISSING",severity:"error",message:Le.length>0?`NativeSoul plugin manifest is missing required hook registrations: ${Le.join(", ")}.`:"NativeSoul plugin manifest does not register required continuity hooks.",remediation:"Reinstall the NativeSoul plugin"})}!c&&!t.nativeHooksSupported&&i.push({code:"PLUGIN_PACKAGE_MANIFEST_INVALID",severity:"error",message:`NativeSoul ${t.packageKind} manifest is invalid for ${e.host}.`,remediation:"Reinstall the NativeSoul package"})}r&&t.nativeHooksSupported&&!s&&i.push({code:"PLUGIN_HOOK_FILE_MISSING",severity:"error",message:`NativeSoul required hook files are missing under ${e.targetPath}: ${n.join(", ")}`,remediation:"Reinstall the NativeSoul plugin"});let u=e.targetPath?me.join(e.targetPath,"shared","hooks","lib.cjs"):null;r&&t.nativeHooksSupported&&(!u||!ve(u))&&i.push({code:"PLUGIN_SHARED_HOOKS_MISSING",severity:"error",message:"NativeSoul shared hook support files are missing under shared/hooks.",remediation:"Reinstall the NativeSoul plugin"});let d=e.targetPath?me.resolve(me.dirname(me.dirname(e.targetPath))):void 0,f=!t.nativeHooksSupported||u!==null&&ve(u),m=t.nativeHooksSupported?s&&f:!0,E=r&&a&&c&&m&&l,te=e.host==="grok"?await Hs(d):null;return e.host==="grok"&&E&&te===!1&&i.push({code:"GROK_PLUGIN_RUNTIME_DISABLED",severity:"error",message:"NativeSoul is installed for Grok but disabled in grok config, so SessionStart hooks will not run.",remediation:"Run `grok plugin enable nativesoul` or `nativesoul install --host grok --apply`."}),{host:e.host,surface:e.surface,targetPath:e.targetPath,target_exists:r,manifest_exists:a,enabled:E&&te!==!1,hook_registered:t.nativeHooksSupported?c&&s:!1,package_kind:t.packageKind,native_hooks_supported:t.nativeHooksSupported,native_scheduler_supported:!1,issues:i}}async function Zd(e,t,r){let o=Do(e);if(o.length===0)return r;let a=gt(t,lr(e,t)),n=o[0];if(!n||n===a)return r;let s=me.join(t,n);return ve(s)?JSON.parse(await dr(s,"utf8")):{}}async function eu(e){let t=Lo(e.host),r=gt(e.targetPath,lr(e.host,e.targetPath));if(t.length>0&&!t.includes(r)){for(let o of t){let a=me.join(e.targetPath,o);if(ve(a)&&Ho(JSON.parse(await dr(a,"utf8"))))return!0}return!1}if(e.host==="codex"){let o=me.join(e.targetPath,".mcp.json");return ve(o)?Ho(JSON.parse(await dr(o,"utf8"))):!1}return Ho(e.manifest)}function Ho(e){let r=(!e.mcpServers||Array.isArray(e.mcpServers)||typeof e.mcpServers!="object"?null:e.mcpServers)?.nativesoul??(!e.nativeSoul||Array.isArray(e.nativeSoul)||typeof e.nativeSoul!="object"?null:e.nativeSoul.mcpServer);if(!r||Array.isArray(r)||typeof r!="object")return!1;let o=r.command,a=r.args;return typeof o!="string"||o.length===0?!1:o==="nativesoul-mcp"||Co(o)||o===process.execPath?!0:Array.isArray(a)&&a.some(n=>typeof n=="string"&&me.isAbsolute(n))}import{cp as E_,mkdir as P_,readFile as x_,readdir as T_}from"node:fs/promises";import C_ from"node:path";import{existsSync as q_}from"node:fs";import{cp as W_,mkdir as z_,readFile as X_,writeFile as Y_}from"node:fs/promises";import Z_ from"node:path";import{fileURLToPath as tb}from"node:url";import{spawnSync as L_}from"node:child_process";import{accessSync as H_,constants as $_,existsSync as F_}from"node:fs";import V_ from"node:path";function ur(e,t,r){let o=or(e,r);if(e==="claude"&&o==="claude-desktop")return{surface:o,managedBlock:null,mcpRegistration:t?yt.join(yt.resolve(t,e),"claude_desktop_config.json"):ws(),plugin:be(e,o,t)};if(!t)return{surface:o,managedBlock:ks(e),mcpRegistration:ar(e),plugin:be(e,o)};let a=yt.resolve(t,e);return{surface:o,managedBlock:yt.join(a,Rs(e)),mcpRegistration:yt.join(a,Ss(e)),plugin:be(e,o,t)}}import{accessSync as ru,constants as ou,existsSync as _t}from"node:fs";import{mkdir as Bb,readFile as $o,rm as Jb,writeFile as Kb}from"node:fs/promises";import ie from"node:path";async function Vo(e){let t=ie.resolve(e.targetPath??Js(e.host)),r=Es(e.host,e.targetPath),o=_t(t),a=[],n=await au(e.host,t,r);if(n&&a.push(n),!o)return a.push({code:"MCP_CONFIG_MISSING",severity:"warn",message:`MCP config target is missing: ${t}`,remediation:"Run nativesoul mcp install --host <host> --target <path> --apply"}),{host:e.host,targetPath:t,target_exists:!1,parse_ok:!1,configured:!1,command:null,command_ok:!1,issues:a};let s=null;try{s=Fo(await $o(t,"utf8"))}catch(d){a.push({code:"MCP_CONFIG_INVALID_JSON",severity:"error",message:d instanceof Error?d.message:"MCP config is invalid JSON",remediation:"Fix the JSON syntax or roll back from an NativeSoul snapshot"})}let i=s?Uo(s):null,c=typeof i?.command=="string"?i.command:null,l=Array.isArray(i?.args)?i.args.filter(d=>typeof d=="string"):[];i?c||a.push({code:"NATIVESOUL_MCP_COMMAND_MISSING",severity:"error",message:"nativesoul MCP server command is missing",remediation:"Re-run nativesoul mcp install"}):a.push({code:"NATIVESOUL_MCP_MISSING",severity:"warn",message:"nativesoul MCP server entry is not configured",remediation:"Run nativesoul mcp install --host <host> --target <path> --apply"});let u=c?e.checkCommand===!1?{ok:!0,issues:[]}:nu(c,l,t):{ok:!1,issues:[]};return a.push(...u.issues),{host:e.host,targetPath:t,target_exists:o,parse_ok:s!==null,configured:i!==null,command:c,command_ok:u.ok,issues:a}}function Js(e){return ar(e)}function Fo(e){if(e===null||e.trim().length===0)return{};let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("MCP config root must be a JSON object");return t}function Uo(e){let t=e.mcpServers;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.nativesoul;return!r||typeof r!="object"||Array.isArray(r)?null:r}async function au(e,t,r){if(e!=="claude"||r===null||ie.resolve(r)===t||!_t(r))return null;try{let o=Fo(await $o(r,"utf8")),a=Uo(o);if(!a)return null;if(_t(t)){let n=Fo(await $o(t,"utf8")),s=Uo(n);if(s&&JSON.stringify(Vs(s))===JSON.stringify(Vs(a)))return null}}catch{return null}return{code:"LEGACY_MCP_PATH",severity:"warn",message:`Legacy Claude MCP registration detected at ${r}.`,remediation:"Migrate to ~/.claude.json with nativesoul mcp install --host claude --apply, then uninstall or roll back the legacy ~/.claude/mcp.json entry."}}function Vs(e){return{command:typeof e.command=="string"?e.command:null,args:Array.isArray(e.args)?e.args.filter(t=>typeof t=="string"):[]}}function nu(e,t,r){let o=[],a=su(e);if(!a)return o.push({code:"NATIVESOUL_MCP_COMMAND_UNRESOLVED",severity:"error",message:`nativesoul MCP command does not resolve to an executable: ${e}`,remediation:"Reinstall with NATIVESOUL_MCP_COMMAND set to an absolute nativesoul-mcp path, or run npm install -g nativesoul and retry."}),{ok:!1,issues:o};if(iu(e,a)){let n=t[0],s=n?ie.isAbsolute(n)?n:ie.resolve(ie.dirname(r),n):null;if(!s||!_t(s))return o.push({code:"NATIVESOUL_MCP_NODE_SCRIPT_MISSING",severity:"error",message:"nativesoul MCP command uses node but the server script is missing.",remediation:"Re-run nativesoul mcp install with --command-mode absolute or rebuild the local package."}),{ok:!1,issues:o}}return{ok:!0,issues:o}}function su(e){if(ie.isAbsolute(e))return Bs(e)?e:null;let t=(process.env.PATH??"").split(ie.delimiter).filter(Boolean),r=process.platform==="win32"?(process.env.PATHEXT??".EXE;.CMD;.BAT").split(";"):[""];for(let o of t)for(let a of r){let n=ie.join(o,`${e}${a}`);if(Bs(n))return n}return null}function Bs(e){if(process.platform==="win32"&&_t(e))return!0;try{return ru(e,ou.X_OK),!0}catch{return!1}}function iu(e,t){let r=ie.basename(e).toLowerCase(),o=ie.basename(t).toLowerCase();return r==="node"||r==="node.exe"||o==="node"||o==="node.exe"}async function Bo(e){let t=e.readOnly?p(e.home):await b(e.home);if(e.readOnly&&!await y(t.database))return[];let r=h(t.database,{readOnly:e.readOnly});try{return r.listSchedules({host:e.host,limit:Math.min(Math.max(e.limit??50,1),200)})}finally{r.close()}}function Jo(e){let t=e.observedAt??new Date().toISOString(),r=e.plugin.enabled&&["native-plugin","official-extension"].includes(e.plugin.package_kind),o=e.plugin.native_hooks_supported&&e.plugin.hook_registered,a=e.mcpRegistration.configured,n=e.schedules.some(m=>lu(m,t)),s=mu(e.capabilities,e.adapterDiagnostics),i=[bt("native_package",r,t,e.plugin.targetPath??e.plugin.package_kind,"Native package/extension is not installed or enabled."),bt("native_hooks",o,t,e.plugin.targetPath??e.plugin.package_kind,"Native lifecycle hook registration is missing."),bt("mcp",a,t,e.mcpRegistration.targetPath,"MCP registration is missing or invalid."),bt("native_scheduler",n,t,uu(e.schedules),gu(e.host,e.schedules)),bt("official_inventory",s,t,pu(e.capabilities),"Official non-degraded capability inventory evidence is missing.")],c=i.filter(m=>!m.satisfied).map(m=>m.requirement),l=r&&o&&a,u=!s,d=c.includes("native_scheduler")&&qs(e.host),f=c.length===0;return{schema_version:1,host:e.host,surface:e.surface,status:fu({fullNative:f,blockedByHost:d,degradedScan:u,ready:l}),ready:l,full_native:f,blocked_by_host:d,degraded_scan:u,generated_at:t,requirements:i,missing_requirements:c}}function bt(e,t,r,o,a){return{requirement:e,satisfied:t,evidence:t?[{source_kind:"doctor",reference:o,observed_at:r,confidence:cu(o)}]:[],missing_reason:t?null:a}}function cu(e){return e.startsWith("not-applicable:")||e==="missing"?"low":"medium"}function lu(e,t){return e.enabled&&e.native_schedule_supported&&e.native_id!==null&&!du(e.updated_at,t)}function du(e,t){if(!e)return!1;let r=Date.parse(e),o=Date.parse(t);return!Number.isFinite(r)||!Number.isFinite(o)?!0:o-r>10080*60*1e3}function uu(e){let t=e.find(r=>r.native_id!==null);return t?.native_id?t.updated_at?`${t.native_id}@${t.updated_at}`:t.native_id:"missing"}function pu(e){return e.find(t=>t.ready)?.source??"missing"}function mu(e,t){return t.some(r=>r.severity==="error"||r.severity==="warn")?!1:e.some(r=>r.ready&&r.schema_hash?.startsWith("official:")===!0)}function gu(e,t){return qs(e)?e==="claude"?"Claude local Scheduled Tasks proof is missing, UI-only, or cloud-routine-only for this surface.":e==="antigravity"?"Antigravity scheduler write/list/status/cancel contract proof is missing or stale.":`Host ${e} has no proven native scheduler support.`:t.some(r=>r.enabled)?"Enabled schedule uses fallback or has no native_id mapping.":"No enabled native schedule evidence is available."}function qs(e){return e==="codex"||e==="claude"||e==="grok"||e==="gemini"||e==="antigravity"}function fu(e){return e.fullNative?"full_native":e.blockedByHost?"blocked_by_host":e.degradedScan?"degraded_scan":e.ready?"ready_fallback":"ready"}async function Ws(e){let t=ur(e.host,e.targetRoot,e.surface),r=t.managedBlock??`not-applicable:${pt(e.host,e.surface)}`,o=t.managedBlock?await Zn({host:e.host,targetPath:r}):Eu(e.host,e.surface),a=await Vo({host:e.host,targetPath:t.mcpRegistration,checkCommand:e.targetRoot===void 0}),n=await Ke({host:e.host,surface:e.surface,targetPath:t.plugin}),s=await xo({home:e.home,host:e.host}),c=(e.databaseExists?await Bo({home:e.home,host:e.host,limit:200,readOnly:!0}):[]).filter(R=>bu(e.host,e.surface,R)),l=e.databaseExists?await Ve({home:e.home,host:e.host,limit:100,readOnly:!0}):[],u=e.databaseExists?sr(p(e.home).database):[],d=e.targetRoot!==void 0,f=d?[]:(await io(e.host))[0]?.diagnostics??[],m=c.length===0&&e.databaseExists?[{code:"SCHEDULE_DESIRED_STATE_MISSING",severity:"warn",message:`No persisted schedule desired state found for ${e.host}.`,remediation:e.targetRoot?`Run nativesoul install --host ${e.host} --apply --target-root ${e.targetRoot}`:"Run nativesoul install --host <host> --apply"}]:[],E=s.stale?[{code:"HANDSHAKE_STALE",severity:"warn",message:`Last ${e.host} handshake is ${s.age_hours??"unknown"} hour(s) old.`,remediation:`Run nativesoul bootstrap --host ${e.host} --cwd <current-working-directory> --format inject`}]:[],te=await Su({host:e.host,managedBlock:o,handshake:s}),J=await ku(e.host),Me=c.filter(R=>R.enabled&&R.native_schedule_supported&&R.native_id===null).map(R=>({code:"NATIVE_SCHEDULE_MAPPING_MISSING",severity:"warn",message:`Schedule ${R.id} reports native support but has no native_id mapping.`,remediation:e.targetRoot?`Run nativesoul schedule reconcile --host ${e.host} --apply --target-root ${e.targetRoot}`:`Run nativesoul schedule reconcile --host ${e.host} --apply`})),Le=c.filter(R=>R.enabled&&!R.native_schedule_supported&&!n.enabled&&n.package_kind!=="unsupported-native").map(R=>({code:"NATIVE_SCHEDULE_UNSUPPORTED_NO_FALLBACK_INSTALLED",severity:"warn",message:`Schedule ${R.id} has no native scheduler support and no NativeSoul package fallback is installed.`,remediation:`Run nativesoul install --host ${e.host} --apply`})),Pt=Ru({managedBlock:o,mcpRegistration:a,plugin:n,schedules:c,capabilities:l}),fa=Jo({host:e.host,surface:e.surface,mcpRegistration:a,plugin:n,schedules:c,capabilities:l,adapterDiagnostics:f}),xt=[...o.issues,...a.issues,...n.issues,...f,...m,...E,...te,...J,...Me,...Le];return{host:e.host,surface:e.surface,status:xt.some(R=>R.severity==="error"||R.severity==="warn")?"degraded":"ready",targets:{managed_block:r,mcp_registration:a.targetPath},native_adapter_diagnostics_skipped:d,adapter_diagnostics:f,managed_block:o,mcp_registration:a,plugin:n,provider_parity:Pt,full_native_evidence:fa,handshake:s,schedule_count:c.length,enabled_schedule_count:c.filter(R=>R.enabled).length,native_schedule_mappings:c.map(R=>({id:R.id,native_schedule_supported:R.native_schedule_supported,native_id:R.native_id})),capability_count:l.length,ready_capability_count:l.filter(R=>R.ready).length,cross_host_inventory_summary:{current_host:l.length,other_hosts:u.filter(R=>R.host!==e.host&&R.host!=="all").length,ready_other_hosts:u.filter(R=>R.host!==e.host&&R.host!=="all"&&R.ready).length},issues:xt}}function bu(e,t,r){return e!=="claude"?!0:vu(r.desired)===t}function vu(e){if(e&&typeof e=="object"&&!Array.isArray(e)&&"surface"in e){let t=e.surface;if(t==="claude-desktop"||t==="claude-code")return t}return"claude-code"}function Ru(e){let t=e.plugin.enabled,r=e.mcpRegistration.configured,o=e.managedBlock.configured||t,a=e.schedules.some(d=>d.enabled),s=e.schedules.some(d=>d.enabled&&d.native_schedule_supported)?"native":a&&t?"official-fallback":"unsupported-native",i=e.plugin.native_hooks_supported?e.plugin.hook_registered?"native":"unsupported-native":t?"official-fallback":"unsupported-native",c=e.plugin.package_kind==="unsupported-native"?"unsupported-native":t?"ready":"degraded",l=e.capabilities.length===0||e.capabilities.some(d=>d.ready);return{level:o&&r&&c==="ready"&&i!=="unsupported-native"&&s!=="unsupported-native"?"ready":e.plugin.package_kind==="native-plugin"?"native":e.plugin.package_kind==="unsupported-native"?"unsupported-native":"official-fallback",bootstrap:o?"ready":"degraded",mcp:r?"ready":"degraded",package:c,hooks:i,memory_recall:r?"ready":"degraded",policy_guard:o?"ready":"degraded",capability_scan:l?"ready":"degraded",heartbeat:s}}async function Su(e){if(!e.managedBlock.configured||e.managedBlock.targetPath.startsWith("not-applicable:"))return[];let t=10080*60*1e3,r=await Au(e.managedBlock.targetPath),o=e.handshake.age_ms;return r!==null&&r<=t?[]:o!==null&&o<=t?[]:[{code:"HANDSHAKE_NOT_OBSERVED",severity:"warn",message:`NativeSoul managed block is present for ${e.host}, but no handshake was observed in the last 7 days.`,remediation:`Start a host session or run nativesoul bootstrap --host ${e.host} --cwd <current-working-directory> --format inject`}]}async function ku(e){let t=wu(e).map(r=>Gs.resolve(process.cwd(),r));for(let r of t){if(!hu(r))continue;let o=await yu(r,"utf8"),a=rt(o);if(a>2e3)return[{code:"PROJECT_CONTEXT_HEAVY",severity:"info",message:`Project instruction file is heavy (${a} estimated tokens): ${r}`,remediation:"Keep project rules authoritative for code boundaries; NativeSoul persona remains advisory continuity."}]}return[]}function wu(e){switch(e){case"claude":return["CLAUDE.md",Gs.join(".claude","CLAUDE.md")];case"codex":return["AGENTS.md"];case"grok":return["Agents.md","AGENTS.md"];case"antigravity":case"gemini":return["GEMINI.md"]}}async function Au(e){try{let t=await _u(e);return Math.max(Date.now()-t.mtimeMs,0)}catch{return null}}function Eu(e,t){return{host:e,targetPath:`not-applicable:${pt(e,t)}`,target_exists:!1,configured:!0,markers_valid:!0,issues:[]}}async function vt(e){let t=p(e.home),r=await ko(e.home),o=Ko(t.database),a=Ue(e.host),n=[],s=o?sr(t.database):[],i=Cs(t.database,o),c=await Be(t.home),l=Ko(nr(t.home)),u=Ko(lt(t.home));for(let m of a)for(let E of ut(m,e.surface))n.push(await Ws({home:t.home,host:m,surface:E,targetRoot:e.targetRoot,databaseExists:o}));let d=[...r.issues,...Is(i),...n.flatMap(m=>m.issues)],f=r.healthy&&!d.some(m=>m.severity==="error");return{home:t.home,healthy:f,status:d.some(m=>m.severity==="error"||m.severity==="warn")?"degraded":"ready",workspace:r,target_root:e.targetRoot?zs.resolve(e.targetRoot):null,cross_host_inventory:Os(s),activation_summary:vs({home:t.home,targetRoot:e.targetRoot?zs.resolve(e.targetRoot):null,host:e.host,profile:c,onboardingComplete:l,activationComplete:u,hosts:n}),full_native_matrix:Pu(n),semantic_index:i,hosts:n,issues:d}}function Pu(e){let t=e.map(r=>({host:r.host,surface:r.surface,status:r.full_native_evidence.status,full_native:r.full_native_evidence.full_native,blocked_by_host:r.full_native_evidence.blocked_by_host,degraded_scan:r.full_native_evidence.degraded_scan,missing_requirements:r.full_native_evidence.missing_requirements}));return{require_full_native_ready:t.length>0&&t.every(r=>r.full_native),host_count:t.length,full_native_count:t.filter(r=>r.full_native).length,blocked_count:t.filter(r=>r.blocked_by_host).length,degraded_scan_count:t.filter(r=>r.degraded_scan).length,ready_fallback_count:t.filter(r=>r.status==="ready_fallback").length,hosts:t}}import{existsSync as Fv}from"node:fs";import{mkdir as Vv,readdir as Bv,readFile as Jv,writeFile as Kv}from"node:fs/promises";import Gv from"node:path";import{lstat as nR,readdir as sR,readFile as iR}from"node:fs/promises";import lR from"node:path";import{lstat as bR,readFile as vR}from"node:fs/promises";import SR from"node:path";var Oe={state:"unlicensed",license_key:null,instance_id:null,purchased_at:null,version_at_activation:null,updates_until:null,last_checked_at:null,source:"none"};import{chmod as xu,mkdir as Tu,readFile as ju,rm as OR,writeFile as Cu}from"node:fs/promises";import{randomUUID as Iu}from"node:crypto";import Xs from"node:path";function qo(e){return Xs.join(p(e).home,"license.json")}async function Ne(e){let t=qo(e);if(!await y(t))return null;try{let r=JSON.parse(await ju(t,"utf8"));return Ou(r)?r:null}catch{return null}}async function pr(e,t){let r=qo(e);return await Tu(Xs.dirname(r),{recursive:!0,mode:448}),await Cu(r,`${JSON.stringify(t,null,2)}
777
- `,{encoding:"utf8",mode:384}),await xu(r,384),t}async function Go(e){let t=await Ne(e);if(t?.instance_id)return t.instance_id;let r=Iu();return await pr(e,{...Oe,instance_id:r,purchased_at:t?.purchased_at??null,version_at_activation:t?.version_at_activation??null,updates_until:t?.updates_until??null,license_key_instance_id:t?.license_key_instance_id??null}),r}function Ou(e){return(e.state==="licensed"||e.state==="unlicensed")&&(typeof e.license_key=="string"||e.license_key===null)&&(typeof e.instance_id=="string"||e.instance_id===null)&&(typeof e.purchased_at=="string"||e.purchased_at===null||e.purchased_at===void 0)&&(typeof e.version_at_activation=="string"||e.version_at_activation===null||e.version_at_activation===void 0)&&(typeof e.updates_until=="string"||e.updates_until===null)&&(typeof e.last_checked_at=="string"||e.last_checked_at===null)&&(e.source==="dodo"||e.source==="none")&&(typeof e.license_key_instance_id=="string"||e.license_key_instance_id===null)}var Lu="https://api.dodopayments.com",Du=1440*60*1e3,Hu=14;async function Wo(e){let t=p(e.home).home,r=e.now??new Date,o=await Ne(t),a=e.key??o?.license_key,n=o?.instance_id??null;if(!a)return await Rt(t,"license_validate_missing",null,"INVALID_KEY","blocked"),{ok:!1,reason:"INVALID_KEY",license:o?mr(o):Oe};if(o?.state==="licensed"&&$u(o.last_checked_at,r))return await Rt(t,"license_validate_cache_hit",a,null,"ok"),{ok:!0,license:mr(o)};let s=await Uu(e,"/licenses/validate",{license_key:a});if(s.ok){let i=await pr(t,{state:"licensed",license_key:a,instance_id:n??await Go(t),license_key_instance_id:o?.license_key_instance_id??null,purchased_at:o?.purchased_at??null,version_at_activation:o?.version_at_activation??null,updates_until:o?.updates_until??null,last_checked_at:r.toISOString(),source:"dodo"});return await Rt(t,"license_validated",a,null,"ok"),{ok:!0,license:mr(i)}}return s.reason==="NETWORK"&&o?.state==="licensed"&&Fu(o.last_checked_at,r,e.graceDays)?(await Rt(t,"license_validate_grace_served",a,"NETWORK","ok"),{ok:!0,license:mr(o)}):(await Rt(t,"license_validate_failed",a,s.reason,"blocked"),{ok:!1,reason:s.reason,license:{...Oe,instance_id:n}})}function mr(e){return{state:e.state,license_key:e.license_key,instance_id:e.instance_id,purchased_at:e.purchased_at??null,version_at_activation:e.version_at_activation??null,updates_until:e.updates_until,last_checked_at:e.last_checked_at,source:e.source}}function $u(e,t){return e?t.getTime()-new Date(e).getTime()<Du:!1}function Fu(e,t,r=Hu){return e?t.getTime()-new Date(e).getTime()<=r*24*60*60*1e3:!1}async function Uu(e,t,r){let o=e.fetch??globalThis.fetch;try{let a=await o(new URL(t,Vu(e.endpointBaseUrl)).toString(),{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(r)}),n=await Bu(a);return a.ok?t==="/licenses/validate"&&n.valid!==!0?{ok:!1,reason:Ys(n)}:{ok:!0,license_key_instance_id:Ju(n),purchased_at:Ku(n)}:{ok:!1,reason:Ys(n)}}catch{return{ok:!1,reason:"NETWORK"}}}function Vu(e=process.env.NATIVESOUL_DODO_LICENSE_API_BASE_URL??Lu){return e.endsWith("/")?e:`${e}/`}async function Bu(e){try{let t=await e.json();return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Ju(e){let r=[e.license_key_instance_id,e.licenseKeyInstanceId,e.id,St(e.data)?e.data.license_key_instance_id:null,St(e.data)?e.data.id:null].find(o=>typeof o=="string"&&o.length>0);return typeof r=="string"?r:null}function Ku(e){let t=St(e.data)?e.data:{},r=St(e.license_key)?e.license_key:St(t.license_key)?t.license_key:{},a=[e.purchased_at,e.purchase_date,e.created_at,t.purchased_at,t.purchase_date,t.created_at,r.purchased_at,r.purchase_date,r.created_at].find(n=>typeof n=="string"&&!Number.isNaN(Date.parse(n)));return typeof a=="string"?new Date(a).toISOString():null}function Ys(e){let t=String(e.reason??e.code??e.error??"").toUpperCase();return t.includes("LIMIT")?"ACTIVATION_LIMIT":t.includes("ACTIVE")?"NOT_ACTIVE":"INVALID_KEY"}function St(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}async function Rt(e,t,r,o,a){await g({home:e,type:t,result:a,details:{provider:"dodo",license_key_ref:r?qu(r):null,reason:o}})}function qu(e){return e.length<=8?"[REDACTED_LICENSE_KEY]":`${e.slice(0,4)}\u2026${e.slice(-4)}`}var gr="https://native-soul.mintlify.site/account/licensing";async function fr(e){let t=Gu(e),r=p(t.home).home;try{let o=await Ne(r),a=await Wo(t);if(a.ok)return{ok:!0,license:a.license};let n=a.reason==="NETWORK"&&o?.state==="licensed"?"GRACE_EXPIRED":"UNLICENSED",s=t.activateUrl??gr;return{ok:!1,reason:n,activate_url:s,message:zo({reason:n,activate_url:s}),license:a.license}}catch{let o=t.activateUrl??gr;return{ok:!1,reason:"UNLICENSED",activate_url:o,message:zo({reason:"UNLICENSED",activate_url:o}),license:Oe}}}function zo(e){return`${e.reason==="GRACE_EXPIRED"?"License offline grace expired.":"NativeSoul is not activated."} NativeSoul is paid-only. Run \`nativesoul license activate <key>\` after purchase: ${e.activate_url}`}function Gu(e){return typeof e=="string"?{home:e}:e??{}}import{readdir as QR,readFile as ZR,stat as eS}from"node:fs/promises";import rS from"node:path";import{copyFile as cS,mkdir as lS,readFile as Wu,rename as dS,stat as zu,writeFile as uS}from"node:fs/promises";import{existsSync as Xu}from"node:fs";import Qs from"node:path";async function Xo(e){let t=p(e.home),r=Zs(t.home,e.host);if(!Xu(r))return Yu({home:t.home,host:e.host,targetPath:r,recordTelemetry:e.recordTelemetry});let o=await Wu(r,"utf8"),a=await zu(r),n=e.ttlDays??7,s=Date.now()-a.mtimeMs>n*24*60*60*1e3,i=new Date().toISOString(),c=s?["BOOTSTRAP_CACHE_STALE"]:[],l=["---","nativesoul: bootstrap-context-cache",`host: ${e.host}`,`generated_at: ${i}`,"degraded: true",c.length>0?`warnings: ${c.join(", ")}`:"warnings: none","---","",o].join(`
778
- `),u={host:e.host,generated_at:i,degraded:!0,warnings:c,tokens_used:ti(l),tokens_max:1900,content:l,targetPath:r,stale:s};if(e.recordTelemetry!==!1){await g({home:t.home,type:"bootstrap_context_cache_read",details:{...u,content:"[omitted]"}});let d=Qu(o);await Ie({home:t.home,host:e.host,outcome:"degraded",tier:"D",cwd:d.cwd,project:d.project,tokensUsed:u.tokens_used,tokensMax:u.tokens_max,source:"bootstrap-cache",warnings:c})}return u}async function Yo(e){let t=await Xo({home:e.home,host:e.host,ttlDays:e.ttlDays,recordTelemetry:e.recordTelemetry});if(!t.warnings.includes("BOOTSTRAP_CACHE_MISSING")||!e.projectCwd)return t;let r=await Xo({home:ei(e.projectCwd),host:e.host,ttlDays:e.ttlDays,recordTelemetry:!1});return r.warnings.includes("BOOTSTRAP_CACHE_MISSING")?t:r}function Zs(e,t){return Qs.join(e,"generated",t,"last-context.md")}function ei(e){return Qs.join(e,".nativesoul-cache")}async function Yu(e){let t=new Date().toISOString(),r=["BOOTSTRAP_CACHE_MISSING"],o=["---","nativesoul: bootstrap-context-cache",`host: ${e.host}`,`generated_at: ${t}`,"degraded: true",`warnings: ${r.join(", ")}`,"---","","Bootstrap context cache is not available. Run `nativesoul bootstrap --format inject` after install."].join(`
779
- `),a={host:e.host,generated_at:t,degraded:!0,warnings:r,tokens_used:ti(o),tokens_max:1900,content:o,targetPath:e.targetPath,stale:!1};return e.recordTelemetry!==!1&&(await g({home:e.home,type:"bootstrap_context_cache_missing",details:{...a,content:"[omitted]"}}),await Ie({home:e.home,host:e.host,outcome:"degraded",tier:"D",cwd:null,project:null,tokensUsed:a.tokens_used,tokensMax:a.tokens_max,source:"bootstrap-cache",warnings:r})),a}function ti(e){return Math.ceil(e.length/4)}function Qu(e){let t=e.match(/^- CWD:\s*(.+)$/mu)?.[1]?.trim()??null,r=e.match(/^- ID:\s*(.+)$/mu)?.[1]?.trim()??null;return{cwd:t,project:r}}import{readdir as VS,readFile as BS}from"node:fs/promises";import KS from"node:path";import{mkdir as AS,readdir as tp,readFile as rp,writeFile as ES}from"node:fs/promises";import kt from"node:path";var op=new Set(["SOUL.MD","POLICY.MD"]),ap=5e3,ri=new Map;async function wt(e){let t=p(e),r=ri.get(t.home);if(r&&r.expiresAt>Date.now())return r.orders;let o=kt.join(t.home,"standing-orders"),a;try{a=await tp(o)}catch{return[]}let n=[];for(let s of a.filter(i=>i.endsWith(".yaml")||i.endsWith(".yml")).sort()){let i=kt.join(o,s),c=await rp(i,"utf8");n.push(np(c,i))}return ri.set(t.home,{expiresAt:Date.now()+ap,orders:n}),n}async function At(e){let t=await wt(e.home),r=e.target??null,o=r?sp(r):null,a=t.filter(i=>Qo(i,e)),n=a.find(i=>i.allowed.includes(e.action)),s=a.find(i=>i.approval_required.includes(e.action));if(o&&op.has(o))return Re(e,"proposal_required",["PROTECTED_HUMAN_FILE"],null);if(e.className==="identity_policy_change")return Re(e,"proposal_required",["IDENTITY_POLICY_CHANGE"],null);if(e.className==="destructive")return Re(e,"denied",["DESTRUCTIVE_DENIED_BY_DEFAULT"],n?.id??s?.id??null);if(s)return Re(e,"approval_required",["STANDING_ORDER_REQUIRES_APPROVAL"],s.id);if(n)return Re(e,"allowed",["STANDING_ORDER_ALLOWED"],n.id);switch(e.className){case"read_local":case"probe_external":case"write_local":return Re(e,"allowed",["DEFAULT_ALLOWED"],null);case"write_project":return Re(e,"approval_required",["PROJECT_WRITE_REQUIRES_APPROVAL"],null);case"external_write":return Re(e,"approval_required",["EXTERNAL_WRITE_REQUIRES_APPROVAL"],null)}}function Re(e,t,r,o){return{action:e.action,class:e.className,target:e.target??null,decision:t,reasons:r,matched_standing_order:o}}function np(e,t){return{id:ip(e,"id")??kt.basename(t,kt.extname(t)),allowed:qe(e,"allowed"),approval_required:qe(e,"approval_required"),scope_projects:qe(e,"projects").concat(qe(e,"scope_projects")),scope_hosts:qe(e,"hosts").concat(qe(e,"scope_hosts")),source:t}}function Qo(e,t){return!(e.scope_projects.length>0&&(!t.project||!e.scope_projects.includes(t.project))||e.scope_hosts.length>0&&(!t.host||!e.scope_hosts.includes(t.host)))}function sp(e){return kt.basename(e.replaceAll("\\","/")).toUpperCase()}function ip(e,t){let r=new RegExp(`^\\s*${t}:\\s*([^\\n#]+)`,"mu");return e.match(r)?.[1]?.trim().replace(/^["']|["']$/gu,"")??null}function qe(e,t){let r=e.match(new RegExp(`^\\s*${t}:\\s*\\[([^\\]]*)\\]`,"mu"));if(r?.[1])return r[1].split(",").map(i=>i.trim().replace(/^["']|["']$/gu,"")).filter(Boolean);let o=e.split(/\r?\n/u),a=[],n=!1,s=0;for(let i of o){let c=i.trim();if(!n){let u=i.match(new RegExp(`^(\\s*)${t}:\\s*$`,"u"));u&&(n=!0,s=u[1]?.length??0);continue}let l=i.length-i.trimStart().length;if(c&&l<=s&&!c.startsWith("-"))break;c.startsWith("-")&&a.push(c.slice(1).trim().replace(/^["']|["']$/gu,""))}return a.filter(Boolean)}import{mkdir as ek,writeFile as tk}from"node:fs/promises";import ok from"node:path";import{readFile as mp}from"node:fs/promises";import gp from"node:path";var hr=1500;async function ea(e){let t=await b(e.home),r=await hp(t.home),o=new Date,a=fp(e.ttlSeconds??r.ttlSeconds),n=new Date(o.getTime()+a*1e3).toISOString(),s=ra(e.project,e.slot),i=h(t.database),c;try{c=i.claimHeartbeatLease({id:P("lease"),slot:e.slot,holder:e.host,idempotencyKey:s,now:o.toISOString(),expiresAt:n})}finally{i.close()}return await g({home:t.home,type:c.claimed?"heartbeat_claimed":"heartbeat_skipped",details:{slot:e.slot,host:e.host,project:e.project,lease_id:c.lease.id,reason:c.reason}}),{slot:e.slot,host:e.host,project:e.project,claimed:c.claimed,reason:c.reason,silent_ack:c.claimed||c.reason==="LEASE_OCCUPIED"&&!r.skipWhenBusy?null:"HEARTBEAT_OK",lease:c.lease}}async function ta(e){let t=await b(e.home),r=new Date().toISOString(),o=ra(e.project,e.slot),a=K(e.result??"HEARTBEAT_OK"),n=K(e.evidence??{}),s=h(t.database),i;try{i=s.completeHeartbeatLease({idempotencyKey:o,host:e.host,project:e.project,result:a,evidence:n,completedAt:r,runId:P("run")})}finally{s.close()}return await g({home:t.home,type:i.completed?"heartbeat_completed":"heartbeat_completion_replayed",details:{slot:e.slot,host:e.host,project:e.project,lease_id:i.lease.id,run_id:i.run?.id??null}}),{slot:e.slot,project:e.project,completed:i.completed,silent_ack:"HEARTBEAT_OK",lease:i.lease,run:i.run}}function ra(e,t){return`heartbeat:${e}:${t}`}function fp(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),1440*60):hr}async function hp(e){let t;try{t=await mp(gp.join(e,"config.yaml"),"utf8")}catch{return{ttlSeconds:hr,skipWhenBusy:!0}}return{ttlSeconds:yp(t),skipWhenBusy:_p(t,"skip_when_busy",!0)}}function yp(e){let t=Zo(e,"ttl_seconds"),r=Zo(e,"lease_ttl"),o=bp(e,"heartbeat_ttl_seconds"),a=vp(t??r??o);return Number.isFinite(a)?a:hr}function _p(e,t,r){let o=Zo(e,t);return o?/^(true|yes|1)$/i.test(o)?!0:/^(false|no|0)$/i.test(o)?!1:r:r}function Zo(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.match(new RegExp(`^\\s*heartbeat:\\s*$[\\s\\S]*?^\\s{2}${r}:\\s*([^#\\n]+)`,"mu"))?.[1]?.trim().replace(/^["']|["']$/g,"")??null}function bp(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.match(new RegExp(`^\\s*${r}:\\s*([^#\\n]+)`,"mu"))?.[1]?.trim().replace(/^["']|["']$/g,"")??null}function vp(e){if(!e)return hr;let t=e.match(/^(\d+)$/);if(t)return Number(t[1]);let r=e.match(/^(\d+)\s*([smh])$/i);if(!r)return Number.NaN;let o=Number(r[1]),a=r[2]?.toLowerCase();return a==="s"?o:a==="m"?o*60:o*60*60}import xk from"node:path";import{rm as jk}from"node:fs/promises";async function aa(e){let t=p(e.home),r=h(t.database),o;try{let a=r.findPendingApprovalMatch(oa(e));if(!a.available)return{approval:null,created:!1,available:!1,warning:a.warning};if(a.approval)return{approval:a.approval,created:!1,available:!0,warning:null};let n=r.createApproval({id:P("approval"),...oa(e)});o={approval:n.approval,created:!!n.approval,available:n.available,warning:n.warning}}finally{r.close()}return o.created&&o.approval&&await g({home:t.home,type:"approval_requested",details:ia(o.approval)}),o}async function na(e){let t=p(e.home),r=h(t.database),o;try{let a=r.decideApproval(e.id,{status:e.status,reviewer:e.reviewer??"local-operator",reason:e.reason??null});o={approval:a.approval,available:a.available,warning:a.warning}}catch(a){throw a instanceof oe,a}finally{r.close()}return o.approval&&await g({home:t.home,type:o.approval.status==="approved"?"approval_approved":"approval_rejected",details:ia(o.approval)}),o}async function sa(e){let t=p(e.home),r=h(t.database),o;try{let a=r.createDecidedApproval({id:P("approval"),...oa(e),status:"approved",reviewer:`standing-order:${e.standingOrderId}`,reason:e.reason});o={approval:a.approval,available:a.available,warning:a.warning,created:!!a.approval}}finally{r.close()}return o.approval&&await g({home:t.home,type:"approval_auto_approved",details:{...ia(o.approval),standing_order:e.standingOrderId}}),o}function oa(e){return{action:e.action,class:e.class,target:e.target??null,project:e.project??null,host:e.host??null}}function ia(e){return{id:e.id,action:e.action,class:e.class,target:e.target,project:e.project,host:e.host,status:e.status,reviewer:e.reviewer,reason:e.reason}}async function ca(e){let t=await At(e),r=await Tp(e,t);if(r){let a=await sa({home:e.home,action:t.action,class:t.class,target:t.target,project:e.project??null,host:e.host??null,standingOrderId:r.id,reason:`standing-order allowed:${t.action}`});return{evaluation:t,approval:a.approval,approval_created:a.created,approval_available:a.available,warning:a.warning}}if(t.decision!=="approval_required")return{evaluation:t,approval:null,approval_created:!1,approval_available:!0,warning:null};let o=await aa({home:e.home,action:t.action,class:t.class,target:t.target,project:e.project??null,host:e.host??null});return{evaluation:t,approval:o.approval,approval_created:o.created,approval_available:o.available,warning:o.warning}}async function Tp(e,t){return t.decision!=="allowed"||!t.matched_standing_order||!jp(e.className)?null:(await wt(e.home)).find(o=>o.id===t.matched_standing_order&&o.allowed.includes(e.action)&&Qo(o,e))??null}function jp(e){return e==="write_project"||e==="external_write"}import{existsSync as mw}from"node:fs";import{mkdir as fw,readFile as hw,rm as yw,writeFile as _w}from"node:fs/promises";import vw from"node:path";import{existsSync as rw}from"node:fs";import{readdir as aw,readFile as nw}from"node:fs/promises";import iw from"node:path";import{fileURLToPath as lw}from"node:url";import Xk from"node:path";var ni=["AGENTS.md","CLAUDE.md","GEMINI.md","Agents.md",".claude/CLAUDE.md"],Yk=new Set(ni);import Ip from"node:path";async function yr(e={}){let t=p(e.home),r=e.host??"all",[o,a,n,s]=await Promise.all([Be(t.home),y(nr(t.home)),y(lt(t.home)),vt({home:t.home,host:r,surface:e.surface,targetRoot:e.targetRoot})]);return So({home:t.home,targetRoot:e.targetRoot?Ip.resolve(e.targetRoot):null,host:r,profile:o,onboardingComplete:a,activationComplete:n,hosts:s.hosts})}async function la(e={}){let t=await yr(e);if(!e.profile||t.profile?.profile===e.profile)return t;let r={...t.profile??Ro,profile:e.profile,updated_at:t.profile?.updated_at??"dry-run"};return{...t,profile:r,plan:[{id:"activation-profile-switch",component:"bootstrap",status:"approval_required",action:`Switch activation profile to ${e.profile}.`,target:`${t.home}/state/activation-profile.json`,dry_run:!0,requires_user_confirmed:!0,reason:"Activation profile replacement requires explicit reset/user confirmation."},...t.plan]}}import{randomUUID as Op}from"node:crypto";import Np from"node:path";var Mp="NativeSoul activation verification marker";async function ua(e={}){let t=$p(e),r=pe(t.projectCwd,e.home),o=await vt({home:e.home,host:e.host??"all",surface:e.surface,targetRoot:e.targetRoot}),a=[];for(let l of o.hosts)a.push(await Lp({home:o.home,inputHost:l,testCwd:t.projectCwd}));let n=await Hp({home:e.home,testProject:`${r.id}-${Op()}`,apply:e.apply===!0,userConfirmed:e.userConfirmed===!0,retainTestData:e.retainTestData===!0}),s=[...new Set([...a.flatMap(l=>l.recommendations),...n.status==="failed"?["Review memory persistence and rerun verification."]:[]])],i=a.map(l=>l.status),c=Up(i,n.status);return{schema_version:1,home:o.home,target_root:o.target_root,host:e.host??"all",surface:e.surface??null,project:{requested_cwd:t.projectCwd,normalized:r.id,source:r.source,git_root:r.git_root,remote:r.remote,alias_key:r.alias_key},overall_status:c,memory_recall:n,hosts:a,recommendations:s}}async function Lp(e){let t=[],r=await Dp({home:e.home,host:e.inputHost.host,cwd:e.testCwd,warnings:e.inputHost.handshake.last?.warnings??[]});e.inputHost.mcp_registration.configured||t.push(`Install MCP registration for ${e.inputHost.host}: nativesoul mcp install --host ${e.inputHost.host} --apply --json`),r.status!=="ready"&&t.push(`Regenerate bootstrap context for ${e.inputHost.host}: nativesoul bootstrap --host ${e.inputHost.host} --cwd ${e.testCwd} --format inject --json`);let o=Fp(e.inputHost.provider_parity.heartbeat),a=[...e.inputHost.full_native_evidence.missing_requirements];o==="unsupported"&&(a.includes("native_scheduler")||a.push("native_scheduler"),t.push(`Choose a host with native scheduler support or configure external scheduler workflow for ${e.inputHost.host}.`));let s=e.inputHost.provider_parity.heartbeat==="unsupported-native"&&e.inputHost.host!=="codex"?"blocked_by_host":r.status==="failed"||r.status==="degraded"||r.cache.status==="degraded"||r.cache.status==="missing"||!e.inputHost.plugin.enabled?"degraded":"ready";return{host:e.inputHost.host,surface:e.inputHost.surface,status:s,mcp:{configured:e.inputHost.mcp_registration.configured,issues:e.inputHost.mcp_registration.issues.map(i=>i.message)},bootstrap:r,heartbeat:{status:o,requirements:a},recommendations:t}}async function Dp(e){let t=[...e.warnings],r=[],o="ready",a=!1,n="",s="ready";try{let i=await ct({home:e.home,host:e.host,cwd:e.cwd,readOnly:!0});t.push(...i.warnings),i.warnings.some(c=>c.startsWith("HOST_ADAPTER_UNAVAILABLE")||c==="PROJECT_MEMORY_EMPTY")&&(s="degraded")}catch(i){t.push(`bootstrap_injection_failed:${da(i)}`),s="failed"}try{let i=await Yo({home:e.home,host:e.host,projectCwd:e.cwd,recordTelemetry:!1});n=i.targetPath,a=i.stale,r.push(...i.warnings),r.length>0&&(o=i.warnings.some(c=>c==="BOOTSTRAP_CACHE_MISSING")?"missing":"degraded",s==="ready"&&(s="degraded"))}catch{r.push("bootstrap_cache_check_failed"),o="missing",s==="ready"&&(s="degraded")}return{status:s,warnings:t,cache:{status:o,warnings:r,targetPath:n,stale:a}}}async function Hp(e){let t=[],r=null,o=!1,a=!1;try{let n=`verify-${e.testProject}`,s=`${Mp} ${e.testProject}`;r=await ye(e.home,{project:n,content:s,confidence:.91,source:{host:"activation-verification",session_id:`verification-${e.testProject}`}});let i=await it(e.home,s,n,8),c=await tr({home:e.home,project:n,status:"candidate",limit:8}),l=i.some(u=>u.id===r?.id)||c.some(u=>u.id===r?.id);if(e.apply&&e.userConfirmed&&r){let u=await at(e.home,r.id);r=u,a=r.id===u.id&&r.status==="active"}if(!e.retainTestData&&r)try{r.status==="candidate"?await nt(e.home,r.id):await st(e.home,r.id),o=!0}catch(u){t.push(`memory_cleanup_failed:${da(u)}`)}return{test_project:e.testProject,candidate_id:r?.id??"",candidate_status:r?.status??"candidate",recalled:l,promoted:a,status:l?"passed":"failed",warnings:t,cleanup_performed:o}}catch(n){return t.push(`memory_recall_check_failed:${da(n)}`),{test_project:e.testProject,candidate_id:r?.id??"",candidate_status:r?.status??"candidate",recalled:!1,promoted:!1,status:"failed",warnings:t,cleanup_performed:!1}}}function $p(e){return{projectCwd:Np.resolve(e.projectCwd??process.cwd())}}function Fp(e){return e==="native"?"native":e==="official-fallback"?"official_fallback":"unsupported"}function Up(e,t){return e.includes("blocked_by_host")?"blocked_by_host":e.includes("degraded")||t==="failed"?"degraded":e.length>0?"ready":"degraded"}function da(e){return e instanceof Error?e.message:String(e)}function ii(e){let t=p(e);if(!Vp(t.database))return{home:t.home,initialized:!1,database:t.database,migrations:0,memories:0,events:0,capabilities:0,ledger:Bp()};let r=h(t.database,{readOnly:!0});try{return{home:t.home,initialized:!0,database:t.database,...r.counts()}}finally{r.close()}}function Bp(){return{hosts:0,sessions:0,memory_edges:0,commitments:0,standing_orders:0,capability_sources:0,capability_experience:0,schedules:0,leases:0,runs:0}}var ci={life_activation_status:async(e,t)=>await yr({home:t,host:pa(e.host),targetRoot:Se(e.target_root)??Se(e.targetRoot)}),life_activation_plan:async(e,t)=>await la({home:t,host:pa(e.host),targetRoot:Se(e.target_root)??Se(e.targetRoot),profile:Jp(e.profile)}),life_activation_verify:async(e,t)=>await ua({home:t,host:pa(e.host),surface:Kp(e.surface),targetRoot:Se(e.target_root)??Se(e.targetRoot),projectCwd:Se(e.project_cwd)??Se(e.projectCwd),apply:ma(e.apply),userConfirmed:ma(e["user-confirmed"]),retainTestData:ma(e["retain-test-data"])})},li=[{name:"life_activation_status",description:"Return activation status by component, including bootstrap, MCP, plugins/hooks, heartbeat, recall, memory, and cross-host verification.",inputSchema:{type:"object",properties:{host:{type:"string"},target_root:{type:"string"},targetRoot:{type:"string"}}}},{name:"life_activation_plan",description:"Return a read-only dry-run activation plan with exact files, settings, scheduler actions, and approvals.",inputSchema:{type:"object",properties:{host:{type:"string"},profile:{type:"string"},target_root:{type:"string"},targetRoot:{type:"string"}}}},{name:"life_activation_verify",description:"Run cross-host activation verification for bootstrap cache, MCP, scheduler evidence, and memory recall.",inputSchema:{type:"object",properties:{host:{type:"string"},surface:{type:"string"},project_cwd:{type:"string"},projectCwd:{type:"string"},target_root:{type:"string"},targetRoot:{type:"string"},apply:{type:"boolean"},"user-confirmed":{type:"boolean"},"retain-test-data":{type:"boolean"}}}}];function pa(e){if(e===void 0)return"all";if(e==="all"||e==="codex"||e==="claude"||e==="grok"||e==="antigravity"||e==="gemini")return e;throw new Error("Invalid activation host")}function Jp(e){if(e!==void 0){if(e==="quickstart"||e==="advanced")return e;throw new Error("Invalid activation profile")}}function Kp(e){if(e!==void 0){if(e==="desktop"||e==="claude-desktop")return"claude-desktop";if(e==="claude-code")return"claude-code";throw new Error("activation verify surface must be claude-code, desktop, or claude-desktop")}}function Se(e){return typeof e=="string"?e:void 0}function ma(e){return e===!0}var qp=["2025-11-25","2024-11-05","2024-10-07"],pi={...ci,life_status:(e,t)=>ii(t),life_bootstrap:async(e,t)=>await Qp({home:t,host:A(e.host,"codex"),cwd:A(e.cwd,process.cwd()),query:ce(e.query)}),life_recall:async(e,t)=>await it(t,A(e.query,""),A(e.project,"default"),ga(e.limit,5)),life_remember_propose:async(e,t)=>await ye(t,{project:A(e.project,"default"),content:A(e.content,""),type:ce(e.type),confidence:di(e.confidence),source:{host:"mcp",session_id:"local"}}),life_memory_promote:async(e,t)=>await at(t,A(e.id,"")),life_memory_reject:async(e,t)=>await nt(t,A(e.id,"")),life_memory_forget:async(e,t)=>await st(t,A(e.id,"")),life_memory_expire:async(e,t)=>await yo(t,A(e.id,"")),life_capability_search:async(e,t)=>await co({home:t,query:A(e.query,""),host:em(e)?void 0:ce(e.host)??"codex",readyOnly:Ge(e.readyOnly,!1),limit:ga(e.limit,8)}),life_capability_status:async(e,t)=>{let r=A(e.uid,""),o=r?await lo({home:t,uid:r}):null;if(!o)throw new Error(`Capability not found: ${r}`);return o},life_policy_evaluate:async(e,t)=>await At({home:t,action:A(e.action,""),className:ui(e.class),target:ce(e.target)}),life_approval_request:async(e,t)=>await am({home:t,action:A(e.action,""),className:ui(e.class),target:ce(e.target),project:ce(e.project),host:ce(e.host)}),life_approval_decide:async(e,t)=>{let r=A(e.id,""),o=await na({home:t,id:r,status:om(e.status),reviewer:A(e.host,"mcp"),reason:ce(e.reason)??null});if(!o.approval)throw new Error(`Approval not found: ${r}`);return o},life_commitment_create:async(e,t)=>await po({home:t,project:A(e.project,"default"),summary:A(e.summary,""),dueAt:ce(e.due_at),ttlSeconds:di(e.ttl_seconds),source:{host:"mcp",session_id:"local"}}),life_commitment_complete:async(e,t)=>await go(t,A(e.id,"")),life_heartbeat_claim:async(e,t)=>await ea({home:t,slot:A(e.slot,""),host:A(e.host,"codex"),project:A(e.project,"default"),ttlSeconds:ga(e.ttl_seconds,1500)}),life_heartbeat_complete:async(e,t)=>await ta({home:t,slot:A(e.slot,""),host:A(e.host,"codex"),project:A(e.project,"default"),result:e.result??"HEARTBEAT_OK",evidence:e.evidence??{}}),life_onboarding_status:async(e,t)=>await wo(t),life_onboard_apply:async(e,t)=>await Ao({home:t,dry_run:Ge(e.dry_run,!0),user_confirmed:Ge(e.user_confirmed,!1),files:tm(e.files),config_patch:rm(e.config_patch)}),life_onboard_complete:async(e,t)=>await Eo({home:t,archive:e.archive===void 0?!0:Ge(e.archive,!0)})},Gp=new Set(Object.keys(pi));function Wp(e){return e.method?.startsWith("notifications/")?!0:!Object.prototype.hasOwnProperty.call(e,"id")}async function zp(e,t){if(Wp(e))return null;let r=e.id??null;try{if(e.method==="initialize"){let o=Et(e.params),a=ce(o.protocolVersion),n=a&&qp.includes(a)?a:"2024-11-05";return ge(r,{protocolVersion:n,serverInfo:{name:"nativesoul",version:"0.1.0"},capabilities:{tools:{}}})}if(e.method==="ping")return ge(r,{});if(e.method==="resources/list")return ge(r,{resources:[]});if(e.method==="prompts/list")return ge(r,{prompts:[]});if(e.method==="tools/list")return ge(r,{tools:[{name:"life_status",description:"Return local NativeSoul health and counts.",inputSchema:{type:"object"}},{name:"life_bootstrap",description:"Return compact bootstrap context for a host and cwd.",inputSchema:{type:"object",required:["host","cwd"],properties:{host:{type:"string"},cwd:{type:"string"},query:{type:"string"}}}},{name:"life_recall",description:"Search project-scoped memory.",inputSchema:{type:"object",required:["query","project"],properties:{query:{type:"string"},project:{type:"string"},limit:{type:"number"}}}},{name:"life_remember_propose",description:"Create a redacted local candidate memory for a project.",inputSchema:{type:"object",required:["project","content"],properties:{project:{type:"string"},content:{type:"string"},type:{type:"string"},confidence:{type:"number"}}}},{name:"life_memory_promote",description:"Promote a candidate memory to active status.",inputSchema:{type:"object",required:["id"],properties:{id:{type:"string"}}}},{name:"life_memory_reject",description:"Reject a candidate memory.",inputSchema:{type:"object",required:["id"],properties:{id:{type:"string"}}}},{name:"life_memory_forget",description:"Forget an active memory.",inputSchema:{type:"object",required:["id"],properties:{id:{type:"string"}}}},{name:"life_memory_expire",description:"Expire an active memory.",inputSchema:{type:"object",required:["id"],properties:{id:{type:"string"}}}},{name:"life_capability_search",description:"Search persisted local capability records.",inputSchema:{type:"object",required:["query"],properties:{query:{type:"string"},host:{type:"string"},allHosts:{type:"boolean"},all_hosts:{type:"boolean"},readyOnly:{type:"boolean"},limit:{type:"number"}}}},{name:"life_capability_status",description:"Return one persisted capability record by uid.",inputSchema:{type:"object",required:["uid"],properties:{uid:{type:"string"}}}},{name:"life_policy_evaluate",description:"Evaluate a proposed action against local policy and standing orders.",inputSchema:{type:"object",required:["action","class"],properties:{action:{type:"string"},class:{type:"string"},target:{type:"string"}}}},{name:"life_approval_request",description:"Request approval for a sensitive action. If blocked, stop and return control to the human; there is no server or polling in this turn-based protocol.",inputSchema:{type:"object",required:["action","class"],properties:{action:{type:"string"},class:{type:"string"},target:{type:"string"},project:{type:"string"},host:{type:"string"}}}},{name:"life_approval_decide",description:"Record a human-driven approval decision. Acting agents must not self-approve; use this only from a human-operated host turn.",inputSchema:{type:"object",required:["id","status"],properties:{id:{type:"string"},status:{type:"string",enum:["approved","rejected"]},reason:{type:"string"},host:{type:"string"}}}},{name:"life_commitment_create",description:"Create a local project-scoped commitment with optional TTL.",inputSchema:{type:"object",required:["project","summary"],properties:{project:{type:"string"},summary:{type:"string"},due_at:{type:"string"},ttl_seconds:{type:"number"}}}},{name:"life_commitment_complete",description:"Complete a local commitment by id.",inputSchema:{type:"object",required:["id"],properties:{id:{type:"string"}}}},{name:"life_heartbeat_claim",description:"Claim a local heartbeat lease for a project and slot.",inputSchema:{type:"object",required:["slot","host","project"],properties:{slot:{type:"string"},host:{type:"string"},project:{type:"string"},ttl_seconds:{type:"number"}}}},{name:"life_heartbeat_complete",description:"Complete a local heartbeat lease and record a run.",inputSchema:{type:"object",required:["slot","host","project"],properties:{slot:{type:"string"},host:{type:"string"},project:{type:"string"},result:{type:"string"},evidence:{type:"object"}}}},{name:"life_onboarding_status",description:"Return onboarding ritual status, interview themes, and file_generation_rules (IDENTITY/SOUL/USER/AGENTS formats). Call before drafting files.",inputSchema:{type:"object"}},...li,{name:"life_onboard_apply",description:"Dry-run or apply AI-generated onboarding human files.",inputSchema:{type:"object",required:["files"],properties:{dry_run:{type:"boolean"},user_confirmed:{type:"boolean"},files:{type:"object"},config_patch:{type:"object"}}}},{name:"life_onboard_complete",description:"Archive BOOTSTRAP.md and mark onboarding ritual complete.",inputSchema:{type:"object",properties:{archive:{type:"boolean"}}}}]});if(e.method==="tools/call"){let o=await fr(t);if(!o.ok)return ge(r,o);let a=Zp(e.params);return ge(r,await Yp(a.name??"",a.arguments??{},t))}if(Gp.has(e.method)){let o=await fr(t);return o.ok?ge(r,await gi(e.method,Et(e.params),t)):ge(r,o)}return _r(r,-32601,`Unknown method: ${e.method}`)}catch(o){return o instanceof xe?_r(r,-32010,o.message,{code:o.code,id:o.id,from:o.from,to:o.to}):o instanceof oe?_r(r,-32011,o.message,{code:o.code,id:o.id,status:o.status}):_r(r,-32603,o instanceof Error?o.message:"Unknown MCP error")}}async function mi(e){let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",r=>{t+=r;let o=t.split(/\r?\n/u);t=o.pop()??"";for(let a of o){let n=a.trim();n&&Xp(n,e).catch(s=>{process.stderr.write(`NativeSoul MCP response error: ${nm(s)}
780
- `)})}})}async function Xp(e,t){let r;try{r=JSON.parse(e)}catch{process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}
781
- `);return}let o=await zp(r,t);o&&process.stdout.write(`${JSON.stringify(o)}
782
- `)}async function Yp(e,t,r){let o=await gi(e,t,r);return{content:[{type:"text",text:JSON.stringify(o)}]}}async function gi(e,t,r){let o=pi[e];if(!o)throw new Error(`Unknown tool: ${e}`);return await o(t,r)}async function Qp(e){try{let t=await ct({...e,readOnly:!0});try{await Ie({home:e.home,host:e.host,outcome:"succeeded",tier:"B",cwd:t.project.cwd,project:t.project.id,tokensUsed:t.context_budget.tokens_used,tokensMax:t.context_budget.tokens_max,source:"mcp-life-bootstrap",warnings:t.warnings})}catch{}return t}catch(t){try{await Ie({home:e.home,host:e.host,outcome:"failed",tier:"B",cwd:e.cwd,project:null,source:"mcp-life-bootstrap",error:t})}catch{}throw t}}function ge(e,t){return{jsonrpc:"2.0",id:e,result:t}}function _r(e,t,r,o){return{jsonrpc:"2.0",id:e,error:o===void 0?{code:t,message:r}:{code:t,message:r,data:o}}}function Zp(e){return Et(e)}function Et(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function A(e,t){return typeof e=="string"?e:t}function ce(e){return typeof e=="string"?e:void 0}function ga(e,t){return typeof e=="number"?e:t}function di(e){return typeof e=="number"?e:void 0}function Ge(e,t){return typeof e=="boolean"?e:t}function em(e){return Ge(e.allHosts,!1)||Ge(e.all_hosts,!1)}function tm(e){let t=Et(e),r={};for(let[o,a]of Object.entries(t))typeof a=="string"&&(r[o]=a);return r}function rm(e){let r=Et(e).hosts;if(!Array.isArray(r))return;let o=r.filter(a=>typeof a=="string");return o.length>0?{hosts:o}:void 0}function ui(e){if(e==="read_local"||e==="probe_external"||e==="write_local"||e==="write_project"||e==="external_write"||e==="destructive"||e==="identity_policy_change")return e;throw new Error("Invalid policy action class")}function om(e){if(e==="approved"||e==="rejected")return e;throw new Error("life_approval_decide status must be approved or rejected")}async function am(e){let t=await ca(e),r=t.approval?.id??null;return t.evaluation.decision==="approval_required"?{blocked:!0,allowed:!1,decision:"approval_required",approval_id:r,approval_created:t.approval_created,wait:"human",instruction:r?`approval ${r} pending - run: nativesoul approvals approve ${r} --confirm`:"approval pending but unavailable - inspect NativeSoul approval storage",warning:t.warning}:t.evaluation.decision==="allowed"?{blocked:!1,allowed:!0,decision:"allowed",approval_id:t.approval?.id??null,approval_status:t.approval?.status??null,warning:t.warning}:t.evaluation.decision==="proposal_required"?{blocked:!1,allowed:!1,decision:"proposal_required",approval_id:null,instruction:"use the existing SOUL.md/POLICY.md proposal flow; approvals do not cover protected human files",warning:t.warning}:{blocked:!1,allowed:!1,decision:"denied",approval_id:null,instruction:"stop; denied actions are not approvable through Approval Gate",warning:t.warning}}function nm(e){return e instanceof Error?e.message:"Unknown MCP response error"}var fi=process.argv.indexOf("--home"),sm=fi>=0?process.argv[fi+1]:void 0;await mi(sm);
838
+ `}function Su(e){let t=e.indexOf(vu),r=e.indexOf(oi);if(t<0||r<0||r<t)return null;let o=r+oi.length;return{before:e.slice(0,t),block:e.slice(t,o),after:e.slice(o)}}function ai(e,t){return t?Ba(e):wu()}function wu(){return{provider_id:"local-hash",model_id:"local-hash-bow-v1",schema_version:1,available:!1,indexable_count:0,indexed_count:0,stale_count:0,healthy:!1,remediation:"Run nativesoul init, then nativesoul memory index"}}function ii(e){return!e.available||e.stale_count===0?[]:[{code:"SEMANTIC_INDEX_STALE",severity:"warn",message:`${e.stale_count} memory record(s) need semantic indexing.`,remediation:e.remediation??"Run nativesoul memory index"}]}function ci(e){let t=new Map;for(let o of e){let n=t.get(o.host)??{capability_count:0,ready_capability_count:0};t.set(o.host,{capability_count:n.capability_count+1,ready_capability_count:n.ready_capability_count+(o.ready?1:0)})}let r=Array.from(t.entries()).map(([o,n])=>({host:o,...n}));return{host_count:r.length,capability_count:r.reduce((o,n)=>o+n.capability_count,0),ready_capability_count:r.reduce((o,n)=>o+n.ready_capability_count,0),hosts:r}}function lr(e){let t=f(e,{readOnly:!0});try{return t.listCapabilities({limit:1e4}).map(r=>({host:r.host,ready:r.ready}))}finally{t.close()}}import{existsSync as lp}from"node:fs";import{readFile as dp,stat as up}from"node:fs/promises";import Ai from"node:path";import{mkdir as Eu,readFile as Au,rename as Pu,writeFile as xu}from"node:fs/promises";import _t from"node:path";var Iu=1440*60*1e3;async function Le(e){let t=p(e.home),r=await Bo(t.home),o={host:e.host,outcome:e.outcome,tier:e.tier,cwd:e.cwd?_t.resolve(e.cwd):null,project:e.project??null,tokens_used:e.tokensUsed??null,tokens_max:e.tokensMax??null,source:e.source??"nativesoul",warnings:(e.warnings??[]).map(n=>N(n).value),error:Nu(e.error),recorded_at:e.recordedAt??new Date().toISOString()};return r.hosts[e.host]=o,await ju(t.home,r),await m({home:t.home,type:Cu(e.outcome),result:e.outcome==="failed"?"error":"ok",details:o}),o}async function Bo(e){let t=p(e),r=Jo(t.home);if(!await y(r))return Tu();let o=JSON.parse(await Au(r,"utf8"));return{schema:1,hosts:typeof o.hosts=="object"&&o.hosts!==null?o.hosts:{}}}async function Wo(e){let t=p(e.home),o=(await Bo(t.home)).hosts[e.host]??null,n=(e.now??new Date).getTime(),s=o?Date.parse(o.recorded_at):Number.NaN,a=Number.isFinite(s)?Math.max(n-s,0):null;return{state_path:Jo(t.home),last:o,age_ms:a,age_hours:a===null?null:Math.round(a/(3600*1e3)*10)/10,stale:a!==null&&a>Iu}}function Tu(){return{schema:1,hosts:{}}}async function ju(e,t){let r=Jo(e);await Eu(_t.dirname(r),{recursive:!0,mode:448});let o=_t.join(_t.dirname(r),`.last-handshake-${A("tmp")}.tmp`);await xu(o,`${JSON.stringify(t,null,2)}
839
+ `,{encoding:"utf8",mode:384}),await Pu(o,r)}function Jo(e){return _t.join(e,"state","last-handshake.json")}function Cu(e){return`handshake_${e}`}function Nu(e){if(e==null)return null;let t=e instanceof Error?e.message:String(e);return N(t).value.slice(0,500)}import kt from"node:path";import{existsSync as Av}from"node:fs";import{cp as xv,mkdir as Iv,rm as Tv}from"node:fs/promises";import Cv from"node:path";import{existsSync as Re}from"node:fs";import{readFile as fr}from"node:fs/promises";import ge from"node:path";import Ou from"node:path";function dr(e){return e.split(/[\\/]/u).join("/")}function bt(e,t){return dr(Ou.relative(e,t))}import{existsSync as li}from"node:fs";import Ko from"node:path";function qo(e){if(Ko.isAbsolute(e))return li(e)?e:null;let t=(process.env.PATH??"").split(Ko.delimiter).filter(Boolean),r=process.platform==="win32"?(process.env.PATHEXT??".EXE;.CMD;.BAT").split(";"):[""];for(let o of t)for(let n of r){let s=Ko.join(o,`${e}${n}`);if(li(s))return s}return null}import{spawnSync as cb}from"node:child_process";import{existsSync as mr}from"node:fs";import{mkdir as ub,readFile as gr,writeFile as pb}from"node:fs/promises";import Mu from"node:os";import me from"node:path";import{existsSync as tb}from"node:fs";import vt from"node:os";import ee from"node:path";import{fileURLToPath as sb}from"node:url";function ke(e,t,r){return ur(e,t)?r?ee.join(ee.resolve(r),e,"plugins","nativesoul"):e==="claude"?ee.join(vt.homedir(),".claude","plugins","nativesoul"):e==="codex"?ee.join(vt.homedir(),".codex","plugins","nativesoul"):e==="gemini"?ee.join(vt.homedir(),".gemini","extensions","nativesoul"):e==="grok"?ee.join(vt.homedir(),".grok","plugins","nativesoul"):e==="antigravity"?ee.join(vt.homedir(),".antigravity","plugins","nativesoul"):null:null}function ur(e,t){return e==="codex"||e==="gemini"||e==="grok"||e==="antigravity"||e==="claude"&&(t==="claude-code"||t==="claude-desktop")}function pr(e,t){return e==="claude"?ee.join(t,".claude-plugin","plugin.json"):e==="gemini"?ee.join(t,"gemini-extension.json"):e==="grok"||e==="antigravity"?ee.join(t,"plugin.json"):ee.join(t,".codex-plugin","plugin.json")}var di="nativesoul",ui="nativesoul";async function gi(e){let t=e?$u(e):me.join(Mu.homedir(),".grok","config.toml");if(!mr(t))return null;let r=await gr(t,"utf8");return pi(r,"disabled",di)?!1:pi(r,"enabled",di)?!0:null}async function fi(e){let t=Hu(e);if(!mr(t))return!1;let r=JSON.parse(await gr(t,"utf8"));return Lu(r)}async function hi(e){let t=yi(e),r=me.join(t,"agents",`${ui}.md`),o=me.join(t,"config.toml");if(!mr(r)||!mr(o))return!1;let[n,s]=await Promise.all([gr(r,"utf8"),gr(o,"utf8")]);return n.includes("NativeSoul continuity agent")&&Fu(s)===ui}function pi(e,t,r){let s=(e.match(/\[plugins\][\s\S]*?(?=\n\[|$)/u)?.[0]??e).match(new RegExp(`${t}\\s*=\\s*\\[([^\\]]*)\\]`,"u"))?.[1];return s?s.split(",").some(a=>a.replace(/["'\s]/gu,"")===r):!1}function Lu(e){let t=e.hooks;return!t||Array.isArray(t)||typeof t!="object"?!1:[["SessionStart","session-start --host grok"],["UserPromptSubmit","prompt-bootstrap --host grok"],["PreToolUse","pre-tool-use --host grok"],["Stop","memory-flush --host grok"],["PreCompact","memory-flush --host grok"]].every(([o,n])=>Du(t,o,n))}function Du(e,t,r){let o=e[t];return Array.isArray(o)?o.some(n=>Uu(n)?.includes(r)===!0):!1}function Hu(e){return me.join(yi(e),"hooks","nativesoul.json")}function yi(e){return me.resolve(e,"..","..")}function $u(e){let t=me.resolve(e),r=me.basename(t);return r==="grok"||r===".grok"?me.join(t,"config.toml"):me.join(t,".grok","config.toml")}function Fu(e){return e.match(/\[agent\][\s\S]*?(?=\n\[|$)/u)?.[0]?.match(/\bname\s*=\s*["']([^"']+)["']/u)?.[1]??null}function Uu(e){if(!e||Array.isArray(e)||typeof e!="object")return null;let t=e.hooks;if(!Array.isArray(t)||t.length===0)return null;let r=t[0];if(!r||Array.isArray(r)||typeof r!="object")return null;let o=r.command;return typeof o=="string"?o:null}import Vu from"node:path";var Go=[{event:"SessionStart",commandFragment:"hooks/session-start.cjs",fileName:"session-start.cjs"},{event:"PreToolUse",commandFragment:"hooks/pre-tool-use.cjs",fileName:"pre-tool-use.cjs"},{event:"Stop",commandFragment:"hooks/memory-flush.cjs",fileName:"memory-flush.cjs"},{event:"PreCompact",commandFragment:"hooks/memory-flush.cjs",fileName:"memory-flush.cjs"},{event:"UserPromptSubmit",commandFragment:"hooks/user-prompt-submit.cjs",fileName:"user-prompt-submit.cjs"}],Bu={grok:[{event:"SessionStart",commandFragment:"host-hook.cjs"},{event:"UserPromptSubmit",commandFragment:"prompt-bootstrap --host grok"},{event:"PreToolUse",commandFragment:"pre-tool-use --host grok"},{event:"Stop",commandFragment:"memory-flush --host grok"},{event:"PreCompact",commandFragment:"memory-flush --host grok"}],gemini:[{event:"SessionStart",commandFragment:"host-hook.cjs"},{event:"BeforeAgent",commandFragment:"prompt-bootstrap --host gemini"},{event:"BeforeTool",commandFragment:"pre-tool-use --host gemini"},{event:"AfterAgent",commandFragment:"memory-flush --host gemini"},{event:"PreCompress",commandFragment:"memory-flush --host gemini"}],antigravity:[{event:"SessionStart",commandFragment:"host-hook.cjs"},{event:"UserPromptSubmit",commandFragment:"prompt-bootstrap --host antigravity"},{event:"PreToolUse",commandFragment:"pre-tool-use --host antigravity"},{event:"Stop",commandFragment:"memory-flush --host antigravity"},{event:"PreCompact",commandFragment:"memory-flush --host antigravity"}]};function Xo(e,t){return e==="codex"||e==="claude"||e==="grok"||e==="antigravity"?{packageKind:"native-plugin",nativeHooksSupported:!0}:e==="gemini"?{packageKind:"official-extension",nativeHooksSupported:!0}:{packageKind:"unsupported-native",nativeHooksSupported:!1}}function Wu(e){return e==="grok"||e==="gemini"||e==="antigravity"?Bu[e]:Go}function zo(e){return e==="grok"||e==="gemini"?["hooks/hooks.json"]:e==="antigravity"?["hooks.json"]:[...new Set(Go.map(t=>t.fileName).filter(t=>!!t))].map(t=>Vu.join("hooks",t))}function _i(e,t){return t==="official-extension"?typeof e.name=="string"&&e.name==="nativesoul":typeof e.name=="string"&&e.name.includes("nativesoul")}function bi(e,t){return Yo(e,t).length===0}function Yo(e,t){return Wu(e).filter(({event:r,commandFragment:o})=>!Ju(t,r,o)).map(({event:r})=>r)}function Qo(e){return e==="claude"?[".claude-plugin/plugin.json"]:e==="codex"?[".mcp.json"]:e==="gemini"?["gemini-extension.json"]:e==="grok"?[".mcp.json"]:e==="antigravity"?["mcp_config.json"]:[]}function Zo(e){return e==="claude"?[".claude-plugin/plugin.json"]:e==="codex"?[".codex-plugin/plugin.json"]:e==="gemini"||e==="grok"?["hooks/hooks.json"]:e==="antigravity"?["hooks.json"]:[]}function Ju(e,t,r){if(!e.hooks||Array.isArray(e.hooks)||typeof e.hooks!="object")return!1;let n=e.hooks[t];return!Array.isArray(n)||n.length===0?!1:n.some(s=>{if(!s||Array.isArray(s)||typeof s!="object")return!1;let a=s.hooks;return!Array.isArray(a)||a.length===0?!1:a.some(i=>{if(!i||Array.isArray(i)||typeof i!="object")return!1;let c=i.command;return typeof c=="string"&&dr(c).includes(r)})})}async function Xe(e){if(!e.targetPath||!ur(e.host,e.surface))return{host:e.host,surface:e.surface,targetPath:e.targetPath,target_exists:!1,manifest_exists:!1,enabled:!1,hook_registered:!1,package_kind:"unsupported-native",native_hooks_supported:!1,native_scheduler_supported:!1,issues:[]};let t=Xo(e.host,e.surface),r=Re(e.targetPath),o=pr(e.host,e.targetPath),n=Re(o),s=t.nativeHooksSupported&&e.targetPath?zo(e.host).filter(re=>!Re(ge.join(e.targetPath,re))):zo(e.host),a=t.nativeHooksSupported?s.length===0:!0,i=[],c=!1,l=!t.nativeHooksSupported,u=e.host!=="grok";if(!r)i.push({code:"PLUGIN_NOT_INSTALLED",severity:"warn",message:`NativeSoul plugin is not installed for ${e.host}:${e.surface}.`,remediation:`Run nativesoul install --host ${e.host} --apply`});else if(!n)i.push({code:"PLUGIN_MANIFEST_MISSING",severity:"error",message:`NativeSoul plugin manifest is missing: ${o}`,remediation:"Reinstall the NativeSoul plugin"});else{let re=JSON.parse(await fr(o,"utf8")),$e=t.nativeHooksSupported?await Ku(e.host,e.targetPath,re):re;if(c=t.nativeHooksSupported?e.host==="grok"?await fi(e.targetPath):bi(e.host,$e):_i(re,t.packageKind),l=!t.nativeHooksSupported||await qu({host:e.host,targetPath:e.targetPath,manifest:re}),u=e.host==="grok"?await hi(e.targetPath):!0,e.host==="grok"&&!u&&i.push({code:"GROK_AGENT_PROFILE_MISSING",severity:"error",message:"NativeSoul Grok hooks are installed, but Grok is not configured to use the NativeSoul agent profile for first-turn bootstrap.",remediation:"Run `nativesoul install --host grok --apply` to install ~/.grok/agents/nativesoul.md and set [agent].name."}),t.nativeHooksSupported&&!l&&i.push({code:"PLUGIN_MCP_COMMAND_UNRESOLVED",severity:"error",message:"NativeSoul plugin MCP server command is not resolved for daemon-safe startup.",remediation:"Reinstall the NativeSoul plugin so its MCP server command is rendered with an absolute or executable command"}),!c&&t.nativeHooksSupported){let Ee=Yo(e.host,$e);i.push({code:"PLUGIN_HOOK_MISSING",severity:"error",message:Ee.length>0?`NativeSoul plugin manifest is missing required hook registrations: ${Ee.join(", ")}.`:"NativeSoul plugin manifest does not register required continuity hooks.",remediation:"Reinstall the NativeSoul plugin"})}!c&&!t.nativeHooksSupported&&i.push({code:"PLUGIN_PACKAGE_MANIFEST_INVALID",severity:"error",message:`NativeSoul ${t.packageKind} manifest is invalid for ${e.host}.`,remediation:"Reinstall the NativeSoul package"})}r&&t.nativeHooksSupported&&!a&&i.push({code:"PLUGIN_HOOK_FILE_MISSING",severity:"error",message:`NativeSoul required hook files are missing under ${e.targetPath}: ${s.join(", ")}`,remediation:"Reinstall the NativeSoul plugin"});let d=e.targetPath?ge.join(e.targetPath,"shared","hooks","lib.cjs"):null;r&&t.nativeHooksSupported&&(!d||!Re(d))&&i.push({code:"PLUGIN_SHARED_HOOKS_MISSING",severity:"error",message:"NativeSoul shared hook support files are missing under shared/hooks.",remediation:"Reinstall the NativeSoul plugin"});let h=e.targetPath?ge.resolve(ge.dirname(ge.dirname(e.targetPath))):void 0,g=!t.nativeHooksSupported||d!==null&&Re(d),x=t.nativeHooksSupported?a&&g:!0,te=r&&n&&c&&x&&l&&u,he=e.host==="grok"?await gi(h):null;return e.host==="grok"&&te&&he===!1&&i.push({code:"GROK_PLUGIN_RUNTIME_DISABLED",severity:"error",message:"NativeSoul is installed for Grok but disabled in grok config, so SessionStart hooks will not run.",remediation:"Run `grok plugin enable nativesoul` or `nativesoul install --host grok --apply`."}),{host:e.host,surface:e.surface,targetPath:e.targetPath,target_exists:r,manifest_exists:n,enabled:te&&he!==!1,hook_registered:t.nativeHooksSupported?c&&a:!1,package_kind:t.packageKind,native_hooks_supported:t.nativeHooksSupported,native_scheduler_supported:!1,issues:i}}async function Ku(e,t,r){let o=Zo(e);if(o.length===0)return r;let n=bt(t,pr(e,t)),s=o[0];if(!s||s===n)return r;let a=ge.join(t,s);return Re(a)?JSON.parse(await fr(a,"utf8")):{}}async function qu(e){let t=Qo(e.host),r=bt(e.targetPath,pr(e.host,e.targetPath));if(t.length>0&&!t.includes(r)){for(let o of t){let n=ge.join(e.targetPath,o);if(Re(n)&&en(JSON.parse(await fr(n,"utf8"))))return!0}return!1}if(e.host==="codex"){let o=ge.join(e.targetPath,".mcp.json");return Re(o)?en(JSON.parse(await fr(o,"utf8"))):!1}return en(e.manifest)}function en(e){let r=(!e.mcpServers||Array.isArray(e.mcpServers)||typeof e.mcpServers!="object"?null:e.mcpServers)?.nativesoul??(!e.nativeSoul||Array.isArray(e.nativeSoul)||typeof e.nativeSoul!="object"?null:e.nativeSoul.mcpServer);if(!r||Array.isArray(r)||typeof r!="object")return!1;let o=r.command,n=r.args;return typeof o!="string"||o.length===0?!1:o==="nativesoul-mcp"||qo(o)||o===process.execPath?!0:Array.isArray(n)&&n.some(s=>typeof s=="string"&&ge.isAbsolute(s))}import{cp as Cb,mkdir as Nb,readFile as Ob,readdir as Mb}from"node:fs/promises";import Db from"node:path";import{existsSync as Qb}from"node:fs";import{cp as ev,mkdir as tv,readFile as rv,writeFile as ov}from"node:fs/promises";import sv from"node:path";import{fileURLToPath as iv}from"node:url";import{spawnSync as Vb}from"node:child_process";import{accessSync as Wb,constants as Jb,existsSync as Kb}from"node:fs";import Gb from"node:path";function hr(e,t,r){let o=ar(e,r);if(e==="claude"&&o==="claude-desktop")return{surface:o,managedBlock:null,mcpRegistration:t?kt.join(kt.resolve(t,e),"claude_desktop_config.json"):Za(),plugin:ke(e,o,t)};if(!t)return{surface:o,managedBlock:Qa(e),mcpRegistration:ir(e),plugin:ke(e,o)};let n=kt.resolve(t,e);return{surface:o,managedBlock:kt.join(n,za(e)),mcpRegistration:kt.join(n,Ya(e)),plugin:ke(e,o,t)}}import{accessSync as Xu,constants as zu,existsSync as Rt}from"node:fs";import{mkdir as Yv,readFile as tn,rm as Qv,writeFile as Zv}from"node:fs/promises";import ce from"node:path";async function nn(e){let t=ce.resolve(e.targetPath??Si(e.host)),r=ti(e.host,e.targetPath),o=Rt(t),n=[],s=await Yu(e.host,t,r);if(s&&n.push(s),!o)return n.push({code:"MCP_CONFIG_MISSING",severity:"warn",message:`MCP config target is missing: ${t}`,remediation:"Run nativesoul mcp install --host <host> --target <path> --apply"}),{host:e.host,targetPath:t,target_exists:!1,parse_ok:!1,configured:!1,command:null,command_ok:!1,issues:n};let a=null;try{a=rn(await tn(t,"utf8"))}catch(d){n.push({code:"MCP_CONFIG_INVALID_JSON",severity:"error",message:d instanceof Error?d.message:"MCP config is invalid JSON",remediation:"Fix the JSON syntax or roll back from an NativeSoul snapshot"})}let i=a?on(a):null,c=typeof i?.command=="string"?i.command:null,l=Array.isArray(i?.args)?i.args.filter(d=>typeof d=="string"):[];i?c||n.push({code:"NATIVESOUL_MCP_COMMAND_MISSING",severity:"error",message:"nativesoul MCP server command is missing",remediation:"Re-run nativesoul mcp install"}):n.push({code:"NATIVESOUL_MCP_MISSING",severity:"warn",message:"nativesoul MCP server entry is not configured",remediation:"Run nativesoul mcp install --host <host> --target <path> --apply"});let u=c?e.checkCommand===!1?{ok:!0,issues:[]}:Qu(c,l,t):{ok:!1,issues:[]};return n.push(...u.issues),{host:e.host,targetPath:t,target_exists:o,parse_ok:a!==null,configured:i!==null,command:c,command_ok:u.ok,issues:n}}function Si(e){return ir(e)}function rn(e){if(e===null||e.trim().length===0)return{};let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("MCP config root must be a JSON object");return t}function on(e){let t=e.mcpServers;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.nativesoul;return!r||typeof r!="object"||Array.isArray(r)?null:r}async function Yu(e,t,r){if(e!=="claude"||r===null||ce.resolve(r)===t||!Rt(r))return null;try{let o=rn(await tn(r,"utf8")),n=on(o);if(!n)return null;if(Rt(t)){let s=rn(await tn(t,"utf8")),a=on(s);if(a&&JSON.stringify(ki(a))===JSON.stringify(ki(n)))return null}}catch{return null}return{code:"LEGACY_MCP_PATH",severity:"warn",message:`Legacy Claude MCP registration detected at ${r}.`,remediation:"Migrate to ~/.claude.json with nativesoul mcp install --host claude --apply, then uninstall or roll back the legacy ~/.claude/mcp.json entry."}}function ki(e){return{command:typeof e.command=="string"?e.command:null,args:Array.isArray(e.args)?e.args.filter(t=>typeof t=="string"):[]}}function Qu(e,t,r){let o=[],n=Zu(e);if(!n)return o.push({code:"NATIVESOUL_MCP_COMMAND_UNRESOLVED",severity:"error",message:`nativesoul MCP command does not resolve to an executable: ${e}`,remediation:"Reinstall with NATIVESOUL_MCP_COMMAND set to an absolute nativesoul-mcp path, or run npm install -g nativesoul and retry."}),{ok:!1,issues:o};if(ep(e,n)){let s=t[0],a=s?ce.isAbsolute(s)?s:ce.resolve(ce.dirname(r),s):null;if(!a||!Rt(a))return o.push({code:"NATIVESOUL_MCP_NODE_SCRIPT_MISSING",severity:"error",message:"nativesoul MCP command uses node but the server script is missing.",remediation:"Re-run nativesoul mcp install with --command-mode absolute or rebuild the local package."}),{ok:!1,issues:o}}return{ok:!0,issues:o}}function Zu(e){if(ce.isAbsolute(e))return Ri(e)?e:null;let t=(process.env.PATH??"").split(ce.delimiter).filter(Boolean),r=process.platform==="win32"?(process.env.PATHEXT??".EXE;.CMD;.BAT").split(";"):[""];for(let o of t)for(let n of r){let s=ce.join(o,`${e}${n}`);if(Ri(s))return s}return null}function Ri(e){if(process.platform==="win32"&&Rt(e))return!0;try{return Xu(e,zu.X_OK),!0}catch{return!1}}function ep(e,t){let r=ce.basename(e).toLowerCase(),o=ce.basename(t).toLowerCase();return r==="node"||r==="node.exe"||o==="node"||o==="node.exe"}async function sn(e){let t=e.readOnly?p(e.home):await _(e.home);if(e.readOnly&&!await y(t.database))return[];let r=f(t.database,{readOnly:e.readOnly});try{return r.listSchedules({host:e.host,limit:Math.min(Math.max(e.limit??50,1),200)})}finally{r.close()}}function an(e){let t=e.observedAt??new Date().toISOString(),r=e.plugin.enabled&&["native-plugin","official-extension"].includes(e.plugin.package_kind),o=e.plugin.native_hooks_supported&&e.plugin.hook_registered,n=e.mcpRegistration.configured,s=e.schedules.some(g=>rp(g,t)),a=ap(e.capabilities,e.adapterDiagnostics),i=[St("native_package",r,t,e.plugin.targetPath??e.plugin.package_kind,"Native package/extension is not installed or enabled."),St("native_hooks",o,t,e.plugin.targetPath??e.plugin.package_kind,"Native lifecycle hook registration is missing."),St("mcp",n,t,e.mcpRegistration.targetPath,"MCP registration is missing or invalid."),St("native_scheduler",s,t,np(e.schedules),ip(e.host,e.schedules)),St("official_inventory",a,t,sp(e.capabilities),"Official non-degraded capability inventory evidence is missing.")],c=i.filter(g=>!g.satisfied).map(g=>g.requirement),l=r&&o&&n,u=!a,d=c.includes("native_scheduler")&&Ei(e.host),h=c.length===0;return{schema_version:1,host:e.host,surface:e.surface,status:cp({fullNative:h,blockedByHost:d,degradedScan:u,ready:l}),ready:l,full_native:h,blocked_by_host:d,degraded_scan:u,generated_at:t,requirements:i,missing_requirements:c}}function St(e,t,r,o,n){return{requirement:e,satisfied:t,evidence:t?[{source_kind:"doctor",reference:o,observed_at:r,confidence:tp(o)}]:[],missing_reason:t?null:n}}function tp(e){return e.startsWith("not-applicable:")||e==="missing"?"low":"medium"}function rp(e,t){return e.enabled&&e.native_schedule_supported&&e.native_id!==null&&!op(e.updated_at,t)}function op(e,t){if(!e)return!1;let r=Date.parse(e),o=Date.parse(t);return!Number.isFinite(r)||!Number.isFinite(o)?!0:o-r>10080*60*1e3}function np(e){let t=e.find(r=>r.native_id!==null);return t?.native_id?t.updated_at?`${t.native_id}@${t.updated_at}`:t.native_id:"missing"}function sp(e){return e.find(t=>t.ready)?.source??"missing"}function ap(e,t){return t.some(r=>r.severity==="error"||r.severity==="warn")?!1:e.some(r=>r.ready&&r.schema_hash?.startsWith("official:")===!0)}function ip(e,t){return Ei(e)?e==="claude"?"Claude local Scheduled Tasks proof is missing, UI-only, or cloud-routine-only for this surface.":e==="antigravity"?"Antigravity scheduler write/list/status/cancel contract proof is missing or stale.":`Host ${e} has no proven native scheduler support.`:t.some(r=>r.enabled)?"Enabled schedule uses fallback or has no native_id mapping.":"No enabled native schedule evidence is available."}function Ei(e){return e==="codex"||e==="claude"||e==="grok"||e==="gemini"||e==="antigravity"}function cp(e){return e.fullNative?"full_native":e.blockedByHost?"blocked_by_host":e.degradedScan?"degraded_scan":e.ready?"ready_fallback":"ready"}async function Pi(e){let t=hr(e.host,e.targetRoot,e.surface),r=t.managedBlock??`not-applicable:${yt(e.host,e.surface)}`,o=t.managedBlock?await xa({host:e.host,targetPath:r}):bp(e.host,e.surface),n=await nn({host:e.host,targetPath:t.mcpRegistration,checkCommand:e.targetRoot===void 0}),s=await Xe({host:e.host,surface:e.surface,targetPath:t.plugin}),a=await Wo({home:e.home,host:e.host}),c=(e.databaseExists?await sn({home:e.home,host:e.host,limit:200,readOnly:!0}):[]).filter(k=>pp(e.host,e.surface,k)),l=e.databaseExists?await Ke({home:e.home,host:e.host,limit:100,readOnly:!0}):[],u=e.databaseExists?lr(p(e.home).database):[],d=e.targetRoot!==void 0,h=d?[]:(await wo(e.host))[0]?.diagnostics??[],g=c.length===0&&e.databaseExists?[{code:"SCHEDULE_DESIRED_STATE_MISSING",severity:"warn",message:`No persisted schedule desired state found for ${e.host}.`,remediation:e.targetRoot?`Run nativesoul install --host ${e.host} --apply --target-root ${e.targetRoot}`:"Run nativesoul install --host <host> --apply"}]:[],x=a.stale?[{code:"HANDSHAKE_STALE",severity:"warn",message:`Last ${e.host} handshake is ${a.age_hours??"unknown"} hour(s) old.`,remediation:`Run nativesoul bootstrap --host ${e.host} --cwd <current-working-directory> --format inject`}]:[],te=await fp({host:e.host,managedBlock:o,handshake:a}),he=await hp(e.host),re=c.filter(k=>k.enabled&&k.native_schedule_supported&&k.native_id===null).map(k=>({code:"NATIVE_SCHEDULE_MAPPING_MISSING",severity:"warn",message:`Schedule ${k.id} reports native support but has no native_id mapping.`,remediation:e.targetRoot?`Run nativesoul schedule reconcile --host ${e.host} --apply --target-root ${e.targetRoot}`:`Run nativesoul schedule reconcile --host ${e.host} --apply`})),$e=c.filter(k=>k.enabled&&!k.native_schedule_supported&&!s.enabled&&s.package_kind!=="unsupported-native").map(k=>({code:"NATIVE_SCHEDULE_UNSUPPORTED_NO_FALLBACK_INSTALLED",severity:"warn",message:`Schedule ${k.id} has no native scheduler support and no NativeSoul package fallback is installed.`,remediation:`Run nativesoul install --host ${e.host} --apply`})),Ee=gp({managedBlock:o,mcpRegistration:n,plugin:s,schedules:c,capabilities:l}),$n=an({host:e.host,surface:e.surface,mcpRegistration:n,plugin:s,schedules:c,capabilities:l,adapterDiagnostics:h}),jt=[...o.issues,...n.issues,...s.issues,...h,...g,...x,...te,...he,...re,...$e];return{host:e.host,surface:e.surface,status:jt.some(k=>k.severity==="error"||k.severity==="warn")?"degraded":"ready",targets:{managed_block:r,mcp_registration:n.targetPath},native_adapter_diagnostics_skipped:d,adapter_diagnostics:h,managed_block:o,mcp_registration:n,plugin:s,provider_parity:Ee,full_native_evidence:$n,handshake:a,schedule_count:c.length,enabled_schedule_count:c.filter(k=>k.enabled).length,native_schedule_mappings:c.map(k=>({id:k.id,native_schedule_supported:k.native_schedule_supported,native_id:k.native_id})),capability_count:l.length,ready_capability_count:l.filter(k=>k.ready).length,cross_host_inventory_summary:{current_host:l.length,other_hosts:u.filter(k=>k.host!==e.host&&k.host!=="all").length,ready_other_hosts:u.filter(k=>k.host!==e.host&&k.host!=="all"&&k.ready).length},issues:jt}}function pp(e,t,r){return e!=="claude"?!0:mp(r.desired)===t}function mp(e){if(e&&typeof e=="object"&&!Array.isArray(e)&&"surface"in e){let t=e.surface;if(t==="claude-desktop"||t==="claude-code")return t}return"claude-code"}function gp(e){let t=e.plugin.enabled,r=e.mcpRegistration.configured,o=e.managedBlock.configured||t,n=e.schedules.some(d=>d.enabled),a=e.schedules.some(d=>d.enabled&&d.native_schedule_supported)?"native":n&&t?"official-fallback":"unsupported-native",i=e.plugin.native_hooks_supported?e.plugin.hook_registered?"native":"unsupported-native":t?"official-fallback":"unsupported-native",c=e.plugin.package_kind==="unsupported-native"?"unsupported-native":t?"ready":"degraded",l=e.capabilities.length===0||e.capabilities.some(d=>d.ready);return{level:o&&r&&c==="ready"&&i!=="unsupported-native"&&a!=="unsupported-native"?"ready":e.plugin.package_kind==="native-plugin"?"native":e.plugin.package_kind==="unsupported-native"?"unsupported-native":"official-fallback",bootstrap:o?"ready":"degraded",mcp:r?"ready":"degraded",package:c,hooks:i,memory_recall:r?"ready":"degraded",policy_guard:o?"ready":"degraded",capability_scan:l?"ready":"degraded",heartbeat:a}}async function fp(e){if(!e.managedBlock.configured||e.managedBlock.targetPath.startsWith("not-applicable:"))return[];let t=10080*60*1e3,r=await _p(e.managedBlock.targetPath),o=e.handshake.age_ms;return r!==null&&r<=t?[]:o!==null&&o<=t?[]:[{code:"HANDSHAKE_NOT_OBSERVED",severity:"warn",message:`NativeSoul managed block is present for ${e.host}, but no handshake was observed in the last 7 days.`,remediation:`Start a host session or run nativesoul bootstrap --host ${e.host} --cwd <current-working-directory> --format inject`}]}async function hp(e){let t=yp(e).map(r=>Ai.resolve(process.cwd(),r));for(let r of t){if(!lp(r))continue;let o=await dp(r,"utf8"),n=it(o);if(n>2e3)return[{code:"PROJECT_CONTEXT_HEAVY",severity:"info",message:`Project instruction file is heavy (${n} estimated tokens): ${r}`,remediation:"Keep project rules authoritative for code boundaries; NativeSoul persona remains advisory continuity."}]}return[]}function yp(e){switch(e){case"claude":return["CLAUDE.md",Ai.join(".claude","CLAUDE.md")];case"codex":return["AGENTS.md"];case"grok":return["Agents.md","AGENTS.md"];case"antigravity":case"gemini":return["GEMINI.md"]}}async function _p(e){try{let t=await up(e);return Math.max(Date.now()-t.mtimeMs,0)}catch{return null}}function bp(e,t){return{host:e,targetPath:`not-applicable:${yt(e,t)}`,target_exists:!1,configured:!0,markers_valid:!0,issues:[]}}async function wt(e){let t=p(e.home),r=await $o(e.home),o=cn(t.database),n=Je(e.host),s=[],a=o?lr(t.database):[],i=ai(t.database,o),c=await qe(t.home),l=cn(cr(t.home)),u=cn(gt(t.home));for(let g of n)for(let x of ht(g,e.surface))s.push(await Pi({home:t.home,host:g,surface:x,targetRoot:e.targetRoot,databaseExists:o}));let d=[...r.issues,...ii(i),...s.flatMap(g=>g.issues)],h=r.healthy&&!d.some(g=>g.severity==="error");return{home:t.home,healthy:h,status:d.some(g=>g.severity==="error"||g.severity==="warn")?"degraded":"ready",workspace:r,target_root:e.targetRoot?xi.resolve(e.targetRoot):null,cross_host_inventory:ci(a),activation_summary:Xa({home:t.home,targetRoot:e.targetRoot?xi.resolve(e.targetRoot):null,host:e.host,profile:c,onboardingComplete:l,activationComplete:u,hosts:s}),full_native_matrix:vp(s),semantic_index:i,hosts:s,issues:d}}function vp(e){let t=e.map(r=>({host:r.host,surface:r.surface,status:r.full_native_evidence.status,full_native:r.full_native_evidence.full_native,blocked_by_host:r.full_native_evidence.blocked_by_host,degraded_scan:r.full_native_evidence.degraded_scan,missing_requirements:r.full_native_evidence.missing_requirements}));return{require_full_native_ready:t.length>0&&t.every(r=>r.full_native),host_count:t.length,full_native_count:t.filter(r=>r.full_native).length,blocked_count:t.filter(r=>r.blocked_by_host).length,degraded_scan_count:t.filter(r=>r.degraded_scan).length,ready_fallback_count:t.filter(r=>r.status==="ready_fallback").length,hosts:t}}import{existsSync as Gk}from"node:fs";import{mkdir as zk,readdir as Yk,readFile as Qk,writeFile as Zk}from"node:fs/promises";import tR from"node:path";import{lstat as mR,readdir as gR,readFile as fR}from"node:fs/promises";import yR from"node:path";import{lstat as PR,readFile as xR}from"node:fs/promises";import TR from"node:path";var De={state:"unlicensed",license_key:null,instance_id:null,purchased_at:null,version_at_activation:null,updates_until:null,last_checked_at:null,source:"none"};import{chmod as kp,mkdir as Rp,readFile as Sp,rm as UR,writeFile as wp}from"node:fs/promises";import{randomUUID as Ep}from"node:crypto";import Ii from"node:path";function ln(e){return Ii.join(p(e).home,"license.json")}async function He(e){let t=ln(e);if(!await y(t))return null;try{let r=JSON.parse(await Sp(t,"utf8"));return Ap(r)?r:null}catch{return null}}async function yr(e,t){let r=ln(e);return await Rp(Ii.dirname(r),{recursive:!0,mode:448}),await wp(r,`${JSON.stringify(t,null,2)}
840
+ `,{encoding:"utf8",mode:384}),await kp(r,384),t}async function dn(e){let t=await He(e);if(t?.instance_id)return t.instance_id;let r=Ep();return await yr(e,{...De,instance_id:r,purchased_at:t?.purchased_at??null,version_at_activation:t?.version_at_activation??null,updates_until:t?.updates_until??null,license_key_instance_id:t?.license_key_instance_id??null}),r}function Ap(e){return(e.state==="licensed"||e.state==="unlicensed")&&(typeof e.license_key=="string"||e.license_key===null)&&(typeof e.instance_id=="string"||e.instance_id===null)&&(typeof e.purchased_at=="string"||e.purchased_at===null||e.purchased_at===void 0)&&(typeof e.version_at_activation=="string"||e.version_at_activation===null||e.version_at_activation===void 0)&&(typeof e.updates_until=="string"||e.updates_until===null)&&(typeof e.last_checked_at=="string"||e.last_checked_at===null)&&(e.source==="dodo"||e.source==="none")&&(typeof e.license_key_instance_id=="string"||e.license_key_instance_id===null)}var Ti={name:"nativesoul",version:"0.1.2",description:"Local-first continuity layer for coding agents.",type:"module",license:"UNLICENSED",main:"dist/packages/cli/src/index.js",repository:{type:"git",url:"git+https://github.com/fillipeweb/nativesoul.git"},bugs:{url:"https://github.com/fillipeweb/nativesoul/issues"},homepage:"https://github.com/fillipeweb/nativesoul#readme",files:["dist/","plugins/","policy-packs/","schemas/","docs/adr/","docs/legal/","llm-install.txt","README.md","CHANGELOG.md"],bin:{nativesoul:"dist/packages/cli/src/index.js","nativesoul-mcp":"dist/packages/mcp-server/src/index.js"},scripts:{lint:"eslint .",typecheck:"tsc -p tsconfig.json --noEmit",test:"npm run build && npm run test:non-e2e","test:non-e2e":"node scripts/run-non-e2e-tests.mjs",build:"npm run build:ts && npm run build:minify","build:ts":"tsc -p tsconfig.build.json","build:minify":"node scripts/build-min.mjs","policy:generate":"node scripts/generate-policy-fail-closed.mjs","policy:check":"node scripts/generate-policy-fail-closed.mjs --check","release:security:audit":"node scripts/release-security-audit.mjs","release:provenance:dry-run":"node scripts/release-provenance-dry-run.mjs","package:local":"node scripts/package-local.mjs","package:dry-run":"node scripts/package-dry-run.mjs","package:smoke":"node scripts/package-smoke.mjs","test:e2e":"npm run build && vitest run tests/e2e"},engines:{node:">=22.17.0"},dependencies:{},devDependencies:{"@eslint/js":"^10.0.1","@types/node":"^26.0.0",esbuild:"^0.28.1",eslint:"^10.5.0",typescript:"^6.0.3","typescript-eslint":"^8.62.0",vitest:"^4.1.9"}};var ji=Ti.version;var Ip="https://api.dodopayments.com",Tp=1440*60*1e3,jp=14;async function un(e){let t=p(e.home).home,r=e.now??new Date,o=await He(t),n=e.key??o?.license_key,s=o?.instance_id??null;if(!n)return await Et(t,"license_validate_missing",null,"INVALID_KEY","blocked"),{ok:!1,reason:"INVALID_KEY",license:o?_r(o):De};if(o?.state==="licensed"&&Cp(o.last_checked_at,r))return await Et(t,"license_validate_cache_hit",n,null,"ok"),{ok:!0,license:_r(o)};let a=await Op(e,"/licenses/validate",{license_key:n});if(a.ok){let i=await yr(t,{state:"licensed",license_key:n,instance_id:s??await dn(t),license_key_instance_id:o?.license_key_instance_id??null,purchased_at:o?.purchased_at??null,version_at_activation:o?.version_at_activation??null,updates_until:o?.updates_until??null,last_checked_at:r.toISOString(),source:"dodo"});return await Et(t,"license_validated",n,null,"ok"),{ok:!0,license:_r(i)}}return a.reason==="NETWORK"&&o?.state==="licensed"&&Np(o.last_checked_at,r,e.graceDays)?(await Et(t,"license_validate_grace_served",n,"NETWORK","ok"),{ok:!0,license:_r(o)}):(await Et(t,"license_validate_failed",n,a.reason,"blocked"),{ok:!1,reason:a.reason,license:{...De,instance_id:s}})}function _r(e){return{state:e.state,license_key:e.license_key,instance_id:e.instance_id,purchased_at:e.purchased_at??null,version_at_activation:e.version_at_activation??null,updates_until:e.updates_until,last_checked_at:e.last_checked_at,source:e.source}}function Cp(e,t){return e?t.getTime()-new Date(e).getTime()<Tp:!1}function Np(e,t,r=jp){return e?t.getTime()-new Date(e).getTime()<=r*24*60*60*1e3:!1}async function Op(e,t,r){let o=e.fetch??globalThis.fetch;try{let n=await o(new URL(t,Mp(e.endpointBaseUrl)).toString(),{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(r)}),s=await Lp(n);return n.ok?t==="/licenses/validate"&&s.valid!==!0?{ok:!1,reason:Ci(s)}:{ok:!0,license_key_instance_id:Dp(s),purchased_at:Hp(s)}:{ok:!1,reason:Ci(s)}}catch{return{ok:!1,reason:"NETWORK"}}}function Mp(e=process.env.NATIVESOUL_DODO_LICENSE_API_BASE_URL??Ip){return e.endsWith("/")?e:`${e}/`}async function Lp(e){try{let t=await e.json();return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Dp(e){let r=[e.license_key_instance_id,e.licenseKeyInstanceId,e.id,At(e.data)?e.data.license_key_instance_id:null,At(e.data)?e.data.id:null].find(o=>typeof o=="string"&&o.length>0);return typeof r=="string"?r:null}function Hp(e){let t=At(e.data)?e.data:{},r=At(e.license_key)?e.license_key:At(t.license_key)?t.license_key:{},n=[e.purchased_at,e.purchase_date,e.created_at,t.purchased_at,t.purchase_date,t.created_at,r.purchased_at,r.purchase_date,r.created_at].find(s=>typeof s=="string"&&!Number.isNaN(Date.parse(s)));return typeof n=="string"?new Date(n).toISOString():null}function Ci(e){let t=String(e.reason??e.code??e.error??"").toUpperCase();return t.includes("LIMIT")?"ACTIVATION_LIMIT":t.includes("ACTIVE")?"NOT_ACTIVE":"INVALID_KEY"}function At(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}async function Et(e,t,r,o,n){await m({home:e,type:t,result:n,details:{provider:"dodo",license_key_ref:r?$p(r):null,reason:o}})}function $p(e){return e.length<=8?"[REDACTED_LICENSE_KEY]":`${e.slice(0,4)}\u2026${e.slice(-4)}`}var br="https://native-soul.mintlify.site/account/licensing";async function vr(e){let t=Fp(e),r=p(t.home).home;try{let o=await He(r),n=await un(t);if(n.ok)return{ok:!0,license:n.license};let s=n.reason==="NETWORK"&&o?.state==="licensed"?"GRACE_EXPIRED":"UNLICENSED",a=t.activateUrl??br;return{ok:!1,reason:s,activate_url:a,message:pn({reason:s,activate_url:a}),license:n.license}}catch{let o=t.activateUrl??br;return{ok:!1,reason:"UNLICENSED",activate_url:o,message:pn({reason:"UNLICENSED",activate_url:o}),license:De}}}function pn(e){return`${e.reason==="GRACE_EXPIRED"?"License offline grace expired.":"NativeSoul is not activated."} NativeSoul is paid-only. Run \`nativesoul license activate <key>\` after purchase: ${e.activate_url}`}function Fp(e){return typeof e=="string"?{home:e}:e??{}}import{readdir as cS,readFile as lS,stat as dS}from"node:fs/promises";import pS from"node:path";import{copyFile as _S,mkdir as bS,readFile as Up,rename as vS,stat as Vp,writeFile as kS}from"node:fs/promises";import{existsSync as Bp}from"node:fs";import Ni from"node:path";async function mn(e){let t=p(e.home),r=Oi(t.home,e.host);if(!Bp(r))return Wp({home:t.home,host:e.host,targetPath:r,recordTelemetry:e.recordTelemetry});let o=await Up(r,"utf8"),n=await Vp(r),s=e.ttlDays??7,a=Date.now()-n.mtimeMs>s*24*60*60*1e3,i=new Date().toISOString(),c=a?["BOOTSTRAP_CACHE_STALE"]:[],l=["---","nativesoul: bootstrap-context-cache",`host: ${e.host}`,`generated_at: ${i}`,"degraded: true",c.length>0?`warnings: ${c.join(", ")}`:"warnings: none","---","",o].join(`
841
+ `),u={host:e.host,generated_at:i,degraded:!0,warnings:c,tokens_used:Li(l),tokens_max:1900,content:l,targetPath:r,stale:a};if(e.recordTelemetry!==!1){await m({home:t.home,type:"bootstrap_context_cache_read",details:{...u,content:"[omitted]"}});let d=Jp(o);await Le({home:t.home,host:e.host,outcome:"degraded",tier:"D",cwd:d.cwd,project:d.project,tokensUsed:u.tokens_used,tokensMax:u.tokens_max,source:"bootstrap-cache",warnings:c})}return u}async function gn(e){let t=await mn({home:e.home,host:e.host,ttlDays:e.ttlDays,recordTelemetry:e.recordTelemetry});if(!t.warnings.includes("BOOTSTRAP_CACHE_MISSING")||!e.projectCwd)return t;let r=await mn({home:Mi(e.projectCwd),host:e.host,ttlDays:e.ttlDays,recordTelemetry:!1});return r.warnings.includes("BOOTSTRAP_CACHE_MISSING")?t:r}function Oi(e,t){return Ni.join(e,"generated",t,"last-context.md")}function Mi(e){return Ni.join(e,".nativesoul-cache")}async function Wp(e){let t=new Date().toISOString(),r=["BOOTSTRAP_CACHE_MISSING"],o=["---","nativesoul: bootstrap-context-cache",`host: ${e.host}`,`generated_at: ${t}`,"degraded: true",`warnings: ${r.join(", ")}`,"---","","Bootstrap context cache is not available. Run `nativesoul bootstrap --format inject` after install."].join(`
842
+ `),n={host:e.host,generated_at:t,degraded:!0,warnings:r,tokens_used:Li(o),tokens_max:1900,content:o,targetPath:e.targetPath,stale:!1};return e.recordTelemetry!==!1&&(await m({home:e.home,type:"bootstrap_context_cache_missing",details:{...n,content:"[omitted]"}}),await Le({home:e.home,host:e.host,outcome:"degraded",tier:"D",cwd:null,project:null,tokensUsed:n.tokens_used,tokensMax:n.tokens_max,source:"bootstrap-cache",warnings:r})),n}function Li(e){return Math.ceil(e.length/4)}function Jp(e){let t=e.match(/^- CWD:\s*(.+)$/mu)?.[1]?.trim()??null,r=e.match(/^- ID:\s*(.+)$/mu)?.[1]?.trim()??null;return{cwd:t,project:r}}var Hi={inbox:["assigned","in_progress"],assigned:["in_progress"],in_progress:["review","blocked","done","failed"],review:["in_progress","done","failed"],blocked:["in_progress","failed"],done:[],failed:[]};async function fn(e){let t=await _(e.home),r=new Date().toISOString(),o=N(e.title).value,n=e.description===void 0||e.description===null?null:N(e.description).value,s={id:A("work"),project_id:e.project,title:o,description:n,status:"inbox",priority:e.priority??"normal",assigned_host:e.host??null,source:e.source??"cli",tags:C(e.tags??[]),metadata:C(e.metadata??{}),created_at:r,updated_at:r,claimed_at:null,completed_at:null},a=$i({workItem:s,type:"created",fromStatus:null,toStatus:"inbox",actor:e.host??"cli",details:{priority:s.priority,source:s.source},now:r}),i=f(t.database),c;try{c=i.insertWorkItem(s),i.insertWorkItemEvent(a)}finally{i.close()}return await Fi(t.home,"work_item_created",c,{redacted:o!==e.title||e.description!==void 0&&e.description!==null&&n!==e.description,event_id:a.id}),c}async function hn(e){let t=e.readOnly?p(e.home):await _(e.home);if(e.readOnly&&!await y(t.database))return[];let r=f(t.database,{readOnly:e.readOnly}),o;try{o=r.listWorkItems({project:e.project,status:e.status,priority:e.priority,assignedHost:e.assignedHost,limit:Gp(e.limit)})}finally{r.close()}return e.readOnly||await m({home:t.home,type:"work_items_listed",details:{project:e.project??null,status:e.status??null,priority:e.priority??null,assigned_host:e.assignedHost??null,count:o.length}}),o}async function yn(e){return vn({home:e.home,id:e.id,actor:e.host,eventType:"claimed",auditType:"work_item_claimed",mutate:(t,r)=>{if(kn(t.status))throw new Error(`Work item already terminal: ${t.id} (${t.status})`);return kr(t.status,"in_progress"),{status:"in_progress",assignedHost:e.host,claimedAt:t.claimed_at??r,updatedAt:r,details:{assigned_host:e.host}}}})}async function _n(e){return vn({home:e.home,id:e.id,actor:e.assignedHost??"cli",eventType:e.status?"status_changed":"updated",auditType:"work_item_updated",mutate:(t,r)=>{let o=e.status??t.status;e.status&&kr(t.status,e.status);let n=e.description===void 0||e.description===null?e.description:N(e.description).value;return{status:o,priority:e.priority,assignedHost:e.assignedHost,description:n,tags:e.tags===void 0?void 0:C(e.tags),metadata:e.metadata===void 0?void 0:zp(t.metadata,C(e.metadata)),completedAt:kn(o)?r:void 0,updatedAt:r,details:{priority:e.priority??null,assigned_host:e.assignedHost??null,fields:qp(e),redacted:e.description!==void 0&&e.description!==null&&n!==e.description}}}})}async function bn(e){let t=e.status??"done";return vn({home:e.home,id:e.id,actor:"cli",eventType:"completed",auditType:"work_item_completed",mutate:(r,o)=>{if(kn(r.status))throw new Error(`Work item already terminal: ${r.id} (${r.status})`);return kr(r.status,t),{status:t,completedAt:o,updatedAt:o,details:{terminal_status:t}}}})}function kr(e,t){if(e!==t&&!Hi[e].includes(t))throw new Error(`Illegal work item transition: ${e} -> ${t}`)}async function vn(e){let t=await _(e.home),r=f(t.database),o,n;try{let s=r.getWorkItem(e.id);if(!s)throw new Error(`Work item not found: ${e.id}`);let a=new Date().toISOString(),i=e.mutate(s,a);n=$i({workItem:s,type:e.eventType,fromStatus:s.status,toStatus:i.status??s.status,actor:e.actor,details:i.details,now:a}),o=r.updateWorkItem({id:s.id,status:i.status,priority:i.priority,assignedHost:i.assignedHost,description:i.description,tags:i.tags,metadata:i.metadata,claimedAt:i.claimedAt,completedAt:i.completedAt,updatedAt:i.updatedAt,event:n})}finally{r.close()}if(!o)throw new Error(`Work item not found: ${e.id}`);return await Fi(t.home,e.auditType,o,{event_id:n.id,event_type:n.type,from_status:n.from_status,to_status:n.to_status,details:n.details}),o}function $i(e){return{id:A("work_evt"),work_item_id:e.workItem.id,project_id:e.workItem.project_id,type:e.type,from_status:e.fromStatus,to_status:e.toStatus,actor:e.actor,details:e.details,created_at:e.now}}async function Fi(e,t,r,o){await m({home:e,type:t,details:{id:r.id,project:r.project_id,status:r.status,...Xp(o)}})}function qp(e){return[e.status===void 0?null:"status",e.priority===void 0?null:"priority",e.assignedHost===void 0?null:"assigned_host",e.description===void 0?null:"description",e.tags===void 0?null:"tags",e.metadata===void 0?null:"metadata"].filter(t=>t!==null)}function kn(e){return e==="done"||e==="failed"}function Gp(e){return!e||!Number.isFinite(e)?50:Math.min(Math.max(Math.trunc(e),1),200)}function Xp(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e}}function zp(e,t){return Di(e)&&Di(t)?{...e,...t}:t}function Di(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}import{readdir as dw,readFile as uw}from"node:fs/promises";import mw from"node:path";import{existsSync as HS}from"node:fs";import{mkdir as qS,readdir as Qp,readFile as Zp,writeFile as GS}from"node:fs/promises";import Pt from"node:path";var em=new Set(["SOUL.MD","POLICY.MD"]),tm=5e3,Ui=new Map;async function xt(e){let t=p(e),r=Ui.get(t.home);if(r&&r.expiresAt>Date.now())return r.orders;let o=Pt.join(t.home,"standing-orders"),n;try{n=await Qp(o)}catch{return[]}let s=[];for(let a of n.filter(i=>i.endsWith(".yaml")||i.endsWith(".yml")).sort()){let i=Pt.join(o,a),c=await Zp(i,"utf8");s.push(rm(c,i))}return Ui.set(t.home,{expiresAt:Date.now()+tm,orders:s}),s}async function It(e){let t=await xt(e.home),r=e.target??null,o=r?om(r):null,n=t.filter(i=>Rn(i,e)),s=n.find(i=>i.allowed.includes(e.action)),a=n.find(i=>i.approval_required.includes(e.action));if(o&&em.has(o))return Se(e,"proposal_required",["PROTECTED_HUMAN_FILE"],null);if(e.className==="identity_policy_change")return Se(e,"proposal_required",["IDENTITY_POLICY_CHANGE"],null);if(e.className==="destructive")return Se(e,"denied",["DESTRUCTIVE_DENIED_BY_DEFAULT"],s?.id??a?.id??null);if(a)return Se(e,"approval_required",["STANDING_ORDER_REQUIRES_APPROVAL"],a.id);if(s)return Se(e,"allowed",["STANDING_ORDER_ALLOWED"],s.id);switch(e.className){case"read_local":case"probe_external":case"write_local":return Se(e,"allowed",["DEFAULT_ALLOWED"],null);case"write_project":return Se(e,"approval_required",["PROJECT_WRITE_REQUIRES_APPROVAL"],null);case"external_write":return Se(e,"approval_required",["EXTERNAL_WRITE_REQUIRES_APPROVAL"],null)}}function Se(e,t,r,o){return{action:e.action,class:e.className,target:e.target??null,decision:t,reasons:r,matched_standing_order:o}}function rm(e,t){return{id:nm(e,"id")??Pt.basename(t,Pt.extname(t)),allowed:ze(e,"allowed"),approval_required:ze(e,"approval_required"),scope_projects:ze(e,"projects").concat(ze(e,"scope_projects")),scope_hosts:ze(e,"hosts").concat(ze(e,"scope_hosts")),source:t}}function Rn(e,t){return!(e.scope_projects.length>0&&(!t.project||!e.scope_projects.includes(t.project))||e.scope_hosts.length>0&&(!t.host||!e.scope_hosts.includes(t.host)))}function om(e){return Pt.basename(e.replaceAll("\\","/")).toUpperCase()}function nm(e,t){let r=new RegExp(`^\\s*${t}:\\s*([^\\n#]+)`,"mu");return e.match(r)?.[1]?.trim().replace(/^["']|["']$/gu,"")??null}function ze(e,t){let r=e.match(new RegExp(`^\\s*${t}:\\s*\\[([^\\]]*)\\]`,"mu"));if(r?.[1])return r[1].split(",").map(i=>i.trim().replace(/^["']|["']$/gu,"")).filter(Boolean);let o=e.split(/\r?\n/u),n=[],s=!1,a=0;for(let i of o){let c=i.trim();if(!s){let u=i.match(new RegExp(`^(\\s*)${t}:\\s*$`,"u"));u&&(s=!0,a=u[1]?.length??0);continue}let l=i.length-i.trimStart().length;if(c&&l<=a&&!c.startsWith("-"))break;c.startsWith("-")&&n.push(c.slice(1).trim().replace(/^["']|["']$/gu,""))}return n.filter(Boolean)}import{mkdir as Sw,writeFile as ww}from"node:fs/promises";import Aw from"node:path";import{readFile as um}from"node:fs/promises";import pm from"node:path";var Rr=1500;async function wn(e){let t=await _(e.home),r=await fm(t.home),o=new Date,n=mm(e.ttlSeconds??r.ttlSeconds),s=new Date(o.getTime()+n*1e3).toISOString(),a=An(e.project,e.slot),i=f(t.database),c;try{c=i.claimHeartbeatLease({id:A("lease"),slot:e.slot,holder:e.host,idempotencyKey:a,now:o.toISOString(),expiresAt:s})}finally{i.close()}return await m({home:t.home,type:c.claimed?"heartbeat_claimed":"heartbeat_skipped",details:{slot:e.slot,host:e.host,project:e.project,lease_id:c.lease.id,reason:c.reason}}),{slot:e.slot,host:e.host,project:e.project,claimed:c.claimed,reason:c.reason,silent_ack:c.claimed||c.reason==="LEASE_OCCUPIED"&&!r.skipWhenBusy?null:"HEARTBEAT_OK",lease:c.lease}}async function En(e){let t=await _(e.home),r=new Date().toISOString(),o=An(e.project,e.slot),n=C(e.result??"HEARTBEAT_OK"),s=C(gm(e.evidence??{},e.workItemId)),a=C(e.cost??{}),i=Fe(a),c=f(t.database),l;try{l=c.completeHeartbeatLease({idempotencyKey:o,host:e.host,project:e.project,result:n,evidence:s,cost:i,completedAt:r,runId:A("run")})}finally{c.close()}return await m({home:t.home,type:l.completed?"heartbeat_completed":"heartbeat_completion_replayed",details:{slot:e.slot,host:e.host,project:e.project,lease_id:l.lease.id,run_id:l.run?.id??null}}),{slot:e.slot,project:e.project,completed:l.completed,silent_ack:"HEARTBEAT_OK",lease:l.lease,run:l.run}}function An(e,t){return`heartbeat:${e}:${t}`}function mm(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),1440*60):Rr}function gm(e,t){return t?{...e&&typeof e=="object"&&!Array.isArray(e)?e:{},work_item_id:t}:e}async function fm(e){let t;try{t=await um(pm.join(e,"config.yaml"),"utf8")}catch{return{ttlSeconds:Rr,skipWhenBusy:!0}}return{ttlSeconds:hm(t),skipWhenBusy:ym(t,"skip_when_busy",!0)}}function hm(e){let t=Sn(e,"ttl_seconds"),r=Sn(e,"lease_ttl"),o=_m(e,"heartbeat_ttl_seconds"),n=bm(t??r??o);return Number.isFinite(n)?n:Rr}function ym(e,t,r){let o=Sn(e,t);return o?/^(true|yes|1)$/i.test(o)?!0:/^(false|no|0)$/i.test(o)?!1:r:r}function Sn(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.match(new RegExp(`^\\s*heartbeat:\\s*$[\\s\\S]*?^\\s{2}${r}:\\s*([^#\\n]+)`,"mu"))?.[1]?.trim().replace(/^["']|["']$/g,"")??null}function _m(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.match(new RegExp(`^\\s*${r}:\\s*([^#\\n]+)`,"mu"))?.[1]?.trim().replace(/^["']|["']$/g,"")??null}function bm(e){if(!e)return Rr;let t=e.match(/^(\d+)$/);if(t)return Number(t[1]);let r=e.match(/^(\d+)\s*([smh])$/i);if(!r)return Number.NaN;let o=Number(r[1]),n=r[2]?.toLowerCase();return n==="s"?o:n==="m"?o*60:o*60*60}import Qw from"node:path";import{rm as eE}from"node:fs/promises";async function xn(e){let t=p(e.home),r=f(t.database),o;try{let n=r.findPendingApprovalMatch(Pn(e));if(!n.available)return{approval:null,created:!1,available:!1,warning:n.warning};if(n.approval)return{approval:n.approval,created:!1,available:!0,warning:null};let s=r.createApproval({id:A("approval"),...Pn(e)});o={approval:s.approval,created:!!s.approval,available:s.available,warning:s.warning}}finally{r.close()}return o.created&&o.approval&&await m({home:t.home,type:"approval_requested",details:jn(o.approval)}),o}async function In(e){let t=p(e.home),r=f(t.database),o;try{let n=r.decideApproval(e.id,{status:e.status,reviewer:e.reviewer??"local-operator",reason:e.reason??null});o={approval:n.approval,available:n.available,warning:n.warning}}catch(n){throw n instanceof ne,n}finally{r.close()}return o.approval&&await m({home:t.home,type:o.approval.status==="approved"?"approval_approved":"approval_rejected",details:jn(o.approval)}),o}async function Tn(e){let t=p(e.home),r=f(t.database),o;try{let n=r.createDecidedApproval({id:A("approval"),...Pn(e),status:"approved",reviewer:`standing-order:${e.standingOrderId}`,reason:e.reason});o={approval:n.approval,available:n.available,warning:n.warning,created:!!n.approval}}finally{r.close()}return o.approval&&await m({home:t.home,type:"approval_auto_approved",details:{...jn(o.approval),standing_order:e.standingOrderId}}),o}function Pn(e){return{action:e.action,class:e.class,target:e.target??null,project:e.project??null,host:e.host??null}}function jn(e){return{id:e.id,action:e.action,class:e.class,target:e.target,project:e.project,host:e.host,status:e.status,reviewer:e.reviewer,reason:e.reason}}async function Cn(e){let t=await It(e),r=await xm(e,t);if(r){let n=await Tn({home:e.home,action:t.action,class:t.class,target:t.target,project:e.project??null,host:e.host??null,standingOrderId:r.id,reason:`standing-order allowed:${t.action}`});return{evaluation:t,approval:n.approval,approval_created:n.created,approval_available:n.available,warning:n.warning}}if(t.decision!=="approval_required")return{evaluation:t,approval:null,approval_created:!1,approval_available:!0,warning:null};let o=await xn({home:e.home,action:t.action,class:t.class,target:t.target,project:e.project??null,host:e.host??null});return{evaluation:t,approval:o.approval,approval_created:o.created,approval_available:o.available,warning:o.warning}}async function xm(e,t){return t.decision!=="allowed"||!t.matched_standing_order||!Im(e.className)?null:(await xt(e.home)).find(o=>o.id===t.matched_standing_order&&o.allowed.includes(e.action)&&Rn(o,e))??null}function Im(e){return e==="write_project"||e==="external_write"}import{existsSync as DE}from"node:fs";import{mkdir as $E,readFile as FE,rm as UE,writeFile as VE}from"node:fs/promises";import WE from"node:path";import{existsSync as AE}from"node:fs";import{readdir as xE,readFile as IE}from"node:fs/promises";import jE from"node:path";import{fileURLToPath as NE}from"node:url";import vE from"node:path";var Wi=["AGENTS.md","CLAUDE.md","GEMINI.md","Agents.md",".claude/CLAUDE.md"],kE=new Set(Wi);import jm from"node:path";async function Sr(e={}){let t=p(e.home),r=e.host??"all",[o,n,s,a]=await Promise.all([qe(t.home),y(cr(t.home)),y(gt(t.home)),wt({home:t.home,host:r,surface:e.surface,targetRoot:e.targetRoot})]);return Ho({home:t.home,targetRoot:e.targetRoot?jm.resolve(e.targetRoot):null,host:r,profile:o,onboardingComplete:n,activationComplete:s,hosts:a.hosts})}async function Nn(e={}){let t=await Sr(e);if(!e.profile||t.profile?.profile===e.profile)return t;let r={...t.profile??Do,profile:e.profile,updated_at:t.profile?.updated_at??"dry-run"};return{...t,profile:r,plan:[{id:"activation-profile-switch",component:"bootstrap",status:"approval_required",action:`Switch activation profile to ${e.profile}.`,target:`${t.home}/state/activation-profile.json`,dry_run:!0,requires_user_confirmed:!0,reason:"Activation profile replacement requires explicit reset/user confirmation."},...t.plan]}}import{randomUUID as Cm}from"node:crypto";import Nm from"node:path";var Om="NativeSoul activation verification marker";async function Mn(e={}){let t=Hm(e),r=pe(t.projectCwd,e.home),o=await wt({home:e.home,host:e.host??"all",surface:e.surface,targetRoot:e.targetRoot}),n=[];for(let l of o.hosts)n.push(await Mm({home:o.home,inputHost:l,testCwd:t.projectCwd}));let s=await Dm({home:e.home,testProject:`${r.id}-${Cm()}`,apply:e.apply===!0,userConfirmed:e.userConfirmed===!0,retainTestData:e.retainTestData===!0}),a=[...new Set([...n.flatMap(l=>l.recommendations),...s.status==="failed"?["Review memory persistence and rerun verification."]:[]])],i=n.map(l=>l.status),c=Fm(i,s.status);return{schema_version:1,home:o.home,target_root:o.target_root,host:e.host??"all",surface:e.surface??null,project:{requested_cwd:t.projectCwd,normalized:r.id,source:r.source,git_root:r.git_root,remote:r.remote,alias_key:r.alias_key},overall_status:c,memory_recall:s,hosts:n,recommendations:a}}async function Mm(e){let t=[],r=await Lm({home:e.home,host:e.inputHost.host,cwd:e.testCwd,warnings:e.inputHost.handshake.last?.warnings??[]});e.inputHost.mcp_registration.configured||t.push(`Install MCP registration for ${e.inputHost.host}: nativesoul mcp install --host ${e.inputHost.host} --apply --json`),r.status!=="ready"&&t.push(`Regenerate bootstrap context for ${e.inputHost.host}: nativesoul bootstrap --host ${e.inputHost.host} --cwd ${e.testCwd} --format inject --json`);let o=$m(e.inputHost.provider_parity.heartbeat),n=[...e.inputHost.full_native_evidence.missing_requirements];o==="unsupported"&&(n.includes("native_scheduler")||n.push("native_scheduler"),t.push(`Choose a host with native scheduler support or configure external scheduler workflow for ${e.inputHost.host}.`));let a=e.inputHost.provider_parity.heartbeat==="unsupported-native"&&e.inputHost.host!=="codex"?"blocked_by_host":r.status==="failed"||r.status==="degraded"||r.cache.status==="degraded"||r.cache.status==="missing"||!e.inputHost.plugin.enabled?"degraded":"ready";return{host:e.inputHost.host,surface:e.inputHost.surface,status:a,mcp:{configured:e.inputHost.mcp_registration.configured,issues:e.inputHost.mcp_registration.issues.map(i=>i.message)},bootstrap:r,heartbeat:{status:o,requirements:n},recommendations:t}}async function Lm(e){let t=[...e.warnings],r=[],o="ready",n=!1,s="",a="ready";try{let i=await mt({home:e.home,host:e.host,cwd:e.cwd,readOnly:!0});t.push(...i.warnings),i.warnings.some(c=>c.startsWith("HOST_ADAPTER_UNAVAILABLE")||c==="PROJECT_MEMORY_EMPTY")&&(a="degraded")}catch(i){t.push(`bootstrap_injection_failed:${On(i)}`),a="failed"}try{let i=await gn({home:e.home,host:e.host,projectCwd:e.cwd,recordTelemetry:!1});s=i.targetPath,n=i.stale,r.push(...i.warnings),r.length>0&&(o=i.warnings.some(c=>c==="BOOTSTRAP_CACHE_MISSING")?"missing":"degraded",a==="ready"&&(a="degraded"))}catch{r.push("bootstrap_cache_check_failed"),o="missing",a==="ready"&&(a="degraded")}return{status:a,warnings:t,cache:{status:o,warnings:r,targetPath:s,stale:n}}}async function Dm(e){let t=[],r=null,o=!1,n=!1;try{let s=`verify-${e.testProject}`,a=`${Om} ${e.testProject}`;r=await be(e.home,{project:s,content:a,confidence:.91,source:{host:"activation-verification",session_id:`verification-${e.testProject}`}});let i=await pt(e.home,a,s,8),c=await nr({home:e.home,project:s,status:"candidate",limit:8}),l=i.some(u=>u.id===r?.id)||c.some(u=>u.id===r?.id);if(e.apply&&e.userConfirmed&&r){let u=await lt(e.home,r.id);r=u,n=r.id===u.id&&r.status==="active"}if(!e.retainTestData&&r)try{r.status==="candidate"?await dt(e.home,r.id):await ut(e.home,r.id),o=!0}catch(u){t.push(`memory_cleanup_failed:${On(u)}`)}return{test_project:e.testProject,candidate_id:r?.id??"",candidate_status:r?.status??"candidate",recalled:l,promoted:n,status:l?"passed":"failed",warnings:t,cleanup_performed:o}}catch(s){return t.push(`memory_recall_check_failed:${On(s)}`),{test_project:e.testProject,candidate_id:r?.id??"",candidate_status:r?.status??"candidate",recalled:!1,promoted:!1,status:"failed",warnings:t,cleanup_performed:!1}}}function Hm(e){return{projectCwd:Nm.resolve(e.projectCwd??process.cwd())}}function $m(e){return e==="native"?"native":e==="official-fallback"?"official_fallback":"unsupported"}function Fm(e,t){return e.includes("blocked_by_host")?"blocked_by_host":e.includes("degraded")||t==="failed"?"degraded":e.length>0?"ready":"degraded"}function On(e){return e instanceof Error?e.message:String(e)}function Ki(e){let t=p(e);if(!Um(t.database))return{home:t.home,initialized:!1,database:t.database,migrations:0,memories:0,events:0,capabilities:0,ledger:Vm()};let r=f(t.database,{readOnly:!0});try{return{home:t.home,initialized:!0,database:t.database,...r.counts()}}finally{r.close()}}function Vm(){return{hosts:0,sessions:0,memory_edges:0,commitments:0,standing_orders:0,capability_sources:0,capability_experience:0,schedules:0,leases:0,runs:0,work_items:0,work_item_events:0}}var qi={life_activation_status:async(e,t)=>await Sr({home:t,host:Ln(e.host),targetRoot:we(e.target_root)??we(e.targetRoot)}),life_activation_plan:async(e,t)=>await Nn({home:t,host:Ln(e.host),targetRoot:we(e.target_root)??we(e.targetRoot),profile:Bm(e.profile)}),life_activation_verify:async(e,t)=>await Mn({home:t,host:Ln(e.host),surface:Wm(e.surface),targetRoot:we(e.target_root)??we(e.targetRoot),projectCwd:we(e.project_cwd)??we(e.projectCwd),apply:Dn(e.apply),userConfirmed:Dn(e["user-confirmed"]),retainTestData:Dn(e["retain-test-data"])})},Gi=[{name:"life_activation_status",description:"Return activation status by component, including bootstrap, MCP, plugins/hooks, heartbeat, recall, memory, and cross-host verification.",inputSchema:{type:"object",properties:{host:{type:"string"},target_root:{type:"string"},targetRoot:{type:"string"}}}},{name:"life_activation_plan",description:"Return a read-only dry-run activation plan with exact files, settings, scheduler actions, and approvals.",inputSchema:{type:"object",properties:{host:{type:"string"},profile:{type:"string"},target_root:{type:"string"},targetRoot:{type:"string"}}}},{name:"life_activation_verify",description:"Run cross-host activation verification for bootstrap cache, MCP, scheduler evidence, and memory recall.",inputSchema:{type:"object",properties:{host:{type:"string"},surface:{type:"string"},project_cwd:{type:"string"},projectCwd:{type:"string"},target_root:{type:"string"},targetRoot:{type:"string"},apply:{type:"boolean"},"user-confirmed":{type:"boolean"},"retain-test-data":{type:"boolean"}}}}];function Ln(e){if(e===void 0)return"all";if(e==="all"||e==="codex"||e==="claude"||e==="grok"||e==="antigravity"||e==="gemini")return e;throw new Error("Invalid activation host")}function Bm(e){if(e!==void 0){if(e==="quickstart"||e==="advanced")return e;throw new Error("Invalid activation profile")}}function Wm(e){if(e!==void 0){if(e==="desktop"||e==="claude-desktop")return"claude-desktop";if(e==="claude-code")return"claude-code";throw new Error("activation verify surface must be claude-code, desktop, or claude-desktop")}}function we(e){return typeof e=="string"?e:void 0}function Dn(e){return e===!0}var Jm=["2025-11-25","2024-11-05","2024-10-07"],Zi={...qi,life_status:(e,t)=>Ki(t),life_bootstrap:async(e,t)=>await Ym({home:t,host:S(e.host,"codex"),cwd:S(e.cwd,process.cwd()),query:D(e.query)}),life_recall:async(e,t)=>await pt(t,S(e.query,""),S(e.project,"default"),Er(e.limit,5)),life_remember_propose:async(e,t)=>await be(t,{project:S(e.project,"default"),content:S(e.content,""),type:D(e.type),confidence:Xi(e.confidence),source:{host:"mcp",session_id:"local"}}),life_memory_promote:async(e,t)=>await lt(t,S(e.id,"")),life_memory_reject:async(e,t)=>await dt(t,S(e.id,"")),life_memory_forget:async(e,t)=>await ut(t,S(e.id,"")),life_memory_expire:async(e,t)=>await No(t,S(e.id,"")),life_capability_search:async(e,t)=>await Eo({home:t,query:S(e.query,""),host:eg(e)?void 0:D(e.host)??"codex",readyOnly:Ye(e.readyOnly,!1),limit:Er(e.limit,8)}),life_capability_status:async(e,t)=>{let r=S(e.uid,""),o=r?await Ao({home:t,uid:r}):null;if(!o)throw new Error(`Capability not found: ${r}`);return o},life_policy_evaluate:async(e,t)=>await It({home:t,action:S(e.action,""),className:Qi(e.class),target:D(e.target)}),life_approval_request:async(e,t)=>await ng({home:t,action:S(e.action,""),className:Qi(e.class),target:D(e.target),project:D(e.project),host:D(e.host)}),life_approval_decide:async(e,t)=>{let r=S(e.id,""),o=await In({home:t,id:r,status:og(e.status),reviewer:S(e.host,"mcp"),reason:D(e.reason)??null});if(!o.approval)throw new Error(`Approval not found: ${r}`);return o},life_commitment_create:async(e,t)=>await xo({home:t,project:S(e.project,"default"),summary:S(e.summary,""),dueAt:D(e.due_at),ttlSeconds:Xi(e.ttl_seconds),source:{host:"mcp",session_id:"local"}}),life_commitment_complete:async(e,t)=>await To(t,S(e.id,"")),life_work_item_create:async(e,t)=>await fn({home:t,project:S(e.project,"default"),title:S(e.title,""),description:D(e.description),priority:Hn(e.priority),source:"mcp",tags:zi(e.tags),host:D(e.host)}),life_work_item_list:async(e,t)=>await hn({home:t,project:D(e.project),status:Yi(e.status),priority:Hn(e.priority),assignedHost:D(e.host),limit:Er(e.limit,50)}),life_work_item_claim:async(e,t)=>await yn({home:t,id:S(e.id,""),host:S(e.host,"mcp")}),life_work_item_update:async(e,t)=>await _n({home:t,id:S(e.id,""),status:Yi(e.status),priority:Hn(e.priority),assignedHost:D(e.host),description:D(e.description),tags:e.tags===void 0?void 0:zi(e.tags)}),life_work_item_complete:async(e,t)=>await bn({home:t,id:S(e.id,""),status:Zm(e.status)}),life_heartbeat_claim:async(e,t)=>await wn({home:t,slot:S(e.slot,""),host:S(e.host,"codex"),project:S(e.project,"default"),ttlSeconds:Er(e.ttl_seconds,1500)}),life_heartbeat_complete:async(e,t)=>await En({home:t,slot:S(e.slot,""),host:S(e.host,"codex"),project:S(e.project,"default"),result:e.result??"HEARTBEAT_OK",evidence:e.evidence??{},workItemId:D(e.work_item_id)}),life_onboarding_status:async(e,t)=>await Fo(t),life_onboard_apply:async(e,t)=>await Uo({home:t,dry_run:Ye(e.dry_run,!0),user_confirmed:Ye(e.user_confirmed,!1),files:tg(e.files),config_patch:rg(e.config_patch)}),life_onboard_complete:async(e,t)=>await Vo({home:t,archive:e.archive===void 0?!0:Ye(e.archive,!0)})},Km=new Set(Object.keys(Zi));function qm(e){return e.method?.startsWith("notifications/")?!0:!Object.prototype.hasOwnProperty.call(e,"id")}async function Gm(e,t){if(qm(e))return null;let r=e.id??null;try{if(e.method==="initialize"){let o=Tt(e.params),n=D(o.protocolVersion),s=n&&Jm.includes(n)?n:"2024-11-05";return fe(r,{protocolVersion:s,serverInfo:{name:"nativesoul",version:"0.1.0"},capabilities:{tools:{}}})}if(e.method==="ping")return fe(r,{});if(e.method==="resources/list")return fe(r,{resources:[]});if(e.method==="prompts/list")return fe(r,{prompts:[]});if(e.method==="tools/list")return fe(r,{tools:[{name:"life_status",description:"Return local NativeSoul health and counts.",inputSchema:{type:"object"}},{name:"life_bootstrap",description:"Return compact bootstrap context for a host and cwd.",inputSchema:{type:"object",required:["host","cwd"],properties:{host:{type:"string"},cwd:{type:"string"},query:{type:"string"}}}},{name:"life_recall",description:"Search project-scoped memory.",inputSchema:{type:"object",required:["query","project"],properties:{query:{type:"string"},project:{type:"string"},limit:{type:"number"}}}},{name:"life_remember_propose",description:"Create a redacted local candidate memory for a project.",inputSchema:{type:"object",required:["project","content"],properties:{project:{type:"string"},content:{type:"string"},type:{type:"string"},confidence:{type:"number"}}}},{name:"life_memory_promote",description:"Promote a candidate memory to active status.",inputSchema:{type:"object",required:["id"],properties:{id:{type:"string"}}}},{name:"life_memory_reject",description:"Reject a candidate memory.",inputSchema:{type:"object",required:["id"],properties:{id:{type:"string"}}}},{name:"life_memory_forget",description:"Forget an active memory.",inputSchema:{type:"object",required:["id"],properties:{id:{type:"string"}}}},{name:"life_memory_expire",description:"Expire an active memory.",inputSchema:{type:"object",required:["id"],properties:{id:{type:"string"}}}},{name:"life_capability_search",description:"Search persisted local capability records.",inputSchema:{type:"object",required:["query"],properties:{query:{type:"string"},host:{type:"string"},allHosts:{type:"boolean"},all_hosts:{type:"boolean"},readyOnly:{type:"boolean"},limit:{type:"number"}}}},{name:"life_capability_status",description:"Return one persisted capability record by uid.",inputSchema:{type:"object",required:["uid"],properties:{uid:{type:"string"}}}},{name:"life_policy_evaluate",description:"Evaluate a proposed action against local policy and standing orders.",inputSchema:{type:"object",required:["action","class"],properties:{action:{type:"string"},class:{type:"string"},target:{type:"string"}}}},{name:"life_approval_request",description:"Request approval for a sensitive action. If blocked, stop and return control to the human; there is no server or polling in this turn-based protocol.",inputSchema:{type:"object",required:["action","class"],properties:{action:{type:"string"},class:{type:"string"},target:{type:"string"},project:{type:"string"},host:{type:"string"}}}},{name:"life_approval_decide",description:"Record a human-driven approval decision. Acting agents must not self-approve; use this only from a human-operated host turn.",inputSchema:{type:"object",required:["id","status"],properties:{id:{type:"string"},status:{type:"string",enum:["approved","rejected"]},reason:{type:"string"},host:{type:"string"}}}},{name:"life_commitment_create",description:"Create a local project-scoped commitment with optional TTL.",inputSchema:{type:"object",required:["project","summary"],properties:{project:{type:"string"},summary:{type:"string"},due_at:{type:"string"},ttl_seconds:{type:"number"}}}},{name:"life_commitment_complete",description:"Complete a local commitment by id.",inputSchema:{type:"object",required:["id"],properties:{id:{type:"string"}}}},{name:"life_work_item_create",description:"Create a local project-scoped work item.",inputSchema:{type:"object",required:["project","title"],properties:{project:{type:"string"},title:{type:"string"},description:{type:"string"},priority:{type:"string",enum:["low","normal","high","urgent"]},tags:{type:"array",items:{type:"string"}},host:{type:"string"}}}},{name:"life_work_item_list",description:"List local work items with optional filters.",inputSchema:{type:"object",properties:{project:{type:"string"},status:{type:"string",enum:["inbox","assigned","in_progress","review","blocked","done","failed"]},priority:{type:"string",enum:["low","normal","high","urgent"]},host:{type:"string"},limit:{type:"number"}}}},{name:"life_work_item_claim",description:"Claim one work item for a host.",inputSchema:{type:"object",required:["id"],properties:{id:{type:"string"},host:{type:"string"}}}},{name:"life_work_item_update",description:"Update one work item through the shared status machine.",inputSchema:{type:"object",required:["id"],properties:{id:{type:"string"},status:{type:"string",enum:["inbox","assigned","in_progress","review","blocked","done","failed"]},priority:{type:"string",enum:["low","normal","high","urgent"]},host:{type:"string"},description:{type:"string"},tags:{type:"array",items:{type:"string"}}}}},{name:"life_work_item_complete",description:"Complete one work item as done or failed.",inputSchema:{type:"object",required:["id"],properties:{id:{type:"string"},status:{type:"string",enum:["done","failed"]}}}},{name:"life_heartbeat_claim",description:"Claim a local heartbeat lease for a project and slot.",inputSchema:{type:"object",required:["slot","host","project"],properties:{slot:{type:"string"},host:{type:"string"},project:{type:"string"},ttl_seconds:{type:"number"}}}},{name:"life_heartbeat_complete",description:"Complete a local heartbeat lease and record a run.",inputSchema:{type:"object",required:["slot","host","project"],properties:{slot:{type:"string"},host:{type:"string"},project:{type:"string"},result:{type:"string"},evidence:{type:"object"},work_item_id:{type:"string"}}}},{name:"life_onboarding_status",description:"Return onboarding ritual status, interview themes, and file_generation_rules (IDENTITY/SOUL/USER/AGENTS formats). Call before drafting files.",inputSchema:{type:"object"}},...Gi,{name:"life_onboard_apply",description:"Dry-run or apply AI-generated onboarding human files.",inputSchema:{type:"object",required:["files"],properties:{dry_run:{type:"boolean"},user_confirmed:{type:"boolean"},files:{type:"object"},config_patch:{type:"object"}}}},{name:"life_onboard_complete",description:"Archive BOOTSTRAP.md and mark onboarding ritual complete.",inputSchema:{type:"object",properties:{archive:{type:"boolean"}}}}]});if(e.method==="tools/call"){let o=await vr(t);if(!o.ok)return fe(r,o);let n=Qm(e.params);return fe(r,await zm(n.name??"",n.arguments??{},t))}if(Km.has(e.method)){let o=await vr(t);return o.ok?fe(r,await tc(e.method,Tt(e.params),t)):fe(r,o)}return wr(r,-32601,`Unknown method: ${e.method}`)}catch(o){return o instanceof Ce?wr(r,-32010,o.message,{code:o.code,id:o.id,from:o.from,to:o.to}):o instanceof ne?wr(r,-32011,o.message,{code:o.code,id:o.id,status:o.status}):wr(r,-32603,o instanceof Error?o.message:"Unknown MCP error")}}async function ec(e){let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",r=>{t+=r;let o=t.split(/\r?\n/u);t=o.pop()??"";for(let n of o){let s=n.trim();s&&Xm(s,e).catch(a=>{process.stderr.write(`NativeSoul MCP response error: ${sg(a)}
843
+ `)})}})}async function Xm(e,t){let r;try{r=JSON.parse(e)}catch{process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}
844
+ `);return}let o=await Gm(r,t);o&&process.stdout.write(`${JSON.stringify(o)}
845
+ `)}async function zm(e,t,r){let o=await tc(e,t,r);return{content:[{type:"text",text:JSON.stringify(o)}]}}async function tc(e,t,r){let o=Zi[e];if(!o)throw new Error(`Unknown tool: ${e}`);return await o(t,r)}async function Ym(e){try{let t=await mt({...e,readOnly:!0});try{await Le({home:e.home,host:e.host,outcome:"succeeded",tier:"B",cwd:t.project.cwd,project:t.project.id,tokensUsed:t.context_budget.tokens_used,tokensMax:t.context_budget.tokens_max,source:"mcp-life-bootstrap",warnings:t.warnings})}catch{}return t}catch(t){try{await Le({home:e.home,host:e.host,outcome:"failed",tier:"B",cwd:e.cwd,project:null,source:"mcp-life-bootstrap",error:t})}catch{}throw t}}function fe(e,t){return{jsonrpc:"2.0",id:e,result:t}}function wr(e,t,r,o){return{jsonrpc:"2.0",id:e,error:o===void 0?{code:t,message:r}:{code:t,message:r,data:o}}}function Qm(e){return Tt(e)}function Tt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function S(e,t){return typeof e=="string"?e:t}function D(e){return typeof e=="string"?e:void 0}function Er(e,t){return typeof e=="number"?e:t}function Xi(e){return typeof e=="number"?e:void 0}function zi(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Yi(e){if(e!==void 0){if(e==="inbox"||e==="assigned"||e==="in_progress"||e==="review"||e==="blocked"||e==="done"||e==="failed")return e;throw new Error("Invalid work item status")}}function Zm(e){if(e!==void 0){if(e==="done"||e==="failed")return e;throw new Error("Work item terminal status must be done or failed")}}function Hn(e){if(e!==void 0){if(e==="low"||e==="normal"||e==="high"||e==="urgent")return e;throw new Error("Invalid work item priority")}}function Ye(e,t){return typeof e=="boolean"?e:t}function eg(e){return Ye(e.allHosts,!1)||Ye(e.all_hosts,!1)}function tg(e){let t=Tt(e),r={};for(let[o,n]of Object.entries(t))typeof n=="string"&&(r[o]=n);return r}function rg(e){let r=Tt(e).hosts;if(!Array.isArray(r))return;let o=r.filter(n=>typeof n=="string");return o.length>0?{hosts:o}:void 0}function Qi(e){if(e==="read_local"||e==="probe_external"||e==="write_local"||e==="write_project"||e==="external_write"||e==="destructive"||e==="identity_policy_change")return e;throw new Error("Invalid policy action class")}function og(e){if(e==="approved"||e==="rejected")return e;throw new Error("life_approval_decide status must be approved or rejected")}async function ng(e){let t=await Cn(e),r=t.approval?.id??null;return t.evaluation.decision==="approval_required"?{blocked:!0,allowed:!1,decision:"approval_required",approval_id:r,approval_created:t.approval_created,wait:"human",instruction:r?`approval ${r} pending - run: nativesoul approvals approve ${r} --confirm`:"approval pending but unavailable - inspect NativeSoul approval storage",warning:t.warning}:t.evaluation.decision==="allowed"?{blocked:!1,allowed:!0,decision:"allowed",approval_id:t.approval?.id??null,approval_status:t.approval?.status??null,warning:t.warning}:t.evaluation.decision==="proposal_required"?{blocked:!1,allowed:!1,decision:"proposal_required",approval_id:null,instruction:"use the existing SOUL.md/POLICY.md proposal flow; approvals do not cover protected human files",warning:t.warning}:{blocked:!1,allowed:!1,decision:"denied",approval_id:null,instruction:"stop; denied actions are not approvable through Approval Gate",warning:t.warning}}function sg(e){return e instanceof Error?e.message:"Unknown MCP response error"}var rc=process.argv.indexOf("--home"),ag=rc>=0?process.argv[rc+1]:void 0;await ec(ag);