nativesoul 0.1.1 → 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 zi=Object.defineProperty;var Se=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(o){throw r=[o],o}};var $n=(e,t)=>{for(var r in t)zi(e,r,{get:t[r],enumerable:!0})};import{spawn as jc}from"node:child_process";import{access as Cc}from"node:fs/promises";import{constants as Nc}from"node:fs";import{existsSync as Oc}from"node:fs";import Rs from"node:path";async function le(e){let t=(process.env.PATH??"").split(Rs.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=Rs.join(o,`${e}${n}`);if(process.platform==="win32"&&Oc(s))return s;try{return await Cc(s,Nc.X_OK),s}catch{}}return null}async function Ft(e,t){return new Promise(r=>{ks(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 to(e,t,r=1e3){return new Promise(o=>{ks(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 ks(e,t,r){let n=await le(e)??e,s=process.platform==="win32"&&/\.(?:cmd|bat)$/iu.test(n);return jc(n,t,{stdio:r,shell:s})}var xe=Se(()=>{"use strict"});import{constants as Mc}from"node:fs";import{access as Lc,readFile as Dc,stat as Hc}from"node:fs/promises";import Ss from"node:os";import $c from"node:path";function v(e){return e==="~"?Ss.homedir():e.startsWith("~/")?$c.join(Ss.homedir(),e.slice(2)):e}async function b(e){try{return await Lc(e,Mc.F_OK),!0}catch{return!1}}async function I(e){try{return(await Hc(e)).isDirectory()}catch{return!1}}async function M(e){return await b(e)?Dc(e,"utf8"):null}function ae(e){let t=ws(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 ws(e){return{start:`<!-- nativesoul:${e}:start v1 -->`,end:`<!-- nativesoul:${e}:end -->`}}function $(e,t){if(!t)return!1;let r=ws(t);return e.includes(r.start)&&e.includes(r.end)}var W=Se(()=>{"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 fe(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 he(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 k(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=Se(()=>{"use strict";W()});import{readdir as Yc,readFile as Qc}from"node:fs/promises";import Os from"node:path";function Ls(e){let t=e??v("~/.claude");return Os.join(t,"scheduled-tasks")}async function Ds(e){if(!await I(e))return null;let t=await Ns(e,Ms);if(t!==null)return t;let r=await el(e);for(let o of r){let n=await Ns(e,o);if(n!==null)return n}return null}async function Ns(e,t){let r=Os.join(e,t,"SKILL.md");if(!await b(r))return null;let n=(await Qc(r,"utf8")).toLowerCase();return t===Ms||t.includes(Zc)||n.includes(`name: ${Cs}`)||n.includes(`# ${Cs}`)?`claude:scheduled-task:${t}`:null}async function el(e){try{return(await Yc(e,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>r.name)}catch{return[]}}var Ms,Zc,Cs,Hs=Se(()=>{"use strict";W();Ms="nativesoul-heartbeat",Zc="nativesoul-heartbeat",Cs="life:heartbeat"});import{mkdir as tl,readFile as rl,writeFile as ol}from"node:fs/promises";import tt from"node:path";import{fileURLToPath as nl}from"node:url";async function Fs(e){try{let t=tt.join(e,$s);await tl(t,{recursive:!0,mode:448});let r=tt.join(t,"SKILL.md"),o=await al();return await ol(r,o??sl,"utf8"),!0}catch{return!1}}async function al(){let e=tt.dirname(nl(import.meta.url)),t=[tt.resolve(process.cwd(),"plugins","claude-nativesoul","skills","life-heartbeat","SKILL.md"),tt.resolve(e,"../../../../plugins/claude-nativesoul/skills/life-heartbeat/SKILL.md")];for(let r of t)if(await b(r))return rl(r,"utf8");return null}var $s,jf,sl,Us=Se(()=>{"use strict";W();$s="nativesoul-heartbeat",jf=`claude:scheduled-task:${$s}`,sl='---\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 Vs={};$n(Vs,{discoverClaudeScheduledTasksManifest:()=>il});async function il(e={}){let t=Ls(e.hostConfigRoot);if(!e.apply&&!await I(t)||(e.surface==="claude-code"?"claude-code":"claude-desktop")==="claude-code")return null;let o=await Ds(t);return o!==null?ao({nativeId:o,evidenceSource:"filesystem"}):e.apply&&await Fs(t)?ao({nativeId:"claude:scheduled-task:nativesoul-heartbeat",evidenceSource:"filesystem-provisioned"}):await I(t)?ao({nativeId:void 0,evidenceSource:"filesystem"}):null}function ao(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 Bs=Se(()=>{"use strict";Hs();Us();W()});var ca={};$n(ca,{discoverCodexAutomationsManifest:()=>kl});import{readFile as co}from"node:fs/promises";import Wt from"node:path";import{spawnSync as hl}from"node:child_process";async function kl(e={}){let t=await Sl();if(t)return t;let r=await wl(e.hostConfigRoot);return r||(e.apply?(await Al(),await El()):null)}async function Sl(){let e=process.env.NATIVESOUL_CODEX_AUTOMATIONS_FIXTURES;if(e)try{return lo(await co(Wt.join(e,"automations.json"),"utf8"))}catch{return null}let t=process.env.NATIVESOUL_CODEX_AUTOMATIONS_MANIFEST;if(t)try{return lo(await co(t,"utf8"))}catch{return null}return null}async function wl(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 co(o,"utf8"),s=lo(n);if(s?.supported)return s;let a=de(n);if(!a)continue;let i=ia(a);if(i)return i}return null}async function El(){let e=Pl();for(let t of e)for(let r of _l){let o=await xl(()=>Tl(t,r),vl),n=ia(o);if(n)return n}return null}async function Al(){let e=await le("codex");e&&hl(e,["app-server","daemon","start"],{encoding:"utf8",stdio:"ignore",timeout:1e4})}function Pl(){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 xl(e,t){for(let r=0;r<=t;r+=1){let o=await e();if(o!==null)return o;r<t&&await Il(Rl)}return null}function Il(e){return new Promise(t=>{setTimeout(t,e)})}async function Tl(e,t){let r=new AbortController,o=setTimeout(()=>r.abort(),bl);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 ia(e){let t=jl(e);for(let r of t){let o=Cl(r),n=JSON.stringify(r).toLowerCase();if(o&&yl.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 jl(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 Cl(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 lo(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 yl,_l,bl,vl,Rl,la=Se(()=>{"use strict";W();xe();ue();yl=["life:heartbeat","nativesoul-heartbeat","life-heartbeat"],_l=["automation/list","automations/list","scheduledAutomation/list"],bl=1e3,vl=2,Rl=150});import{existsSync as Tm}from"node:fs";import{mkdirSync as lc}from"node:fs";import dc from"node:path";import{pathToFileURL as uc}from"node:url";function He(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e;if(t.source!=="host-reported")return{};let r={schema:Un(t.schema)??1,source:"host-reported"},o=wr(t.model);o&&(r.model=o);let n=Fn(t.tokens_in);n!==null&&(r.tokens_in=n);let s=Fn(t.tokens_out);s!==null&&(r.tokens_out=s);let a=Un(t.cost_usd);a!==null&&(r.cost_usd=a);let i=wr(t.currency);i?r.currency=i:a!==null&&(r.currency="USD");let c=wr(t.reported_at);return c&&(r.reported_at=c),r}function Ct(e){try{return He(JSON.parse(e))}catch{return{}}}function wr(e){return typeof e=="string"&&e.length>0?e:null}function Fn(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.trunc(e)}function Un(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}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 Er(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 Vn(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 ze(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 Ar(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 Pr(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 Ye(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 Qe(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 xr(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 Bn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e}}function Wn(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 Ir(e,t){if(!$e(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),Ee(e,t.id)}function Tr(e,t){if(!$e(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),Ee(e,t.id)}function Ee(e,t){if(!$e(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 jr(e,t){if(!$e(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 Cr(e,t){if(!$e(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 zi=Object.defineProperty;var Se=(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?Ot(r):null,warning:null}}function Nr(e,t,r){if(!$e(e))return{available:!1,approval:null,warning:"approvals_not_available"};let o=Ee(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),Ee(e,t)}function $e(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 Jn(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(n){throw e.exec("ROLLBACK"),n}}function Or(e,t){let r=e.prepare("SELECT * FROM memories WHERE id = ?").get(t);return r?we(r):null}function Kn(e,t,r){return e.prepare("UPDATE memories SET status = ? WHERE id = ?").run(r,t),Or(e,t)}function qn(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(we)}function Gn(e,t,r,o){let n=Lt(t);return n?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(n,r,o).map(we):Mr(e,r,o)}function Xn(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 Mr(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 zn(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 Ze=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 Lr(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 n=z(e,t.id);if(!n)throw new Error(`Project upsert did not return a row for ${t.id}`);return{project:n,inserted:!r}}function Dr(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(ze)}function z(e,t){let r=e.prepare("SELECT * FROM projects WHERE id = ?").get(t);return r?ze(r):null}function Hr(e,t,r,o=new Date().toISOString()){if(!et(e))return{found:!1,previous:null,project:null};let n=z(e,t);return n?(e.prepare("UPDATE projects SET display_name = ?, updated_at = ? WHERE id = ?").run(r,o,t),{found:!0,previous:n,project:z(e,t)}):{found:!1,previous:null,project:null}}function $r(e,t,r=new Date().toISOString()){return Zn(e,t,"archived",r)}function Fr(e,t,r=new Date().toISOString()){return Zn(e,t,"active",r)}function Ur(e,t){return e.prepare("SELECT COUNT(*) AS count FROM memories WHERE scope_project = ?").get(t)?.count??0}function Vr(e,t,r,o=new Date().toISOString()){if(!et(e))return{found:!1,previous:null,project:null,memories_affected:0};let n=z(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 Ze({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:z(e,t),memories_affected:s.length}}catch(s){throw e.exec("ROLLBACK"),s}}function Br(e,t={}){if(!et(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(`${Yn} ${n} ORDER BY derived_last_seen_at DESC, p.id ASC LIMIT ?`).all(...o,ec(t.limit)).map(Zi),warning:null}}function Wr(e,t){if(!et(e))return{available:!1,detail:null,warning:"registry_not_available"};let r=e.prepare(`${Yn} WHERE p.id = ?`).get(t);return r?{available:!0,detail:{project:ze(r),counts:Qn(r),derived_last_seen_at:r.last_activity_at??null},warning:null}:{available:!0,detail:tc(e,t),warning:null}}var Yn=`
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 Zi(e){return{...ze(e),counts:Qn(e),derived_last_seen_at:e.last_activity_at??null}}function Qn(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 ec(e){return!e||!Number.isFinite(e)?50:Math.min(Math.max(Math.trunc(e),1),500)}function et(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 Zn(e,t,r,o){if(!et(e))return{found:!1,previous:null,project:null};let n=z(e,t);return n?(e.prepare("UPDATE projects SET status = ?, updated_at = ? WHERE id = ?").run(r,o,t),{found:!0,previous:n,project:z(e,t)}):{found:!1,previous:null,project:null}}function tc(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:rc(i)}}function rc(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 es(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 Zi(e){return{...ze(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 ts(e,t){let r=e.prepare("SELECT * FROM semantic_memory_index WHERE memory_id = ?").get(t);return r?Er(r):null}function rs(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 Zi(e){return{...ze(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(Er)}function os(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 Zi(e){return{...ze(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 ss(r)}function ns(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,15 +168,15 @@ LEFT JOIN activity a ON a.project_id = p.id`;function Zi(e){return{...ze(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 ss(r)}function ss(e){return{indexable_count:e?.indexable_count??0,indexed_count:e?.indexed_count??0,stale_count:e?.stale_count??0}}function Jr(e,t){e.prepare(`INSERT INTO work_items (
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
172
  id, project_id, title, description, status, priority, assigned_host, source,
173
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=Fe(e,t.id);if(!r)throw new Error(`Work item not found after insert: ${t.id}`);return r}function Fe(e,t){if(!zr(e))return null;let r=e.prepare("SELECT * FROM work_items WHERE id = ?").get(t);return r?Ar(r):null}function Kr(e,t){if(!zr(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,ls(t.limit)).map(Ar)}function qr(e,t){if(!zr(e))return null;e.exec("BEGIN IMMEDIATE");try{let r=Fe(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
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
175
  SET status = ?, priority = ?, assigned_host = ?, description = ?, tags_json = ?,
176
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&&as(e,t.event);let d=Fe(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 Gr(e,t){as(e,t);let r=sc(e,t.id);if(!r)throw new Error(`Work item event not found after insert: ${t.id}`);return r}function Xr(e,t,r){return is(e)?e.prepare("SELECT * FROM work_item_events WHERE work_item_id = ? ORDER BY created_at DESC, id DESC LIMIT ?").all(t,ls(r)).map(Pr):[]}function as(e,t){e.prepare(`INSERT INTO work_item_events (
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
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 sc(e,t){if(!is(e))return null;let r=e.prepare("SELECT * FROM work_item_events WHERE id = ?").get(t);return r?Pr(r):null}function zr(e){return cs(e,"work_items")}function is(e){return cs(e,"work_item_events")}function cs(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 ls(e){return!e||!Number.isFinite(e)?50:Math.min(Math.max(Math.trunc(e),1),500)}import{createRequire as ic}from"node:module";var cc=ic(import.meta.url),Dt=null;function ds(){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=cc("node:sqlite"),Dt}finally{process.emitWarning=e}}function us(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 ps(e){e.exec(`
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(`
180
180
  CREATE TABLE IF NOT EXISTS migrations (
181
181
  version INTEGER PRIMARY KEY,
182
182
  name TEXT NOT NULL,
@@ -214,7 +214,7 @@ LEFT JOIN activity a ON a.project_id = p.id`;function Zi(e){return{...ze(e),coun
214
214
 
215
215
  CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts
216
216
  USING fts5(id UNINDEXED, summary, content);
217
- `),Ae(e,1,"initial-core-schema","sha256:initial-core-schema"),e.exec(`
217
+ `),Ie(e,1,"initial-core-schema","sha256:initial-core-schema"),e.exec(`
218
218
  CREATE TABLE IF NOT EXISTS capabilities (
219
219
  uid TEXT PRIMARY KEY,
220
220
  host TEXT NOT NULL,
@@ -234,7 +234,7 @@ LEFT JOIN activity a ON a.project_id = p.id`;function Zi(e){return{...ze(e),coun
234
234
 
235
235
  CREATE VIRTUAL TABLE IF NOT EXISTS capability_fts
236
236
  USING fts5(uid UNINDEXED, host, native_kind, normalized_kind, source);
237
- `),Ae(e,2,"capability-registry","sha256:capability-registry"),e.exec(`
237
+ `),Ie(e,2,"capability-registry","sha256:capability-registry"),e.exec(`
238
238
  CREATE TABLE IF NOT EXISTS hosts (
239
239
  id TEXT PRIMARY KEY,
240
240
  host TEXT NOT NULL,
@@ -357,7 +357,7 @@ LEFT JOIN activity a ON a.project_id = p.id`;function Zi(e){return{...ze(e),coun
357
357
  CREATE INDEX IF NOT EXISTS idx_schedules_host ON schedules(host);
358
358
  CREATE UNIQUE INDEX IF NOT EXISTS idx_leases_idempotency ON leases(idempotency_key);
359
359
  CREATE INDEX IF NOT EXISTS idx_runs_project_status ON runs(project_id, status);
360
- `),Ae(e,3,"core-domain-ledger","sha256:core-domain-ledger"),e.exec(`
360
+ `),Ie(e,3,"core-domain-ledger","sha256:core-domain-ledger"),e.exec(`
361
361
  CREATE TABLE IF NOT EXISTS semantic_memory_index (
362
362
  memory_id TEXT PRIMARY KEY,
363
363
  scope_project TEXT NOT NULL,
@@ -373,7 +373,7 @@ LEFT JOIN activity a ON a.project_id = p.id`;function Zi(e){return{...ze(e),coun
373
373
 
374
374
  CREATE INDEX IF NOT EXISTS idx_semantic_memory_project ON semantic_memory_index(scope_project);
375
375
  CREATE INDEX IF NOT EXISTS idx_semantic_memory_provider ON semantic_memory_index(provider_id, model_id);
376
- `),Ae(e,4,"semantic-memory-index","sha256:semantic-memory-index"),e.exec(`
376
+ `),Ie(e,4,"semantic-memory-index","sha256:semantic-memory-index"),e.exec(`
377
377
  CREATE TABLE IF NOT EXISTS projects (
378
378
  id TEXT PRIMARY KEY,
379
379
  display_name TEXT NOT NULL,
@@ -404,7 +404,7 @@ LEFT JOIN activity a ON a.project_id = p.id`;function Zi(e){return{...ze(e),coun
404
404
  UNION
405
405
  SELECT project_id AS p FROM sessions
406
406
  )
407
- WHERE p IS NOT NULL AND p <> ''`).run(t,t,t),Ae(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
408
  CREATE TABLE IF NOT EXISTS work_items (
409
409
  id TEXT PRIMARY KEY,
410
410
  project_id TEXT NOT NULL,
@@ -438,7 +438,7 @@ LEFT JOIN activity a ON a.project_id = p.id`;function Zi(e){return{...ze(e),coun
438
438
  CREATE INDEX IF NOT EXISTS idx_work_items_project_priority ON work_items(project_id, priority);
439
439
  CREATE INDEX IF NOT EXISTS idx_work_items_status_updated ON work_items(status, updated_at);
440
440
  CREATE INDEX IF NOT EXISTS idx_work_item_events_item ON work_item_events(work_item_id, created_at);
441
- `),Ae(e,6,"work-items-board","sha256:work-items-board"),e.exec(`
441
+ `),Ie(e,6,"work-items-board","sha256:work-items-board"),e.exec(`
442
442
  CREATE TABLE IF NOT EXISTS approvals (
443
443
  id TEXT PRIMARY KEY,
444
444
  action TEXT NOT NULL,
@@ -454,8 +454,8 @@ LEFT JOIN activity a ON a.project_id = p.id`;function Zi(e){return{...ze(e),coun
454
454
  );
455
455
 
456
456
  CREATE INDEX IF NOT EXISTS idx_approvals_status ON approvals(status);
457
- `),Ae(e,7,"approvals","sha256:approvals")}function Ae(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 ms=["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||lc(dc.dirname(t),{recursive:!0,mode:448});let{DatabaseSync:o}=ds(),n=r.readOnly?pc(t):t;this.db=new o(n,r.readOnly?{readOnly:!0}:{}),us(this.db,{readOnly:r.readOnly}),r.readOnly||ps(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(ms.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(Vn)}createApproval(t){return Ir(this.db,t)}createDecidedApproval(t){return Tr(this.db,t)}getApproval(t){return Ee(this.db,t)}listApprovals(t){return jr(this.db,t)}findPendingApprovalMatch(t){return Cr(this.db,t)}decideApproval(t,r){return Nr(this.db,t,r)}insertWorkItem(t){return Jr(this.db,t)}getWorkItem(t){return Fe(this.db,t)}listWorkItems(t){return Kr(this.db,t)}updateWorkItem(t){return qr(this.db,t)}insertWorkItemEvent(t){return Gr(this.db,t)}listWorkItemEvents(t,r){return Xr(this.db,t,r)}insertMemory(t){Jn(this.db,t)}getMemory(t){return Or(this.db,t)}updateMemoryStatus(t,r){return Kn(this.db,t,r)}listMemories(t){return qn(this.db,t)}upsertProject(t){return Lr(this.db,t)}getProject(t){return z(this.db,t)}listProjects(t){return Dr(this.db,t)}listProjectsWithCounts(t={}){return Br(this.db,t)}getProjectDetail(t){return Wr(this.db,t)}renameProject(t,r,o){return Hr(this.db,t,r,o)}archiveProject(t,r){return $r(this.db,t,r)}reactivateProject(t,r){return Fr(this.db,t,r)}countProjectMemories(t){return Ur(this.db,t)}forgetProjectMemories(t,r,o){return Vr(this.db,t,r,o)}searchMemories(t,r,o){return Gn(this.db,t,r,o)}listActiveMemoriesForProject(t,r){return Xn(this.db,t,r)}recentMemories(t,r){return Mr(this.db,t,r)}listSemanticIndexableMemories(t){return zn(this.db,t)}upsertSemanticIndex(t){es(this.db,t)}getSemanticIndex(t){return ts(this.db,t)}listCurrentSemanticIndexesForProject(t){return rs(this.db,t)}semanticIndexStatsForProject(t){return os(this.db,t)}semanticIndexStats(t){return ns(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 (
459
459
  uid, host, native_kind, normalized_kind, source, schema_hash,
460
460
  installed, enabled, active, authenticated, healthy, allowed, ready, last_seen_at
461
461
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -478,12 +478,12 @@ LEFT JOIN activity a ON a.project_id = p.id`;function Zi(e){return{...ze(e),coun
478
478
  WHERE ${o.join(" AND ")}
479
479
  ORDER BY rank
480
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=gs(t.summary),n=this.listCommitments({project:t.project_id,status:"open",includeExpired:!1,limit:200,now:r,skipExpire:!0}).find(a=>gs(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)
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
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
483
483
  SET holder = ?, expires_at = ?, status = 'claimed', created_at = ?, completed_at = NULL
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:Ye(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:Ye(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(He(t.cost)),JSON.stringify(t.result),JSON.stringify({...Bn(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:${Wn(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(Ye)}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(Qe)}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(Qe)}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
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
487
  runs.id,
488
488
  runs.kind,
489
489
  runs.host,
@@ -513,13 +513,13 @@ LEFT JOIN activity a ON a.project_id = p.id`;function Zi(e){return{...ze(e),coun
513
513
  native_schedule_supported = excluded.native_schedule_supported,
514
514
  native_id = excluded.native_id,
515
515
  desired_json = excluded.desired_json,
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(xr)}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?Ye(r):null}getHeartbeatRunById(t){let r=this.db.prepare("SELECT * FROM runs WHERE id = ?").get(t);return r?Qe(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 *
517
517
  FROM runs
518
518
  WHERE kind = 'heartbeat'
519
519
  AND project_id = ?
520
520
  AND json_extract(evidence_json, '$.slot') = ?
521
521
  ORDER BY completed_at DESC, id DESC
522
- LIMIT 1`).get(t,r);return o?Qe(o):null}getSchedule(t){let r=this.db.prepare("SELECT * FROM schedules WHERE id = ?").get(t);return r?xr(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 mc(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 pc(e){return`${uc(e).href}?mode=ro&immutable=1`}function gs(e){return e.trim().replace(/\s+/gu," ").toLocaleLowerCase()}function mc(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 Ac,mkdir as Pc}from"node:fs/promises";import xc from"node:os";import Ic from"node:path";import{createHash as gc,randomUUID as fc}from"node:crypto";function A(e){return`${e}_${fc()}`}function B(e){return`sha256:${gc("sha256").update(e).digest("hex")}`}function Yr(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(r=>Yr(r)).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${Yr(e[r]??null)}`).join(",")}}`}function Pe(e){return B(Yr(e))}import{existsSync as xg}from"node:fs";import Tg from"node:os";var fs=[{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 yc=fs.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 yc)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 _s,readFile as _c,writeFile as Qr}from"node:fs/promises";import{constants as bc,existsSync as bs}from"node:fs";import{access as vc}from"node:fs/promises";import Rc from"node:os";import se from"node:path";var $t={"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
523
523
 
524
524
  _Injected into every supported host via managed blocks. Keep operational rules here._
525
525
 
@@ -794,7 +794,7 @@ recall:
794
794
  - test
795
795
  - build
796
796
  note: UserPromptSubmit recall hooks are opt-in for first ship.
797
- `},hs=`id: example-read-only
797
+ `},_s=`id: example-read-only
798
798
  allowed:
799
799
  - memory_search
800
800
  - life_recall
@@ -804,7 +804,7 @@ approval_required:
804
804
  - external_write
805
805
  - destructive_action
806
806
  source: standing-orders/example.yaml
807
- `;function ys(e){return`# Daily notes \u2014 ${e}
807
+ `;function bs(e){return`# Daily notes \u2014 ${e}
808
808
 
809
809
  _Running context for today. Promote durable facts to curated memory later._
810
810
 
@@ -819,13 +819,13 @@ _Running context for today. Promote durable facts to curated memory later._
819
819
  ## Follow-ups
820
820
 
821
821
  -
822
- `}var kc=["memory/daily","memory/projects","memory/archive","commitments","standing-orders","capabilities/cards","generated","state","logs","backups","proposals"],Sc=$t;function vs(e){return se.resolve(e??process.env.NATIVESOUL_HOME??se.join(Rc.homedir(),".nativesoul"))}function p(e){let t=vs(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 vc(e,bc.F_OK),!0}catch{return!1}}async function _(e){let t=p(e),r=[],o=[],n=[];bs(t.home)||(await _s(t.home,{recursive:!0,mode:448}),r.push(t.home));for(let i of kc){let c=se.join(t.home,i);bs(c)||(await _s(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(Sc)){if(i==="BOOTSTRAP.md"&&s)continue;let l=se.join(t.home,i);if(await y(l)){n.push(l);continue}try{await Qr(l,c,{encoding:"utf8",mode:384,flag:"wx"}),o.push(l)}catch(u){if(wc(u)){n.push(l);continue}throw u}}let a=await Ec(t.home);return o.push(...a.createdFiles),n.push(...a.preservedFiles),{home:t.home,database:t.database,createdDirectories:r,createdFiles:o,preservedFiles:n}}function wc(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}async function Ec(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 Qr(n,ys(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 Qr(s,hs,{encoding:"utf8",mode:384,flag:"wx"}),t.push(s)),{createdFiles:t,preservedFiles:r}}async function Y(e,t){let r=se.join(e,t);return await y(r)?_c(r,"utf8"):""}async function m(e){let t=p(e.home),r=new Date().toISOString(),o=eo(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:Pe({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 Pc(Ic.dirname(t.auditLog),{recursive:!0,mode:448}),await Ac(t.auditLog,`${JSON.stringify(n)}
823
- `,{encoding:"utf8",mode:384}),n}function eo(e,t){if(typeof e=="string")return Tc(e,t);if(Array.isArray(e))return e.map(r=>eo(r,t));if(e&&typeof e=="object"){let r={};for(let[o,n]of Object.entries(e))r[o]=eo(n,t);return r}return e}function Tc(e,t){return[[new RegExp(Zr(t),"gu"),"[REDACTED_NATIVESOUL_HOME]"],[new RegExp(Zr(process.cwd()),"gu"),"[REDACTED_WORKSPACE]"],[new RegExp(Zr(xc.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 Zr(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}import je from"node:path";import{mkdir as Hh,readdir as id,readFile as cd,writeFile as $h}from"node:fs/promises";import{existsSync as Uh}from"node:fs";import xa from"node:path";xe();W();ue();W();import{readdir as Fc}from"node:fs/promises";import q from"node:path";var Q="antigravity",Uc="~/.gemini/GEMINI.md",Vc="~/.antigravity",ro="official:antigravity-plugin-config:v1",Es="official:antigravity-hooks-config:v1",As="official:antigravity-mcp-config:v1",Ps="official:antigravity-command-config:v1",Bc="official:antigravity-context-config:v1",Wc="official:antigravity-features:v1",Jc=[{uid:"antigravity:plugins",nativeKind:"plugins",normalizedKind:"package",relativePath:"plugins"}];function oo(){let e=process.env.NATIVESOUL_ANTIGRAVITY_INVENTORY_ROOT?.trim();return e?q.resolve(e):v(Vc)}function Kc(){let e=oo();return{root:e,globalInstruction:process.env.NATIVESOUL_ANTIGRAVITY_INVENTORY_ROOT?.trim()?q.join(e,"GEMINI.md"):v(Uc)}}async function xs(){let e=[],t=Kc();await b(t.globalInstruction)&&e.push({uid:"antigravity:global-gemini-md",host:Q,nativeKind:"global_context",normalizedKind:"instruction",source:t.globalInstruction,schemaHash:Bc}),await qc(t.root,e),await Gc(t.root,e);for(let r of Jc){let o=q.join(t.root,r.relativePath);await I(o)&&e.push({uid:r.uid,host:Q,nativeKind:r.nativeKind,normalizedKind:r.normalizedKind,source:o,schemaHash:ro})}return e}async function qc(e,t){let r=q.join(e,"plugin.json"),o=q.join(e,"nativesoul-package.json"),n=q.join(e,"hooks.json"),s=q.join(e,"mcp_config.json"),[a,i,c,l]=await Promise.all([H(r),H(o),H(n),H(s)]);if(a){let u=k(a,["name","id"])??"unknown";t.push({uid:`antigravity:plugin:${E(u)}`,host:Q,nativeKind:"plugin",normalizedKind:"extension",source:r,schemaHash:ro})}if(i){let u=k(i,["name","id"])??"unknown";t.push({uid:`antigravity:package:${E(u)}`,host:Q,nativeKind:"native_plugin_package",normalizedKind:"package",source:o,schemaHash:ro});let d=w(i.nativeSoul)?i.nativeSoul:{};for(let P of Ut(d.commands))t.push({uid:`antigravity:command:${E(P)}`,host:Q,nativeKind:"command",normalizedKind:"command",source:`${o}:nativeSoul.commands.${P}`,schemaHash:Ps});let h=w(d.mcpServer)?d.mcpServer:null,g=k(h,["name"]);g&&t.push({uid:`antigravity:mcp:${E(g)}`,host:Q,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${o}:nativeSoul.mcpServer.${g}`,schemaHash:As})}if(c){t.push({uid:"antigravity:hooks:manifest",host:Q,nativeKind:"hooks",normalizedKind:"lifecycle_hooks",source:n,schemaHash:Es});let u=w(c.hooks)?c.hooks:{};for(let d of Object.keys(u))t.push({uid:`antigravity:hook:${E(d)}`,host:Q,nativeKind:"hook",normalizedKind:"lifecycle_hook",source:`${n}:hooks.${d}`,schemaHash:Es})}if(l)for(let u of fe(l.mcpServers))t.push({uid:`antigravity:mcp:${E(u)}`,host:Q,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${s}:mcpServers.${u}`,schemaHash:As});await Xc(q.join(e,"commands"),t)}async function Gc(e,t){let r=q.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:Q,nativeKind:"product_feature",normalizedKind:"feature_evidence",source:`${r}:${s}`,schemaHash:Wc})}async function Xc(e,t){if(!await I(e))return;let r=await Fc(e,{withFileTypes:!0});for(let o of r){if(!o.isFile()||q.extname(o.name)!==".md")continue;let n=q.basename(o.name,".md");t.push({uid:`antigravity:command:${E(n,{allowSlash:!0})}`,host:Q,nativeKind:"command",normalizedKind:"command",source:q.join(e,o.name),schemaHash:Ps})}}W();ue();import Vt from"node:path";async function Is(e){let t=await zc(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:k(r.contract,["schedule"])??void 0,status:k(r.contract,["status"])??void 0,cancel:k(r.contract,["cancel"])??void 0,list:k(r.contract,["list"])??void 0,project_binding:k(r.contract,["project_binding"])??void 0}:void 0}:null}async function zc(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 Ts(e){if(!e)return!1;let t=Date.parse(e);return Number.isFinite(t)?Date.now()-t>10080*60*1e3:!0}var Ue="antigravity",no="~/.gemini/GEMINI.md",so=class{async detect(){let t=v(no),r=oo(),[o,n,s]=await Promise.all([b(t),I(r),le("agy")]);return{host:Ue,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 xs()}async hotProbe(){let t=await this.coldScan();return{host:Ue,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 Is(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(Ts(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(no),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,Ue)&&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(no),r=await M(t);return{host:Ue,targetPath:t,startMarker:"<!-- nativesoul:antigravity:start v1 -->",endMarker:"<!-- nativesoul:antigravity:end -->",content:ae(Ue),wouldCreate:r===null,wouldUpdate:r!==null&&!$(r,Ue)}}};function js(){return new so}xe();ue();W();import Ve from"node:path";import{readFile as Ys}from"node:fs/promises";ue();import{readFile as Ws}from"node:fs/promises";import cl from"node:path";var qs="life:heartbeat";function Gs(e){if(!e||typeof e!="object"||Array.isArray(e))return{kind:"unknown",mode:"leader",apply:!1,skill:qs};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:pl(t),surface:Ks(t.surface)??Ks(w(t.desired)?t.desired.surface:void 0)}}async function Xs(e={}){let t=process.env.NATIVESOUL_CLAUDE_SCHEDULED_TASKS_FIXTURES;if(t)try{return Js(await Ws(cl.join(t,"scheduled-tasks.json"),"utf8"))}catch{return null}let r=process.env.NATIVESOUL_CLAUDE_SCHEDULED_TASKS_MANIFEST;if(r)try{return Js(await Ws(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(()=>(Bs(),Vs));return o({apply:e.apply,surface:e.surface,hostConfigRoot:e.hostConfigRoot})}function zs(e,t){return!e||e==="default"||!t?!0:e===t}function Js(e){let t=de(e);if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,o=ll(r.surface),n=dl(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:ul(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 Ks(e){return e==="default"||e==="claude-code"||e==="claude-desktop"?e:void 0}function ll(e){return e==="claude-code"||e==="claude-desktop"||e==="cloud"?e:void 0}function dl(e){return e==="local_scheduled_task"||e==="cloud_routine"||e==="ui_only"?e:"unknown"}function ul(e){return e==="official_machine_readable"||e==="ui_only"||e==="unknown"?e:void 0}function pl(e){return w(e.desired)&&typeof e.desired.skill=="string"&&e.desired.skill.trim().length>0?e.desired.skill.trim():qs}var J="claude",Bt="~/.claude/CLAUDE.md",Qs="CLAUDE.md",Zs=".claude/CLAUDE.md",ea="life:heartbeat",ra="official:claude-cli-hot-scan:v1",io=class{async detect(){let t=v(Bt),r=Ve.resolve(Qs),o=Ve.resolve(Zs),[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=Ve.resolve(Qs),o=Ve.resolve(Zs),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 ml(o,r);if(c.status==="ready")return c}let[n,s]=await Promise.all([to("claude",["mcp","list","--json"],1200),to("claude",["plugin","list","--json"],1200)]),a=[],i=[];return n.status==="ok"?i.push(...oa(n.stdout)):a.push(ta("CLAUDE_HOT_SCAN_JSON_UNSUPPORTED","claude mcp list --json",n.stderr)),s.status==="ok"?i.push(...na(s.stdout)):a.push(ta("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=Gs(t),o=await Xs({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!==ea?{status:"error",code:"CLAUDE_HEARTBEAT_SKILL_MISMATCH",message:`Claude heartbeat Scheduled Task must invoke ${ea}.`}: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."}:zs(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 ml(e,t){try{let[r,o]=await Promise.all([Ys(Ve.join(e,"mcp-list.json"),"utf8"),Ys(Ve.join(e,"plugin-list.json"),"utf8")]),n=[...oa(r),...na(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 oa(e){let t=de(e);return he(t,["servers","mcps","items"]).flatMap(r=>{let o=k(r,["name","id","server","server_name"]);if(!o)return[];let n=k(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:ra,enabled:s,active:s,authenticated:U(r,["authenticated"])??a,healthy:s,ready:sa(n)}]})}function na(e){let t=de(e);return he(t,["plugins","items"]).flatMap(r=>{let o=k(r,["id","plugin","package"])??k(r,["name"]);if(!o)return[];let n=k(r,["status","state"]),s=U(r,["enabled"])??n!=="disabled",a=U(r,["installed"])??!0;return[{uid:`claude:plugin:${gl(o)}`,host:J,nativeKind:"plugin",normalizedKind:"extension",source:`claude plugin list --json:${o}`,schemaHash:ra,installed:a,enabled:s,active:s,authenticated:U(r,["authenticated"])??s,healthy:a,ready:s&&(n===null||sa(n)||U(r,["enabled"])===!0)}]})}function ta(e,t,r){let o=fl(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 sa(e){return e==="ready"||e==="enabled"||e==="active"||e==="ok"||e==="authenticated"||e==="connected"}function gl(e){return E(e,{allowSlash:!0})}function fl(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 aa(){return new io}xe();ue();W();import po from"node:path";var V="codex",Jt="~/.codex/AGENTS.md",da="AGENTS.md",Nl=1e3,ua="life:heartbeat",qt="official:codex-app-server:v1",mo=class{async detect(){let t=v(Jt),r=po.resolve(da),[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=po.resolve(da),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=$l(t);if(o){let i=await uo(o,r);if(i.status==="ready")return i}let n=process.env.NATIVESOUL_CODEX_APP_SERVER_FIXTURES?.trim();if(n){let i=await uo(Ul(n),r);if(i.status==="ready")return i}let s=Fl(t);if(s){let i=await uo(Vl(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(()=>(la(),ca)),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!==ua?{status:"error",code:"CODEX_HEARTBEAT_SKILL_MISMATCH",message:`Codex heartbeat Automation must invoke ${ua}.`}: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 uo(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=[...Ml(r),...Ll(o),...Dl(n),...Hl(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 Ol(e,t){let r=new AbortController,o=setTimeout(()=>r.abort(),Nl);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 Ml(e){return he(e,["servers","mcpServers","items"]).flatMap(t=>{let r=k(t,["id","name","server","server_name"]);if(!r)return[];let o=k(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 Ll(e){return he(e,["plugins","items"]).flatMap(t=>{let r=k(t,["id","plugin","package"])??k(t,["name"]);if(!r)return[];let o=k(t,["status","state"]),n=Gt(t,o);return[{uid:`codex:plugin:${go(r)}`,host:V,nativeKind:"plugin",normalizedKind:"extension",source:`codex app server plugin/list:${r}`,schemaHash:qt,...n}]})}function Dl(e){return he(e,["skills","items"]).flatMap(t=>{let r=k(t,["id","name","path"]);if(!r)return[];let o=k(t,["status","state"]),n=Gt(t,o);return[{uid:`codex:skill:${go(r)}`,host:V,nativeKind:"skill",normalizedKind:"skill",source:`codex app server skills/list:${r}`,schemaHash:qt,...n}]})}function Hl(e){return he(e,["apps","items"]).flatMap(t=>{let r=k(t,["id","name","app"]);if(!r)return[];let o=k(t,["status","state"]),n=Gt(t,o);return[{uid:`codex:app:${go(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 $l(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 Fl(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 Ul(e){return{async call(t){try{let{readFile:r}=await import("node:fs/promises"),o=t.replace(/\//gu,"-");return JSON.parse(await r(po.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 Vl(e){return{call:t=>Ol(e,t)}}function go(e){return E(e,{allowSlash:!0})}function pa(){return new mo}xe();ue();W();import{readdir as ga}from"node:fs/promises";import Z from"node:path";var F="gemini",ho="~/.gemini/GEMINI.md",Bl="~/.gemini/extensions",Wl="~/.gemini/settings.json",rt="official:gemini-extension-config:v1",fo="official:gemini-settings-config:v1",Jl="official:gemini-memory-config:v1",yo=class{async detect(){let t=ma(),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=ma(),o=r.globalInstruction;await b(o)&&t.push({uid:"gemini:global-gemini-md",host:F,nativeKind:"global_context",normalizedKind:"memory",source:o,schemaHash:Jl}),await Kl(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:rt});let s=await ga(n,{withFileTypes:!0});for(let a of s)a.isDirectory()&&await ql(Z.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(ho),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(ho),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 ma(){let e=process.env.NATIVESOUL_GEMINI_INVENTORY_ROOT?.trim();if(e){let t=Z.resolve(e);return{globalInstruction:Z.join(t,"GEMINI.md"),settingsFile:Z.join(t,"settings.json"),extensionsDirectory:Z.join(t,"extensions")}}return{globalInstruction:v(ho),settingsFile:v(Wl),extensionsDirectory:v(Bl)}}async function Kl(e,t){let r=await H(e);if(r){t.push({uid:"gemini:settings",host:F,nativeKind:"settings",normalizedKind:"config",source:e,schemaHash:fo});for(let o of fe(r.mcpServers))t.push({uid:`gemini:mcp:${E(o)}`,host:F,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${e}:mcpServers.${o}`,schemaHash:fo});for(let o of fa(r.tools))t.push({uid:`gemini:tool:${E(o)}`,host:F,nativeKind:"tool",normalizedKind:"tool",source:`${e}:tools.${o}`,schemaHash:fo})}}async function ql(e,t,r){let o=Z.join(e,"gemini-extension.json"),n=await H(o),s=k(n,["name","id"])??t;if(r.push({uid:`gemini:extension:${E(s)}`,host:F,nativeKind:"extension",normalizedKind:"package",source:n?o:e,schemaHash:n?rt:void 0}),n){for(let a of fe(n.mcpServers))r.push({uid:`gemini:mcp:${E(a)}`,host:F,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${o}:mcpServers.${a}`,schemaHash:rt});for(let a of fa(n.tools))r.push({uid:`gemini:tool:${E(a)}`,host:F,nativeKind:"tool",normalizedKind:"tool",source:`${o}:tools.${a}`,schemaHash:rt})}await Gl(Z.join(e,"commands"),r)}async function Gl(e,t){if(!await I(e))return;let r=await ga(e,{withFileTypes:!0});for(let o of r){if(!o.isFile()||![".toml",".md"].includes(Z.extname(o.name)))continue;let n=Z.basename(o.name,Z.extname(o.name));t.push({uid:`gemini:command:${E(n,{allowSlash:!0})}`,host:F,nativeKind:"command",normalizedKind:"command",source:Z.join(e,o.name),schemaHash:rt})}}function fa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):fe(e)}function ha(){return new yo}xe();ue();W();import{readdir as Ra}from"node:fs/promises";import j from"node:path";var T="grok",Xt="~/.grok/Agents.md",ya="AGENTS.md",_a="Agents.md",ba="CLAUDE.md",Xl="~/.grok",_o="official:grok-plugin-config:v1",va="official:grok-hooks-config:v1",bo="official:grok-mcp-config:v1",ka="official:grok-command-config:v1",zl="official:grok-context-config:v1",Yl=[{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"}],vo=class{async detect(){let t=v(Xt),r=j.resolve(ya),o=j.resolve(_a),n=j.resolve(ba),s=Sa(),[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=Ql(),o=r.globalInstruction;await b(o)&&t.push({uid:"grok:global-agents-md",host:T,nativeKind:"global_context",normalizedKind:"instruction",source:o,schemaHash:zl});let n=j.resolve(ya);await b(n)&&t.push({uid:"grok:project-agents-md",host:T,nativeKind:"project_context",normalizedKind:"instruction",source:n});let s=j.resolve(_a);await b(s)&&t.push({uid:"grok:project-agents-titlecase-md",host:T,nativeKind:"project_context",normalizedKind:"instruction",source:s});let a=j.resolve(ba);await b(a)&&t.push({uid:"grok:project-claude-md",host:T,nativeKind:"project_context",normalizedKind:"instruction",source:a});let i=r.root;await wa(r.root,t),await Zl(i,t);for(let c of Yl){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"?bo:_o})}return td(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 Sa(){let e=process.env.NATIVESOUL_GROK_INVENTORY_ROOT?.trim();return e?j.resolve(e):v(Xl)}function Ql(){let e=Sa();return{root:e,globalInstruction:process.env.NATIVESOUL_GROK_INVENTORY_ROOT?.trim()?j.join(e,"Agents.md"):v(Xt)}}async function wa(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=k(a,["name","id"])??"unknown";t.push({uid:`grok:plugin:${E(u)}`,host:T,nativeKind:"plugin",normalizedKind:"extension",source:r,schemaHash:_o})}if(i){let u=k(i,["name","id"])??"unknown";t.push({uid:`grok:package:${E(u)}`,host:T,nativeKind:"native_plugin_package",normalizedKind:"package",source:o,schemaHash:_o});let d=w(i.nativeSoul)?i.nativeSoul:{};for(let P of Ut(d.commands))t.push({uid:`grok:command:${E(P)}`,host:T,nativeKind:"command",normalizedKind:"command",source:`${o}:nativeSoul.commands.${P}`,schemaHash:ka});let h=w(d.mcpServer)?d.mcpServer:null,g=k(h,["name"]);g&&t.push({uid:`grok:mcp:${E(g)}`,host:T,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${o}:nativeSoul.mcpServer.${g}`,schemaHash:bo})}if(c){t.push({uid:"grok:hooks:manifest",host:T,nativeKind:"hooks",normalizedKind:"lifecycle_hooks",source:n,schemaHash:va});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:va})}if(l)for(let u of fe(l.mcpServers))t.push({uid:`grok:mcp:${E(u)}`,host:T,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${s}:mcpServers.${u}`,schemaHash:bo});await ed(j.join(e,"commands"),t)}async function Zl(e,t){let r=j.join(e,"plugins");if(!await I(r))return;let o=await Ra(r,{withFileTypes:!0});for(let n of o)n.isDirectory()&&await wa(j.join(r,n.name),t)}async function ed(e,t){if(!await I(e))return;let r=await Ra(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:ka})}}function td(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 Ea(){return new vo}import{mkdir as yh,readFile as rd,rm as _h,writeFile as bh}from"node:fs/promises";import{existsSync as od}from"node:fs";import kh from"node:path";function nd(e){return{start:`<!-- nativesoul:${e}:start v1 -->`,end:`<!-- nativesoul:${e}:end -->`}}async function Aa(e){let t=od(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 rd(e.targetPath,"utf8"),n=nd(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 sd=["codex","claude","grok","antigravity","gemini"],ad={codex:pa,claude:aa,grok:Ea,antigravity:js,gemini:ha};function Be(e){return e==="all"?sd:[e]}function Pa(e){return Be(e)}function Ro(e){return ad[e]()}async function ko(e){let t=[];for(let r of Pa(e)){let o=Ro(r);t.push({host:r,diagnostics:await o.doctor({})})}return t}async function We(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=ja(e.limit);try{return r.listCapabilities({host:e.host,readyOnly:e.readyOnly,limit:o,includeShared:e.includeShared})}finally{r.close()}}async function So(e){let t=await _(e.home),r=f(t.database),o=ja(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 wo(e){let t=await _(e.home),r=f(t.database);try{return r.getCapability(e.uid)}finally{r.close()}}async function Eo(e){let t=e.readOnly?p(e.home):await _(e.home),r=xa.join(t.home,"capabilities","cards"),o=[];if(!await y(r))return{cards:[],warnings:o};let n=(await id(r)).filter(l=>l.endsWith(".json")).sort(),s=gd(e.query??""),a=[];for(let l of n){let u=xa.join(r,l),d;try{d=await cd(u,"utf8")}catch{o.push(`CAPABILITY_CARD_UNREADABLE:${l}`);continue}let h=dd(d);if(!h){o.push(`CAPABILITY_CARD_MALFORMED:${l}`);continue}let g=ud(h,e.host);a.push({card:g,score:pd(h,e.host,s)})}let i=fd(e.limit),c=a.sort((l,u)=>u.score-l.score||l.card.uid.localeCompare(u.card.uid));return{cards:ld(c,i).map(l=>l.card),warnings:o}}function ld(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 dd(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Ia(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)||!md(r)?null:t}function ud(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:ot(e.use_when).slice(0,2),requires:ot(e.requires).slice(0,4),approval:e.approval,alternative_host:r,available_on_other_host:o}}function pd(e,t,r){let o=Ta([e.uid,e.host,e.native_kind,e.normalized_kind,e.source,e.schema_hash,...ot(e.use_when),...ot(e.requires),e.approval,...ot(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 ot(e){return e.filter(t=>typeof t=="string")}function Ia(e){return typeof e=="object"&&e!==null}function md(e){return Ia(e)?["installed","enabled","active","authenticated","healthy","allowed","ready"].every(t=>typeof e[t]=="boolean"):!1}function gd(e){return Ta(e).split(/\s+/u).map(t=>t.trim()).filter(t=>t.length>=2)}function Ta(e){return e.toLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/gu,"")}function ja(e){return Math.min(Math.max(e??50,1),100)}function fd(e){return Math.min(Math.max(e??5,1),8)}async function Ao(e){let t=await _(e.home),r=N(e.summary).value,o=new Date,n=e.ttlSeconds?new Date(o.getTime()+yd(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 Po(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 xo(e,t){return hd(e,t,"completed","commitment_completed")}async function hd(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 yd(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),365*24*60*60):1440*60}import{createHash as _d}from"node:crypto";import{existsSync as zt,mkdirSync as bd,realpathSync as vd,readFileSync as Na,writeFileSync as Rd}from"node:fs";import{spawnSync as Oa}from"node:child_process";import ie from"node:path";function pe(e,t){let r=Io(e),o=Ed(r),n=o?Ad(o):null,s=n?Ca(n):o??r,a=Pd(s),i=n?"git-remote":o?"git-root":"path",c=Sd(a,s),l=kd(r),u=l?Ma(l):null,d=Da(t),h=[u,c,n?Ca(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 Ma(e){if(!zt(e))return null;let t=Na(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?wd(o):null}function La(e,t){let r=ie.join(e,".nativesoul","project");return bd(ie.dirname(r),{recursive:!0,mode:448}),Rd(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}:(La(r,t.base_id),{written:!0,marker_path:o,base_id:t.base_id})}function kd(e){let t=Io(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 Sd(e,t){let r=_d("sha256").update(t).digest("hex").slice(0,10);return`${xd(e)}-${r}`}function wd(e){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"workspace"}function Io(e){try{return vd(ie.resolve(e))}catch{return ie.resolve(e)}}function Ed(e){let t=Oa("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?Io(r):null}function Ad(e){let t=Oa("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 Ca(e){return e.trim().replace(/^git@([^:]+):/,"https://$1/").replace(/^ssh:\/\/git@([^/]+)\//,"https://$1/").replace(/^https?:\/\/([^/]+)\//,"https://$1/").replace(/\.git$/u,"").toLowerCase()}function Pd(e){let t=e.replace(/\/+$/u,"");return ie.basename(t)||"workspace"}function xd(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"workspace"}function Da(e){if(!e)return{};let t=ie.join(ie.resolve(e),"config.yaml");if(!zt(t))return{};let r=Na(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 dy,writeFile as uy}from"node:fs/promises";import my from"node:path";import Ey from"node:path";var Id={minLength:1,removeStopwords:!1,normalizeDiacritics:!1};function Qt(e,t={}){let r={...Id,...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||!Td.has(n))??[]))}function Ha(e,t={}){return new Set(Qt(e,t))}function To(e,t){let r=Qt(e);if(r.length===0)return 0;let o=Ha(t),n=r.filter(s=>o.has(s)).length;return Number((n/r.length).toFixed(6))}function $a(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 Td=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 Ua(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:Fa(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,To(e.query,`${d.summary}
825
- ${d.content}`)])),l=jd(e.query),u=s.map(d=>{let h=i.get(d.memory_id);if(!h)return null;let g=c.get(h.id)??0,P=$a(l,d.embedding);return{memory:h,ftsScore:g,semanticScore:P,score:Number((g*.55+P*.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:Fa(o,e.query)}}finally{t.close()}}function jd(e){let r=Array.from({length:32},()=>0);for(let n of Qt(e)){let s=Cd(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 Fa(e,t){return e.map((r,o)=>({...r,recall:{mode:"fts",fts_score:To(t,`${r.summary}
826
- ${r.content}`),semantic_score:0,final_rank:o+1,reason:"fts_fallback"}}))}function Cd(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 nt(e,t=160){let r=e.replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-3)}...`}function st(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 Ie=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}},Nd=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 _(e),o=await Od(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 it(e,t){return sr(e,t,"active","memory_promoted")}async function ct(e,t){return sr(e,t,"rejected","memory_rejected")}async function lt(e,t){return sr(e,t,"forgotten","memory_forgotten")}async function jo(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 Od(e,t,r){let o=N(t.content),n=new Date().toISOString(),s=nt(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:Pe({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&&!Co(a.status,r))throw new Ie({id:t,from:a.status,to:r});i=a?s.updateMemoryStatus(t,r):null}catch(c){throw c instanceof Ie&&await Md({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 Co(e,t){return Nd.get(e)?.has(t)??!1}async function Md(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 dt(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 No(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:Va(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:Va(e.resolution)}}),{touched:!0,inserted:o.inserted,degraded:!1,warning:null}}catch(o){return{touched:!1,inserted:!1,degraded:!0,warning:`PROJECT_REGISTRY_UNAVAILABLE:${Ld(o)}`}}finally{r?.close()}}function Va(e){return e.remote??e.git_root??e.cwd}function Ld(e){return(e instanceof Error?e.message:String(e)).replace(/[^a-zA-Z0-9_.:-]+/g,"_").slice(0,120)}var Dd=/^-\s*\*\*([^:*]+):\*\*\s*(.*)$/u;function Te(e,t){let r=Hd(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(Dd);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 Ba(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 Wa(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 Hd(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 ut(e){let t=e.readOnly?p(e.home):await _(e.home),r=await Ud(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 No({home:t.home,resolution:s});O.warning&&n.push(O.warning)}let i=Vd({explicitQuery:e.query,project:a,host:e.host,cwd:e.cwd,seed:r.memoryQuerySeed}),c=await $d({database:t.database,readOnly:e.readOnly===!0,memoryQuery:i,project:a,limit:r.recallLimit,warnings:n}),l=await We({home:t.home,host:e.host,readyOnly:!0,limit:8,readOnly:e.readOnly}),u=await Jd(t.home,e.host,e.readOnly===!0),d=await Eo({home:t.home,host:e.host,query:e.query??`${je.basename(e.cwd)} ${e.host}`,limit:8,readOnly:e.readOnly}),h=await Po({home:t.home,project:a,status:"open",limit:8,readOnly:e.readOnly}),g=await Y(t.home,"IDENTITY.md"),P=await Y(t.home,"SOUL.md"),re=await Y(t.home,"AGENTS.md"),K=await Y(t.home,"USER.md"),Le=await Y(t.home,"BOOTSTRAP.md"),De=new Date().toISOString().slice(0,10),Tt=je.join(t.home,"memory","daily",`${De}.md`);n.push(...u?[]:[`HOST_ADAPTER_UNAVAILABLE:${e.host}`,"CAPABILITY_REFRESH_STALE"],...d.warnings),!await y(je.join(t.home,"state","onboarding.complete"))&&Le.trim().length>0&&n.push("BOOTSTRAP_RITUAL_PENDING"),await y(Tt)&&n.push(`DAILY_MEMORY_AVAILABLE:${Tt}`),r.warnEmptyMemories&&c.length===0&&n.push("PROJECT_MEMORY_EMPTY");let jt={bootstrap_schema:2,identity:{name:Te(g,"Name")??"NativeSoul",mission:Te(g,"Mission")??"Provide local continuity across native coding-agent hosts.",creature:Te(g,"Creature"),role:Te(g,"Role"),vibe:Te(g,"Vibe"),emoji:Te(g,"Emoji")},soul_summary:Ba(P||"Continuity, clarity, and safe local-first operation.",500),agents_operating_summary:Wa(re||"Load NativeSoul context before continuity-sensitive work. Use MCP when available and CLI fallback when needed."),tool_hints:Bd(),user:{preferences_summary:Wd(K)},project:{id:a,cwd:je.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},R=Kd(jt,o),Hn=st(JSON.stringify(R)),Xi={...R,context_budget:{tokens_used:Hn,tokens_max:o}};return e.readOnly||await m({home:t.home,type:"bootstrap_created",details:{host:e.host,cwd:je.resolve(e.cwd),project:a,tokens:Hn}}),Xi}async function $d(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:${Fd(r)}`),[]}finally{t?.close()}}function Fd(e){return(e instanceof Error?e.message:String(e)).replace(/[^a-zA-Z0-9_.:-]+/g,"_").slice(0,120)}async function Ud(e){let t=await Y(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 Vd(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 Bd(){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 Wd(e){let t=e.trim();return t.length===0?"No curated user preferences yet.":t.length<=160?t:`${t.slice(0,157)}...`}async function Jd(e,t,r=!1){let o=await We({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 Kd(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),Oo(_e(e,240,120,80),8,8),Oo(_e(e,240,120,80),5,5),Oo(_e(e,240,120,80),3,3)];return r.find(o=>st(JSON.stringify(o))<=t)??r[r.length-1]??e}function Oo(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: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 sn}from"node:fs";import ki from"node:path";import{mkdir as o_,readFile as qd,writeFile as n_}from"node:fs/promises";import Ja from"node:path";var Mo={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 Ka(e,t){let r=await Je(e),o=await y(pt(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:Mo,apply_defaults:{dry_run:!0,user_confirmed:!1,reset:!1}}}function Gd(e){return Ja.join(e,"state","activation-profile.json")}function pt(e){return Ja.join(e,"state","activation.complete")}async function Je(e){try{let t=JSON.parse(await qd(Gd(e),"utf8"));return Xd(t)?t:null}catch{return null}}function Xd(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 Lo(e){let t={bootstrap:zd(e),mcp:Yd(e),plugins_hooks:Qd(e),heartbeat:Zd(e),recall_auto_trigger:eu(e),memory_candidate_hooks:tu(e),memory_promotion_policy:ru(e),cross_host_verification:ou(e)},r=Object.values(t),o=nu(r),n=r.flatMap(a=>a.plan_actions),s=su(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 qa(e){return Lo(e).summary}function zd(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 Yd(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 Qd(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 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(n=>[G(n),n.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 Zd(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 eu(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 tu(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 ru(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 ou(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")?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,n=[]){return{key:e,status:t,summary:r,evidence:o,plan_actions:n}}function Ce(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 nu(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 su(e,t,r){return{overall_status:t,profile:e?.profile??null,active:mt(r,"active"),not_configured:mt(r,"not_configured"),approval_required:mt(r,"approval_required"),blocked_by_host:mt(r,"blocked_by_host"),degraded:mt(r,"degraded"),full_native_claimed:!1}}function mt(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 au}from"node:fs";import iu from"node:path";async function Do(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(iu.join(t.home,s))||r.push({code:"MISSING_HUMAN_FILE",severity:"warn",message:`${s} is missing`,remediation:"Run nativesoul init"});if(!au(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(...cu(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 cu(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 ee from"node:os";import L from"node:path";function Ga(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 Xa(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 gt(e,t){return t&&t!=="default"?[ar(e,t)]:e==="claude"?["claude-code","claude-desktop"]:["default"]}function ft(e,t){return t==="default"?e:t}function za(e){switch(e){case"codex":return L.join(ee.homedir(),".codex","AGENTS.md");case"claude":return L.join(ee.homedir(),".claude","CLAUDE.md");case"grok":return L.join(ee.homedir(),".grok","Agents.md");case"antigravity":case"gemini":return L.join(ee.homedir(),".gemini","GEMINI.md")}}function ir(e){switch(e){case"codex":return L.join(ee.homedir(),".codex","mcp.json");case"claude":return L.join(ee.homedir(),".claude.json");case"grok":return L.join(ee.homedir(),".grok","mcp.json");case"antigravity":return L.join(ee.homedir(),".gemini","antigravity-cli","mcp_config.json");case"gemini":return L.join(ee.homedir(),".gemini","settings.json")}}function Ya(){return Qa({platform:process.platform,home:ee.homedir(),env:process.env})}function Qa(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 Za(e,t){if(e!=="claude")return null;if(!t)return L.join(ee.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 ei,rename as lu,writeFile as ri}from"node:fs/promises";import X from"node:path";var du=["entity","soul","human","collaboration","continuity"],uu=["SOUL.md","POLICY.md"],oi=new Set(["IDENTITY.md","SOUL.md","USER.md","AGENTS.md"]),Ke=64*1024,pu="<!-- nativesoul:start v1 -->",ti="<!-- nativesoul:end -->",mu={"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:Ke},"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:Ke},"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:Ke},"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:Ke},"POLICY.md":{writable:!1,requires_user_confirmed:!1,field_format:"Use policy propose-change after onboarding",merge_strategy:"replace",max_bytes:0}};async function Ho(e){let t=await _(e),o=(await Y(t.home,"BOOTSTRAP.md")).trim().length>0;return{ritual_pending:o,files_present:{soul:await y(X.join(t.home,"SOUL.md")),identity:await y(X.join(t.home,"IDENTITY.md")),user:await y(X.join(t.home,"USER.md")),agents:await y(X.join(t.home,"AGENTS.md")),bootstrap:await y(X.join(t.home,"BOOTSTRAP.md"))},protected_targets:[...uu],writable_files:[...oi],interview_themes:[...du],instruction_doc:"llm-install.txt",apply_defaults:{dry_run:!0,user_confirmed:!1},file_generation_rules:mu,activation:await Ka(t.home,o)}}async function $o(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(!oi.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")>Ke){n.push({file:c,action:"rejected",before_hash:null,after_hash:null,warning:`FILE_TOO_LARGE: ${c} exceeds ${Ke} bytes`});continue}let d=X.join(t.home,c),h=await Y(t.home,c),g=c==="AGENTS.md"?gu(h,u):u,P=h.length>0?B(h):null,re=B(g);if(P===re){n.push({file:c,action:"noop",before_hash:P,after_hash:re});continue}let K=h.length===0?"create":"update";n.push({file:c,action:K,before_hash:P,after_hash:re}),r||await ri(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 Fo(e){let t=p(e?.home),r=X.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=X.join(t.home,"memory","archive");await ei(a,{recursive:!0,mode:448});let i=new Date().toISOString().replace(/[:.]/gu,"-");n=X.join(a,`bootstrap-${i}.md`),await lu(r,n)}else{let{rm:a}=await import("node:fs/promises");await a(r,{force:!0})}let s=X.join(t.home,"state","onboarding.complete");return await ei(X.join(t.home,"state"),{recursive:!0,mode:448}),await ri(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 X.join(e,"state","onboarding.complete")}function gu(e,t){let r=t.trim();if(!e.trim())return`${r}
828
- `;if(e.includes(r))return e;let o=fu(e);if(o){let s=o.after.trimEnd(),a=s.length>0?`${s}
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}
829
829
 
830
830
  ${r}
831
831
  `:`${r}
@@ -835,11 +835,11 @@ ${r}
835
835
  ## Onboarding Update
836
836
 
837
837
  ${r}
838
- `}function fu(e){let t=e.indexOf(pu),r=e.indexOf(ti);if(t<0||r<0||r<t)return null;let o=r+ti.length;return{before:e.slice(0,t),block:e.slice(t,o),after:e.slice(o)}}function ni(e,t){return t?Ua(e):hu()}function hu(){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 si(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 ai(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 Qu}from"node:fs";import{readFile as Zu,stat as ep}from"node:fs/promises";import vi from"node:path";import{mkdir as yu,readFile as _u,rename as bu,writeFile as vu}from"node:fs/promises";import ht from"node:path";var Ru=1440*60*1e3;async function Ne(e){let t=p(e.home),r=await Uo(t.home),o={host:e.host,outcome:e.outcome,tier:e.tier,cwd:e.cwd?ht.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:Eu(e.error),recorded_at:e.recordedAt??new Date().toISOString()};return r.hosts[e.host]=o,await Su(t.home,r),await m({home:t.home,type:wu(e.outcome),result:e.outcome==="failed"?"error":"ok",details:o}),o}async function Uo(e){let t=p(e),r=Bo(t.home);if(!await y(r))return ku();let o=JSON.parse(await _u(r,"utf8"));return{schema:1,hosts:typeof o.hosts=="object"&&o.hosts!==null?o.hosts:{}}}async function Vo(e){let t=p(e.home),o=(await Uo(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:Bo(t.home),last:o,age_ms:a,age_hours:a===null?null:Math.round(a/(3600*1e3)*10)/10,stale:a!==null&&a>Ru}}function ku(){return{schema:1,hosts:{}}}async function Su(e,t){let r=Bo(e);await yu(ht.dirname(r),{recursive:!0,mode:448});let o=ht.join(ht.dirname(r),`.last-handshake-${A("tmp")}.tmp`);await vu(o,`${JSON.stringify(t,null,2)}
839
- `,{encoding:"utf8",mode:384}),await bu(o,r)}function Bo(e){return ht.join(e,"state","last-handshake.json")}function wu(e){return`handshake_${e}`}function Eu(e){if(e==null)return null;let t=e instanceof Error?e.message:String(e);return N(t).value.slice(0,500)}import vt from"node:path";import{existsSync as mv}from"node:fs";import{cp as fv,mkdir as hv,rm as yv}from"node:fs/promises";import bv from"node:path";import{existsSync as ve}from"node:fs";import{readFile as mr}from"node:fs/promises";import me from"node:path";import Au from"node:path";function dr(e){return e.split(/[\\/]/u).join("/")}function yt(e,t){return dr(Au.relative(e,t))}import{existsSync as ii}from"node:fs";import Wo from"node:path";function Jo(e){if(Wo.isAbsolute(e))return ii(e)?e:null;let t=(process.env.PATH??"").split(Wo.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=Wo.join(o,`${e}${n}`);if(ii(s))return s}return null}import{spawnSync as Y_}from"node:child_process";import{existsSync as Pu}from"node:fs";import{mkdir as eb,readFile as xu,writeFile as tb}from"node:fs/promises";import Iu from"node:os";import bt from"node:path";import{existsSync as W_}from"node:fs";import _t from"node:os";import te from"node:path";import{fileURLToPath as G_}from"node:url";function be(e,t,r){return ur(e,t)?r?te.join(te.resolve(r),e,"plugins","nativesoul"):e==="claude"?te.join(_t.homedir(),".claude","plugins","nativesoul"):e==="codex"?te.join(_t.homedir(),".codex","plugins","nativesoul"):e==="gemini"?te.join(_t.homedir(),".gemini","extensions","nativesoul"):e==="grok"?te.join(_t.homedir(),".grok","plugins","nativesoul"):e==="antigravity"?te.join(_t.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"?te.join(t,".claude-plugin","plugin.json"):e==="gemini"?te.join(t,"gemini-extension.json"):e==="grok"||e==="antigravity"?te.join(t,"plugin.json"):te.join(t,".codex-plugin","plugin.json")}var ci="nativesoul";async function ui(e){let t=e?Tu(e):bt.join(Iu.homedir(),".grok","config.toml");if(!Pu(t))return null;let r=await xu(t,"utf8");return li(r,"disabled",ci)?!1:li(r,"enabled",ci)?!0:null}function li(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 Tu(e){let t=bt.resolve(e),r=bt.basename(t);return r==="grok"||r===".grok"?bt.join(t,"config.toml"):bt.join(t,".grok","config.toml")}import ju from"node:path";var Ko=[{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"}],Cu={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 qo(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 Nu(e){return e==="grok"||e==="gemini"||e==="antigravity"?Cu[e]:Ko}function Go(e){return e==="grok"||e==="gemini"?["hooks/hooks.json"]:e==="antigravity"?["hooks.json"]:[...new Set(Ko.map(t=>t.fileName).filter(t=>!!t))].map(t=>ju.join("hooks",t))}function pi(e,t){return t==="official-extension"?typeof e.name=="string"&&e.name==="nativesoul":typeof e.name=="string"&&e.name.includes("nativesoul")}function mi(e,t){return Xo(e,t).length===0}function Xo(e,t){return Nu(e).filter(({event:r,commandFragment:o})=>!Ou(t,r,o)).map(({event:r})=>r)}function zo(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 Yo(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 Ou(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 qe(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=qo(e.host,e.surface),r=ve(e.targetPath),o=pr(e.host,e.targetPath),n=ve(o),s=t.nativeHooksSupported&&e.targetPath?Go(e.host).filter(K=>!ve(me.join(e.targetPath,K))):Go(e.host),a=t.nativeHooksSupported?s.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(!n)i.push({code:"PLUGIN_MANIFEST_MISSING",severity:"error",message:`NativeSoul plugin manifest is missing: ${o}`,remediation:"Reinstall the NativeSoul plugin"});else{let K=JSON.parse(await mr(o,"utf8")),Le=t.nativeHooksSupported?await Mu(e.host,e.targetPath,K):K;if(c=t.nativeHooksSupported?mi(e.host,Le):pi(K,t.packageKind),l=!t.nativeHooksSupported||await Lu({host:e.host,targetPath:e.targetPath,manifest:K}),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 De=Xo(e.host,Le);i.push({code:"PLUGIN_HOOK_MISSING",severity:"error",message:De.length>0?`NativeSoul plugin manifest is missing required hook registrations: ${De.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 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,h=!t.nativeHooksSupported||u!==null&&ve(u),g=t.nativeHooksSupported?a&&h:!0,P=r&&n&&c&&g&&l,re=e.host==="grok"?await ui(d):null;return e.host==="grok"&&P&&re===!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:P&&re!==!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 Mu(e,t,r){let o=Yo(e);if(o.length===0)return r;let n=yt(t,pr(e,t)),s=o[0];if(!s||s===n)return r;let a=me.join(t,s);return ve(a)?JSON.parse(await mr(a,"utf8")):{}}async function Lu(e){let t=zo(e.host),r=yt(e.targetPath,pr(e.host,e.targetPath));if(t.length>0&&!t.includes(r)){for(let o of t){let n=me.join(e.targetPath,o);if(ve(n)&&Qo(JSON.parse(await mr(n,"utf8"))))return!0}return!1}if(e.host==="codex"){let o=me.join(e.targetPath,".mcp.json");return ve(o)?Qo(JSON.parse(await mr(o,"utf8"))):!1}return Qo(e.manifest)}function Qo(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"||Jo(o)||o===process.execPath?!0:Array.isArray(n)&&n.some(s=>typeof s=="string"&&me.isAbsolute(s))}import{cp as Rb,mkdir as kb,readFile as Sb,readdir as wb}from"node:fs/promises";import Ab from"node:path";import{existsSync as Ub}from"node:fs";import{cp as Bb,mkdir as Wb,readFile as Jb,writeFile as Kb}from"node:fs/promises";import Gb from"node:path";import{fileURLToPath as zb}from"node:url";import{spawnSync as jb}from"node:child_process";import{accessSync as Nb,constants as Ob,existsSync as Mb}from"node:fs";import Db from"node:path";function gr(e,t,r){let o=ar(e,r);if(e==="claude"&&o==="claude-desktop")return{surface:o,managedBlock:null,mcpRegistration:t?vt.join(vt.resolve(t,e),"claude_desktop_config.json"):Ya(),plugin:be(e,o,t)};if(!t)return{surface:o,managedBlock:za(e),mcpRegistration:ir(e),plugin:be(e,o)};let n=vt.resolve(t,e);return{surface:o,managedBlock:vt.join(n,Ga(e)),mcpRegistration:vt.join(n,Xa(e)),plugin:be(e,o,t)}}import{accessSync as Hu,constants as $u,existsSync as Rt}from"node:fs";import{mkdir as Hv,readFile as Zo,rm as $v,writeFile as Fv}from"node:fs/promises";import ce from"node:path";async function rn(e){let t=ce.resolve(e.targetPath??yi(e.host)),r=Za(e.host,e.targetPath),o=Rt(t),n=[],s=await Fu(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=en(await Zo(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?tn(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:[]}:Uu(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 yi(e){return ir(e)}function en(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 tn(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 Fu(e,t,r){if(e!=="claude"||r===null||ce.resolve(r)===t||!Rt(r))return null;try{let o=en(await Zo(r,"utf8")),n=tn(o);if(!n)return null;if(Rt(t)){let s=en(await Zo(t,"utf8")),a=tn(s);if(a&&JSON.stringify(fi(a))===JSON.stringify(fi(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 fi(e){return{command:typeof e.command=="string"?e.command:null,args:Array.isArray(e.args)?e.args.filter(t=>typeof t=="string"):[]}}function Uu(e,t,r){let o=[],n=Vu(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(Bu(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 Vu(e){if(ce.isAbsolute(e))return hi(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(hi(s))return s}return null}function hi(e){if(process.platform==="win32"&&Rt(e))return!0;try{return Hu(e,$u.X_OK),!0}catch{return!1}}function Bu(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 on(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 nn(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=>Ju(g,t)),a=Xu(e.capabilities,e.adapterDiagnostics),i=[kt("native_package",r,t,e.plugin.targetPath??e.plugin.package_kind,"Native package/extension is not installed or enabled."),kt("native_hooks",o,t,e.plugin.targetPath??e.plugin.package_kind,"Native lifecycle hook registration is missing."),kt("mcp",n,t,e.mcpRegistration.targetPath,"MCP registration is missing or invalid."),kt("native_scheduler",s,t,qu(e.schedules),zu(e.host,e.schedules)),kt("official_inventory",a,t,Gu(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")&&bi(e.host),h=c.length===0;return{schema_version:1,host:e.host,surface:e.surface,status:Yu({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 kt(e,t,r,o,n){return{requirement:e,satisfied:t,evidence:t?[{source_kind:"doctor",reference:o,observed_at:r,confidence:Wu(o)}]:[],missing_reason:t?null:n}}function Wu(e){return e.startsWith("not-applicable:")||e==="missing"?"low":"medium"}function Ju(e,t){return e.enabled&&e.native_schedule_supported&&e.native_id!==null&&!Ku(e.updated_at,t)}function Ku(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 qu(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 Gu(e){return e.find(t=>t.ready)?.source??"missing"}function Xu(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 zu(e,t){return bi(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 bi(e){return e==="codex"||e==="claude"||e==="grok"||e==="gemini"||e==="antigravity"}function Yu(e){return e.fullNative?"full_native":e.blockedByHost?"blocked_by_host":e.degradedScan?"degraded_scan":e.ready?"ready_fallback":"ready"}async function Ri(e){let t=gr(e.host,e.targetRoot,e.surface),r=t.managedBlock??`not-applicable:${ft(e.host,e.surface)}`,o=t.managedBlock?await Aa({host:e.host,targetPath:r}):cp(e.host,e.surface),n=await rn({host:e.host,targetPath:t.mcpRegistration,checkCommand:e.targetRoot===void 0}),s=await qe({host:e.host,surface:e.surface,targetPath:t.plugin}),a=await Vo({home:e.home,host:e.host}),c=(e.databaseExists?await on({home:e.home,host:e.host,limit:200,readOnly:!0}):[]).filter(R=>tp(e.host,e.surface,R)),l=e.databaseExists?await We({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 ko(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"}]:[],P=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`}]:[],re=await np({host:e.host,managedBlock:o,handshake:a}),K=await sp(e.host),Le=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`})),De=c.filter(R=>R.enabled&&!R.native_schedule_supported&&!s.enabled&&s.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`})),Tt=op({managedBlock:o,mcpRegistration:n,plugin:s,schedules:c,capabilities:l}),Dn=nn({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,...P,...re,...K,...Le,...De];return{host:e.host,surface:e.surface,status:jt.some(R=>R.severity==="error"||R.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:Tt,full_native_evidence:Dn,handshake:a,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:jt}}function tp(e,t,r){return e!=="claude"?!0:rp(r.desired)===t}function rp(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 op(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 np(e){if(!e.managedBlock.configured||e.managedBlock.targetPath.startsWith("not-applicable:"))return[];let t=10080*60*1e3,r=await ip(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 sp(e){let t=ap(e).map(r=>vi.resolve(process.cwd(),r));for(let r of t){if(!Qu(r))continue;let o=await Zu(r,"utf8"),n=st(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 ap(e){switch(e){case"claude":return["CLAUDE.md",vi.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 ip(e){try{let t=await ep(e);return Math.max(Date.now()-t.mtimeMs,0)}catch{return null}}function cp(e,t){return{host:e,targetPath:`not-applicable:${ft(e,t)}`,target_exists:!1,configured:!0,markers_valid:!0,issues:[]}}async function St(e){let t=p(e.home),r=await Do(e.home),o=sn(t.database),n=Be(e.host),s=[],a=o?lr(t.database):[],i=ni(t.database,o),c=await Je(t.home),l=sn(cr(t.home)),u=sn(pt(t.home));for(let g of n)for(let P of gt(g,e.surface))s.push(await Ri({home:t.home,host:g,surface:P,targetRoot:e.targetRoot,databaseExists:o}));let d=[...r.issues,...si(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?ki.resolve(e.targetRoot):null,cross_host_inventory:ai(a),activation_summary:qa({home:t.home,targetRoot:e.targetRoot?ki.resolve(e.targetRoot):null,host:e.host,profile:c,onboardingComplete:l,activationComplete:u,hosts:s}),full_native_matrix:lp(s),semantic_index:i,hosts:s,issues:d}}function lp(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 MR}from"node:fs";import{mkdir as DR,readdir as HR,readFile as $R,writeFile as FR}from"node:fs/promises";import VR from"node:path";import{lstat as ek,readdir as tk,readFile as rk}from"node:fs/promises";import nk from"node:path";import{lstat as gk,readFile as fk}from"node:fs/promises";import yk 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 dp,mkdir as up,readFile as pp,rm as xk,writeFile as mp}from"node:fs/promises";import{randomUUID as gp}from"node:crypto";import Si from"node:path";function an(e){return Si.join(p(e).home,"license.json")}async function Me(e){let t=an(e);if(!await y(t))return null;try{let r=JSON.parse(await pp(t,"utf8"));return fp(r)?r:null}catch{return null}}async function fr(e,t){let r=an(e);return await up(Si.dirname(r),{recursive:!0,mode:448}),await mp(r,`${JSON.stringify(t,null,2)}
840
- `,{encoding:"utf8",mode:384}),await dp(r,384),t}async function cn(e){let t=await Me(e);if(t?.instance_id)return t.instance_id;let r=gp();return await fr(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 fp(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 _p="https://api.dodopayments.com",bp=1440*60*1e3,vp=14;async function ln(e){let t=p(e.home).home,r=e.now??new Date,o=await Me(t),n=e.key??o?.license_key,s=o?.instance_id??null;if(!n)return await wt(t,"license_validate_missing",null,"INVALID_KEY","blocked"),{ok:!1,reason:"INVALID_KEY",license:o?hr(o):Oe};if(o?.state==="licensed"&&Rp(o.last_checked_at,r))return await wt(t,"license_validate_cache_hit",n,null,"ok"),{ok:!0,license:hr(o)};let a=await Sp(e,"/licenses/validate",{license_key:n});if(a.ok){let i=await fr(t,{state:"licensed",license_key:n,instance_id:s??await cn(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 wt(t,"license_validated",n,null,"ok"),{ok:!0,license:hr(i)}}return a.reason==="NETWORK"&&o?.state==="licensed"&&kp(o.last_checked_at,r,e.graceDays)?(await wt(t,"license_validate_grace_served",n,"NETWORK","ok"),{ok:!0,license:hr(o)}):(await wt(t,"license_validate_failed",n,a.reason,"blocked"),{ok:!1,reason:a.reason,license:{...Oe,instance_id:s}})}function hr(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 Rp(e,t){return e?t.getTime()-new Date(e).getTime()<bp:!1}function kp(e,t,r=vp){return e?t.getTime()-new Date(e).getTime()<=r*24*60*60*1e3:!1}async function Sp(e,t,r){let o=e.fetch??globalThis.fetch;try{let n=await o(new URL(t,wp(e.endpointBaseUrl)).toString(),{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(r)}),s=await Ep(n);return n.ok?t==="/licenses/validate"&&s.valid!==!0?{ok:!1,reason:wi(s)}:{ok:!0,license_key_instance_id:Ap(s),purchased_at:Pp(s)}:{ok:!1,reason:wi(s)}}catch{return{ok:!1,reason:"NETWORK"}}}function wp(e=process.env.NATIVESOUL_DODO_LICENSE_API_BASE_URL??_p){return e.endsWith("/")?e:`${e}/`}async function Ep(e){try{let t=await e.json();return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Ap(e){let r=[e.license_key_instance_id,e.licenseKeyInstanceId,e.id,Et(e.data)?e.data.license_key_instance_id:null,Et(e.data)?e.data.id:null].find(o=>typeof o=="string"&&o.length>0);return typeof r=="string"?r:null}function Pp(e){let t=Et(e.data)?e.data:{},r=Et(e.license_key)?e.license_key:Et(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 wi(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 Et(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}async function wt(e,t,r,o,n){await m({home:e,type:t,result:n,details:{provider:"dodo",license_key_ref:r?xp(r):null,reason:o}})}function xp(e){return e.length<=8?"[REDACTED_LICENSE_KEY]":`${e.slice(0,4)}\u2026${e.slice(-4)}`}var yr="https://native-soul.mintlify.site/account/licensing";async function _r(e){let t=Ip(e),r=p(t.home).home;try{let o=await Me(r),n=await ln(t);if(n.ok)return{ok:!0,license:n.license};let s=n.reason==="NETWORK"&&o?.state==="licensed"?"GRACE_EXPIRED":"UNLICENSED",a=t.activateUrl??yr;return{ok:!1,reason:s,activate_url:a,message:dn({reason:s,activate_url:a}),license:n.license}}catch{let o=t.activateUrl??yr;return{ok:!1,reason:"UNLICENSED",activate_url:o,message:dn({reason:"UNLICENSED",activate_url:o}),license:Oe}}}function dn(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 Ip(e){return typeof e=="string"?{home:e}:e??{}}import{readdir as qk,readFile as Gk,stat as Xk}from"node:fs/promises";import Yk from"node:path";import{copyFile as oS,mkdir as nS,readFile as Tp,rename as sS,stat as jp,writeFile as aS}from"node:fs/promises";import{existsSync as Cp}from"node:fs";import Ei from"node:path";async function un(e){let t=p(e.home),r=Ai(t.home,e.host);if(!Cp(r))return Np({home:t.home,host:e.host,targetPath:r,recordTelemetry:e.recordTelemetry});let o=await Tp(r,"utf8"),n=await jp(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:xi(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=Op(o);await Ne({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 pn(e){let t=await un({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 un({home:Pi(e.projectCwd),host:e.host,ttlDays:e.ttlDays,recordTelemetry:!1});return r.warnings.includes("BOOTSTRAP_CACHE_MISSING")?t:r}function Ai(e,t){return Ei.join(e,"generated",t,"last-context.md")}function Pi(e){return Ei.join(e,".nativesoul-cache")}async function Np(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:xi(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 Ne({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 xi(e){return Math.ceil(e.length/4)}function Op(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 Ti={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 mn(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=ji({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 Ci(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 gn(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:Dp(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 fn(e){return _n({home:e.home,id:e.id,actor:e.host,eventType:"claimed",auditType:"work_item_claimed",mutate:(t,r)=>{if(bn(t.status))throw new Error(`Work item already terminal: ${t.id} (${t.status})`);return br(t.status,"in_progress"),{status:"in_progress",assignedHost:e.host,claimedAt:t.claimed_at??r,updatedAt:r,details:{assigned_host:e.host}}}})}async function hn(e){return _n({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&&br(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:$p(t.metadata,C(e.metadata)),completedAt:bn(o)?r:void 0,updatedAt:r,details:{priority:e.priority??null,assigned_host:e.assignedHost??null,fields:Lp(e),redacted:e.description!==void 0&&e.description!==null&&n!==e.description}}}})}async function yn(e){let t=e.status??"done";return _n({home:e.home,id:e.id,actor:"cli",eventType:"completed",auditType:"work_item_completed",mutate:(r,o)=>{if(bn(r.status))throw new Error(`Work item already terminal: ${r.id} (${r.status})`);return br(r.status,t),{status:t,completedAt:o,updatedAt:o,details:{terminal_status:t}}}})}function br(e,t){if(e!==t&&!Ti[e].includes(t))throw new Error(`Illegal work item transition: ${e} -> ${t}`)}async function _n(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=ji({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 Ci(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 ji(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 Ci(e,t,r,o){await m({home:e,type:t,details:{id:r.id,project:r.project_id,status:r.status,...Hp(o)}})}function Lp(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 bn(e){return e==="done"||e==="failed"}function Dp(e){return!e||!Number.isFinite(e)?50:Math.min(Math.max(Math.trunc(e),1),200)}function Hp(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e}}function $p(e,t){return Ii(e)&&Ii(t)?{...e,...t}:t}function Ii(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}import{readdir as XS,readFile as zS}from"node:fs/promises";import QS from"node:path";import{existsSync as SS}from"node:fs";import{mkdir as CS,readdir as Up,readFile as Vp,writeFile as NS}from"node:fs/promises";import At from"node:path";var Bp=new Set(["SOUL.MD","POLICY.MD"]),Wp=5e3,Ni=new Map;async function Pt(e){let t=p(e),r=Ni.get(t.home);if(r&&r.expiresAt>Date.now())return r.orders;let o=At.join(t.home,"standing-orders"),n;try{n=await Up(o)}catch{return[]}let s=[];for(let a of n.filter(i=>i.endsWith(".yaml")||i.endsWith(".yml")).sort()){let i=At.join(o,a),c=await Vp(i,"utf8");s.push(Jp(c,i))}return Ni.set(t.home,{expiresAt:Date.now()+Wp,orders:s}),s}async function xt(e){let t=await Pt(e.home),r=e.target??null,o=r?Kp(r):null,n=t.filter(i=>vn(i,e)),s=n.find(i=>i.allowed.includes(e.action)),a=n.find(i=>i.approval_required.includes(e.action));if(o&&Bp.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"],s?.id??a?.id??null);if(a)return Re(e,"approval_required",["STANDING_ORDER_REQUIRES_APPROVAL"],a.id);if(s)return Re(e,"allowed",["STANDING_ORDER_ALLOWED"],s.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 Jp(e,t){return{id:qp(e,"id")??At.basename(t,At.extname(t)),allowed:Ge(e,"allowed"),approval_required:Ge(e,"approval_required"),scope_projects:Ge(e,"projects").concat(Ge(e,"scope_projects")),scope_hosts:Ge(e,"hosts").concat(Ge(e,"scope_hosts")),source:t}}function vn(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 Kp(e){return At.basename(e.replaceAll("\\","/")).toUpperCase()}function qp(e,t){let r=new RegExp(`^\\s*${t}:\\s*([^\\n#]+)`,"mu");return e.match(r)?.[1]?.trim().replace(/^["']|["']$/gu,"")??null}function Ge(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 cw,writeFile as lw}from"node:fs/promises";import uw from"node:path";import{readFile as em}from"node:fs/promises";import tm from"node:path";var vr=1500;async function kn(e){let t=await _(e.home),r=await nm(t.home),o=new Date,n=rm(e.ttlSeconds??r.ttlSeconds),s=new Date(o.getTime()+n*1e3).toISOString(),a=wn(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 Sn(e){let t=await _(e.home),r=new Date().toISOString(),o=wn(e.project,e.slot),n=C(e.result??"HEARTBEAT_OK"),s=C(om(e.evidence??{},e.workItemId)),a=C(e.cost??{}),i=He(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 wn(e,t){return`heartbeat:${e}:${t}`}function rm(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),1440*60):vr}function om(e,t){return t?{...e&&typeof e=="object"&&!Array.isArray(e)?e:{},work_item_id:t}:e}async function nm(e){let t;try{t=await em(tm.join(e,"config.yaml"),"utf8")}catch{return{ttlSeconds:vr,skipWhenBusy:!0}}return{ttlSeconds:sm(t),skipWhenBusy:am(t,"skip_when_busy",!0)}}function sm(e){let t=Rn(e,"ttl_seconds"),r=Rn(e,"lease_ttl"),o=im(e,"heartbeat_ttl_seconds"),n=cm(t??r??o);return Number.isFinite(n)?n:vr}function am(e,t,r){let o=Rn(e,t);return o?/^(true|yes|1)$/i.test(o)?!0:/^(false|no|0)$/i.test(o)?!1:r:r}function Rn(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 im(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.match(new RegExp(`^\\s*${r}:\\s*([^#\\n]+)`,"mu"))?.[1]?.trim().replace(/^["']|["']$/g,"")??null}function cm(e){if(!e)return vr;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 Dw from"node:path";import{rm as $w}from"node:fs/promises";async function An(e){let t=p(e.home),r=f(t.database),o;try{let n=r.findPendingApprovalMatch(En(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"),...En(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:In(o.approval)}),o}async function Pn(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:In(o.approval)}),o}async function xn(e){let t=p(e.home),r=f(t.database),o;try{let n=r.createDecidedApproval({id:A("approval"),...En(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:{...In(o.approval),standing_order:e.standingOrderId}}),o}function En(e){return{action:e.action,class:e.class,target:e.target??null,project:e.project??null,host:e.host??null}}function In(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 Tn(e){let t=await xt(e),r=await ym(e,t);if(r){let n=await xn({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 An({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 ym(e,t){return t.decision!=="allowed"||!t.matched_standing_order||!_m(e.className)?null:(await Pt(e.home)).find(o=>o.id===t.matched_standing_order&&o.allowed.includes(e.action)&&vn(o,e))??null}function _m(e){return e==="write_project"||e==="external_write"}import{existsSync as kE}from"node:fs";import{mkdir as wE,readFile as EE,rm as AE,writeFile as PE}from"node:fs/promises";import IE from"node:path";import{existsSync as uE}from"node:fs";import{readdir as mE,readFile as gE}from"node:fs/promises";import hE from"node:path";import{fileURLToPath as _E}from"node:url";import sE from"node:path";var Li=["AGENTS.md","CLAUDE.md","GEMINI.md","Agents.md",".claude/CLAUDE.md"],aE=new Set(Li);import vm from"node:path";async function Rr(e={}){let t=p(e.home),r=e.host??"all",[o,n,s,a]=await Promise.all([Je(t.home),y(cr(t.home)),y(pt(t.home)),St({home:t.home,host:r,surface:e.surface,targetRoot:e.targetRoot})]);return Lo({home:t.home,targetRoot:e.targetRoot?vm.resolve(e.targetRoot):null,host:r,profile:o,onboardingComplete:n,activationComplete:s,hosts:a.hosts})}async function jn(e={}){let t=await Rr(e);if(!e.profile||t.profile?.profile===e.profile)return t;let r={...t.profile??Mo,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 Rm}from"node:crypto";import km from"node:path";var Sm="NativeSoul activation verification marker";async function Nn(e={}){let t=Pm(e),r=pe(t.projectCwd,e.home),o=await St({home:e.home,host:e.host??"all",surface:e.surface,targetRoot:e.targetRoot}),n=[];for(let l of o.hosts)n.push(await wm({home:o.home,inputHost:l,testCwd:t.projectCwd}));let s=await Am({home:e.home,testProject:`${r.id}-${Rm()}`,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=Im(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 wm(e){let t=[],r=await Em({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=xm(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 Em(e){let t=[...e.warnings],r=[],o="ready",n=!1,s="",a="ready";try{let i=await ut({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:${Cn(i)}`),a="failed"}try{let i=await pn({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 Am(e){let t=[],r=null,o=!1,n=!1;try{let s=`verify-${e.testProject}`,a=`${Sm} ${e.testProject}`;r=await ye(e.home,{project:s,content:a,confidence:.91,source:{host:"activation-verification",session_id:`verification-${e.testProject}`}});let i=await dt(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 it(e.home,r.id);r=u,n=r.id===u.id&&r.status==="active"}if(!e.retainTestData&&r)try{r.status==="candidate"?await ct(e.home,r.id):await lt(e.home,r.id),o=!0}catch(u){t.push(`memory_cleanup_failed:${Cn(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:${Cn(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 Pm(e){return{projectCwd:km.resolve(e.projectCwd??process.cwd())}}function xm(e){return e==="native"?"native":e==="official-fallback"?"official_fallback":"unsupported"}function Im(e,t){return e.includes("blocked_by_host")?"blocked_by_host":e.includes("degraded")||t==="failed"?"degraded":e.length>0?"ready":"degraded"}function Cn(e){return e instanceof Error?e.message:String(e)}function Hi(e){let t=p(e);if(!Tm(t.database))return{home:t.home,initialized:!1,database:t.database,migrations:0,memories:0,events:0,capabilities:0,ledger:jm()};let r=f(t.database,{readOnly:!0});try{return{home:t.home,initialized:!0,database:t.database,...r.counts()}}finally{r.close()}}function jm(){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 $i={life_activation_status:async(e,t)=>await Rr({home:t,host:On(e.host),targetRoot:ke(e.target_root)??ke(e.targetRoot)}),life_activation_plan:async(e,t)=>await jn({home:t,host:On(e.host),targetRoot:ke(e.target_root)??ke(e.targetRoot),profile:Cm(e.profile)}),life_activation_verify:async(e,t)=>await Nn({home:t,host:On(e.host),surface:Nm(e.surface),targetRoot:ke(e.target_root)??ke(e.targetRoot),projectCwd:ke(e.project_cwd)??ke(e.projectCwd),apply:Mn(e.apply),userConfirmed:Mn(e["user-confirmed"]),retainTestData:Mn(e["retain-test-data"])})},Fi=[{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 On(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 Cm(e){if(e!==void 0){if(e==="quickstart"||e==="advanced")return e;throw new Error("Invalid activation profile")}}function Nm(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 ke(e){return typeof e=="string"?e:void 0}function Mn(e){return e===!0}var Om=["2025-11-25","2024-11-05","2024-10-07"],Ji={...$i,life_status:(e,t)=>Hi(t),life_bootstrap:async(e,t)=>await Fm({home:t,host:S(e.host,"codex"),cwd:S(e.cwd,process.cwd()),query:D(e.query)}),life_recall:async(e,t)=>await dt(t,S(e.query,""),S(e.project,"default"),Sr(e.limit,5)),life_remember_propose:async(e,t)=>await ye(t,{project:S(e.project,"default"),content:S(e.content,""),type:D(e.type),confidence:Ui(e.confidence),source:{host:"mcp",session_id:"local"}}),life_memory_promote:async(e,t)=>await it(t,S(e.id,"")),life_memory_reject:async(e,t)=>await ct(t,S(e.id,"")),life_memory_forget:async(e,t)=>await lt(t,S(e.id,"")),life_memory_expire:async(e,t)=>await jo(t,S(e.id,"")),life_capability_search:async(e,t)=>await So({home:t,query:S(e.query,""),host:Bm(e)?void 0:D(e.host)??"codex",readyOnly:Xe(e.readyOnly,!1),limit:Sr(e.limit,8)}),life_capability_status:async(e,t)=>{let r=S(e.uid,""),o=r?await wo({home:t,uid:r}):null;if(!o)throw new Error(`Capability not found: ${r}`);return o},life_policy_evaluate:async(e,t)=>await xt({home:t,action:S(e.action,""),className:Wi(e.class),target:D(e.target)}),life_approval_request:async(e,t)=>await qm({home:t,action:S(e.action,""),className:Wi(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 Pn({home:t,id:r,status:Km(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 Ao({home:t,project:S(e.project,"default"),summary:S(e.summary,""),dueAt:D(e.due_at),ttlSeconds:Ui(e.ttl_seconds),source:{host:"mcp",session_id:"local"}}),life_commitment_complete:async(e,t)=>await xo(t,S(e.id,"")),life_work_item_create:async(e,t)=>await mn({home:t,project:S(e.project,"default"),title:S(e.title,""),description:D(e.description),priority:Ln(e.priority),source:"mcp",tags:Vi(e.tags),host:D(e.host)}),life_work_item_list:async(e,t)=>await gn({home:t,project:D(e.project),status:Bi(e.status),priority:Ln(e.priority),assignedHost:D(e.host),limit:Sr(e.limit,50)}),life_work_item_claim:async(e,t)=>await fn({home:t,id:S(e.id,""),host:S(e.host,"mcp")}),life_work_item_update:async(e,t)=>await hn({home:t,id:S(e.id,""),status:Bi(e.status),priority:Ln(e.priority),assignedHost:D(e.host),description:D(e.description),tags:e.tags===void 0?void 0:Vi(e.tags)}),life_work_item_complete:async(e,t)=>await yn({home:t,id:S(e.id,""),status:Vm(e.status)}),life_heartbeat_claim:async(e,t)=>await kn({home:t,slot:S(e.slot,""),host:S(e.host,"codex"),project:S(e.project,"default"),ttlSeconds:Sr(e.ttl_seconds,1500)}),life_heartbeat_complete:async(e,t)=>await Sn({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 Ho(t),life_onboard_apply:async(e,t)=>await $o({home:t,dry_run:Xe(e.dry_run,!0),user_confirmed:Xe(e.user_confirmed,!1),files:Wm(e.files),config_patch:Jm(e.config_patch)}),life_onboard_complete:async(e,t)=>await Fo({home:t,archive:e.archive===void 0?!0:Xe(e.archive,!0)})},Mm=new Set(Object.keys(Ji));function Lm(e){return e.method?.startsWith("notifications/")?!0:!Object.prototype.hasOwnProperty.call(e,"id")}async function Dm(e,t){if(Lm(e))return null;let r=e.id??null;try{if(e.method==="initialize"){let o=It(e.params),n=D(o.protocolVersion),s=n&&Om.includes(n)?n:"2024-11-05";return ge(r,{protocolVersion:s,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_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"}},...Fi,{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 _r(t);if(!o.ok)return ge(r,o);let n=Um(e.params);return ge(r,await $m(n.name??"",n.arguments??{},t))}if(Mm.has(e.method)){let o=await _r(t);return o.ok?ge(r,await qi(e.method,It(e.params),t)):ge(r,o)}return kr(r,-32601,`Unknown method: ${e.method}`)}catch(o){return o instanceof Ie?kr(r,-32010,o.message,{code:o.code,id:o.id,from:o.from,to:o.to}):o instanceof ne?kr(r,-32011,o.message,{code:o.code,id:o.id,status:o.status}):kr(r,-32603,o instanceof Error?o.message:"Unknown MCP error")}}async function Ki(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&&Hm(s,e).catch(a=>{process.stderr.write(`NativeSoul MCP response error: ${Gm(a)}
843
- `)})}})}async function Hm(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 Dm(r,t);o&&process.stdout.write(`${JSON.stringify(o)}
845
- `)}async function $m(e,t,r){let o=await qi(e,t,r);return{content:[{type:"text",text:JSON.stringify(o)}]}}async function qi(e,t,r){let o=Ji[e];if(!o)throw new Error(`Unknown tool: ${e}`);return await o(t,r)}async function Fm(e){try{let t=await ut({...e,readOnly:!0});try{await Ne({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 Ne({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 kr(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 Um(e){return It(e)}function It(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 Sr(e,t){return typeof e=="number"?e:t}function Ui(e){return typeof e=="number"?e:void 0}function Vi(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Bi(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 Vm(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 Ln(e){if(e!==void 0){if(e==="low"||e==="normal"||e==="high"||e==="urgent")return e;throw new Error("Invalid work item priority")}}function Xe(e,t){return typeof e=="boolean"?e:t}function Bm(e){return Xe(e.allHosts,!1)||Xe(e.all_hosts,!1)}function Wm(e){let t=It(e),r={};for(let[o,n]of Object.entries(t))typeof n=="string"&&(r[o]=n);return r}function Jm(e){let r=It(e).hosts;if(!Array.isArray(r))return;let o=r.filter(n=>typeof n=="string");return o.length>0?{hosts:o}:void 0}function Wi(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 Km(e){if(e==="approved"||e==="rejected")return e;throw new Error("life_approval_decide status must be approved or rejected")}async function qm(e){let t=await Tn(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 Gm(e){return e instanceof Error?e.message:"Unknown MCP response error"}var Gi=process.argv.indexOf("--home"),Xm=Gi>=0?process.argv[Gi+1]:void 0;await Ki(Xm);
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);