nativesoul 0.1.2 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +55 -0
- package/README.md +2 -2
- package/dist/package.json +1 -1
- package/dist/packages/cli/src/index.js +164 -162
- package/dist/packages/mcp-server/src/index.js +53 -52
- package/docs/adr/ADR-043-versioning-and-release-policy.md +1 -1
- package/docs/adr/ADR-046-central-policy-gate-and-path-safety.md +35 -0
- package/package.json +1 -1
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
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 (
|
|
2
|
+
var dl=Object.defineProperty;var Pe=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(o){throw r=[o],o}};var Kn=(e,t)=>{for(var r in t)dl(e,r,{get:t[r],enumerable:!0})};import{spawn as Jl}from"node:child_process";import{access as Kl}from"node:fs/promises";import{constants as ql}from"node:fs";import{existsSync as Gl}from"node:fs";import xs from"node:path";async function de(e){let t=(process.env.PATH??"").split(xs.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=xs.join(o,`${e}${n}`);if(process.platform==="win32"&&Gl(s))return s;try{return await Kl(s,ql.X_OK),s}catch{}}return null}async function Bt(e,t){return new Promise(r=>{Is(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(l=>l.trim()).find(l=>/\d+\.\d+/u.test(l)&&!l.toLowerCase().startsWith("warning"));if(a===0||i){r(i??null);return}r(null)})})})}async function lo(e,t,r=1e3){return new Promise(o=>{Is(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",l=>{a+=String(l)}),n.stderr.on("data",l=>{i+=String(l)}),n.on("error",()=>{clearTimeout(s),o({status:"missing",code:null,stdout:a,stderr:i})}),n.on("close",l=>{clearTimeout(s),o({status:l===0?"ok":"error",code:l,stdout:a,stderr:i})})})})}async function Is(e,t,r){let n=await de(e)??e,s=process.platform==="win32"&&/\.(?:cmd|bat)$/iu.test(n);return Jl(n,t,{stdio:r,shell:s})}var Ce=Pe(()=>{"use strict"});import{constants as Xl}from"node:fs";import{access as zl,readFile as Yl,stat as Ql}from"node:fs/promises";import Ts from"node:os";import Zl from"node:path";function v(e){return e==="~"?Ts.homedir():e.startsWith("~/")?Zl.join(Ts.homedir(),e.slice(2)):e}async function b(e){try{return await zl(e,Xl.F_OK),!0}catch{return!1}}async function T(e){try{return(await Ql(e)).isDirectory()}catch{return!1}}async function L(e){return await b(e)?Yl(e,"utf8"):null}function ae(e){let t=js(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 js(e){return{start:`<!-- nativesoul:${e}:start v1 -->`,end:`<!-- nativesoul:${e}:end -->`}}function F(e,t){if(!t)return!1;let r=js(t);return e.includes(r.start)&&e.includes(r.end)}var W=Pe(()=>{"use strict"});function w(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ue(e){try{return JSON.parse(e)}catch{return null}}async function H(e){let t=await L(e);if(t===null)return null;let r=ue(t);return w(r)?r:null}function _e(e){return w(e)?Object.keys(e).filter(t=>t.trim().length>0):[]}function Wt(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function be(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 V(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 pe=Pe(()=>{"use strict";W()});import{readdir as uc,readFile as pc}from"node:fs/promises";import Us from"node:path";function Bs(e){let t=e??v("~/.claude");return Us.join(t,"scheduled-tasks")}async function Ws(e){if(!await T(e))return null;let t=await Fs(e,Vs);if(t!==null)return t;let r=await gc(e);for(let o of r){let n=await Fs(e,o);if(n!==null)return n}return null}async function Fs(e,t){let r=Us.join(e,t,"SKILL.md");if(!await b(r))return null;let n=(await pc(r,"utf8")).toLowerCase();return t===Vs||t.includes(mc)||n.includes(`name: ${$s}`)||n.includes(`# ${$s}`)?`claude:scheduled-task:${t}`:null}async function gc(e){try{return(await uc(e,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>r.name)}catch{return[]}}var Vs,mc,$s,Js=Pe(()=>{"use strict";W();Vs="nativesoul-heartbeat",mc="nativesoul-heartbeat",$s="life:heartbeat"});import{mkdir as fc,readFile as hc,writeFile as yc}from"node:fs/promises";import ot from"node:path";import{fileURLToPath as _c}from"node:url";async function qs(e){try{let t=ot.join(e,Ks);await fc(t,{recursive:!0,mode:448});let r=ot.join(t,"SKILL.md"),o=await vc();return await yc(r,o??bc,"utf8"),!0}catch{return!1}}async function vc(){let e=ot.dirname(_c(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 hc(r,"utf8");return null}var Ks,th,bc,Gs=Pe(()=>{"use strict";W();Ks="nativesoul-heartbeat",th=`claude:scheduled-task:${Ks}`,bc='---\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 Xs={};Kn(Xs,{discoverClaudeScheduledTasksManifest:()=>kc});async function kc(e={}){let t=Bs(e.hostConfigRoot);if(!e.apply&&!await T(t)||(e.surface==="claude-code"?"claude-code":"claude-desktop")==="claude-code")return null;let o=await Ws(t);return o!==null?go({nativeId:o,evidenceSource:"filesystem"}):e.apply&&await qs(t)?go({nativeId:"claude:scheduled-task:nativesoul-heartbeat",evidenceSource:"filesystem-provisioned"}):await T(t)?go({nativeId:void 0,evidenceSource:"filesystem"}):null}function go(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 zs=Pe(()=>{"use strict";Js();Gs();W()});var fa={};Kn(fa,{discoverCodexAutomationsManifest:()=>Lc});import{readFile as ho}from"node:fs/promises";import qt from"node:path";import{spawnSync as Tc}from"node:child_process";async function Lc(e={}){let t=await Dc();if(t)return t;let r=await Hc(e.hostConfigRoot);return r||(e.apply?(await Fc(),await $c()):null)}async function Dc(){let e=process.env.NATIVESOUL_CODEX_AUTOMATIONS_FIXTURES;if(e)try{return yo(await ho(qt.join(e,"automations.json"),"utf8"))}catch{return null}let t=process.env.NATIVESOUL_CODEX_AUTOMATIONS_MANIFEST;if(t)try{return yo(await ho(t,"utf8"))}catch{return null}return null}async function Hc(e){let t=e??v("~/.codex"),r=[qt.join(t,"automations.json"),qt.join(t,"automations","nativesoul-heartbeat.json"),qt.join(t,"automations","manifest.json")];for(let o of r){if(!await b(o))continue;let n=await ho(o,"utf8"),s=yo(n);if(s?.supported)return s;let a=ue(n);if(!a)continue;let i=ga(a);if(i)return i}return null}async function $c(){let e=Uc();for(let t of e)for(let r of Cc){let o=await Vc(()=>Wc(t,r),Nc),n=ga(o);if(n)return n}return null}async function Fc(){let e=await de("codex");e&&Tc(e,["app-server","daemon","start"],{encoding:"utf8",stdio:"ignore",timeout:1e4})}function Uc(){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 Vc(e,t){for(let r=0;r<=t;r+=1){let o=await e();if(o!==null)return o;r<t&&await Bc(Mc)}return null}function Bc(e){return new Promise(t=>{setTimeout(t,e)})}async function Wc(e,t){let r=new AbortController,o=setTimeout(()=>r.abort(),Oc);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 ga(e){let t=Jc(e);for(let r of t){let o=Kc(r),n=JSON.stringify(r).toLowerCase();if(o&&jc.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 Jc(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 Kc(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 yo(e){let t=ue(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 jc,Cc,Oc,Nc,Mc,ha=Pe(()=>{"use strict";W();Ce();pe();jc=["life:heartbeat","nativesoul-heartbeat","life-heartbeat"],Cc=["automation/list","automations/list","scheduledAutomation/list"],Oc=1e3,Nc=2,Mc=150});import{existsSync as Zm}from"node:fs";import{mkdirSync as Sl}from"node:fs";import wl from"node:path";import{pathToFileURL as El}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:Gn(t.schema)??1,source:"host-reported"},o=jr(t.model);o&&(r.model=o);let n=qn(t.tokens_in);n!==null&&(r.tokens_in=n);let s=qn(t.tokens_out);s!==null&&(r.tokens_out=s);let a=Gn(t.cost_usd);a!==null&&(r.cost_usd=a);let i=jr(t.currency);i?r.currency=i:a!==null&&(r.currency="USD");let l=jr(t.reported_at);return l&&(r.reported_at=l),r}function Mt(e){try{return Fe(JSON.parse(e))}catch{return{}}}function jr(e){return typeof e=="string"&&e.length>0?e:null}function qn(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.trunc(e)}function Gn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function xe(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 Cr(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 Xn(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 Lt(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 Dt(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 Or(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 Nr(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:Mt(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 Mr(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 Ht(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 zn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e}}function Yn(e){return e.replaceAll("\\","\\\\").replaceAll("%","\\%").replaceAll("_","\\_")}function oe(e){return e?1:0}function $t(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 Lr(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),
|
|
5
|
+
) VALUES (?, ?, ?, ?, ?, ?, 'pending', NULL, NULL, ?, NULL)`).run(t.id,t.action,t.class,t.target??null,t.project??null,t.host??null,r),Ie(e,t.id)}function Dr(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),
|
|
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),Ie(e,t.id)}function Ie(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?Dt(r):null,warning:null}}function Hr(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(Dt),warning:null}}function $r(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 nc=Object.defineProperty;var Ae=(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?
|
|
15
|
+
LIMIT 1`).get(t.action,t.class,t.target??null,t.project??null,t.host??null);return{available:!0,approval:r?Dt(r):null,warning:null}}function Fr(e,t,r){if(!Ue(e))return{available:!1,approval:null,warning:"approvals_not_available"};let o=Ie(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),Ie(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
|
|
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 Ur(e,t){let r=e.prepare("SELECT * FROM memories WHERE id = ?").get(t);return r?xe(r):null}function Zn(e,t,r){return e.prepare("UPDATE memories SET status = ? WHERE id = ?").run(r,t),Ur(e,t)}function es(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(xe)}function ts(e,t,r,o){let n=$t(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(
|
|
25
|
+
LIMIT ?`).all(n,r,o).map(xe):Vr(e,r,o)}function rs(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(
|
|
30
|
+
LIMIT ?`).all(t,r).map(xe)}function Vr(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(
|
|
35
|
+
LIMIT ?`).all(t,r).map(xe)}function os(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(
|
|
39
|
+
LIMIT ?`).all(t.limit).map(xe)}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 Br(e,t){let r=Y(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=
|
|
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=Y(e,t.id);if(!n)throw new Error(`Project upsert did not return a row for ${t.id}`);return{project:n,inserted:!r}}function Wr(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 Y(e,t){let r=e.prepare("SELECT * FROM projects WHERE id = ?").get(t);return r?Qe(r):null}function Jr(e,t,r,o=new Date().toISOString()){if(!rt(e))return{found:!1,previous:null,project:null};let n=Y(e,t);return n?(e.prepare("UPDATE projects SET display_name = ?, updated_at = ? WHERE id = ?").run(r,o,t),{found:!0,previous:n,project:Y(e,t)}):{found:!1,previous:null,project:null}}function Kr(e,t,r=new Date().toISOString()){return as(e,t,"archived",r)}function qr(e,t,r=new Date().toISOString()){return as(e,t,"active",r)}function Gr(e,t){return e.prepare("SELECT COUNT(*) AS count FROM memories WHERE scope_project = ?").get(t)?.count??0}function Xr(e,t,r,o=new Date().toISOString()){if(!rt(e))return{found:!1,previous:null,project:null,memories_affected:0};let n=Y(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:Y(e,t),memories_affected:s.length}}catch(s){throw e.exec("ROLLBACK"),s}}function zr(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(`${ns} ${n} ORDER BY derived_last_seen_at DESC, p.id ASC LIMIT ?`).all(...o,gl(t.limit)).map(ml),warning:null}}function Yr(e,t){if(!rt(e))return{available:!1,detail:null,warning:"registry_not_available"};let r=e.prepare(`${ns} WHERE p.id = ?`).get(t);return r?{available:!0,detail:{project:Qe(r),counts:ss(r),derived_last_seen_at:r.last_activity_at??null},warning:null}:{available:!0,detail:fl(e,t),warning:null}}var ns=`
|
|
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
|
|
121
|
+
LEFT JOIN activity a ON a.project_id = p.id`;function ml(e){return{...Qe(e),counts:ss(e),derived_last_seen_at:e.last_activity_at??null}}function ss(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 gl(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 as(e,t,r,o){if(!rt(e))return{found:!1,previous:null,project:null};let n=Y(e,t);return n?(e.prepare("UPDATE projects SET status = ?, updated_at = ? WHERE id = ?").run(r,o,t),{found:!0,previous:n,project:Y(e,t)}):{found:!1,previous:null,project:null}}function fl(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:hl(i)}}function hl(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 is(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 ic(e){return{...Qe(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
|
|
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 ls(e,t){let r=e.prepare("SELECT * FROM semantic_memory_index WHERE memory_id = ?").get(t);return r?Cr(r):null}function cs(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 ic(e){return{...Qe(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(
|
|
144
|
+
LIMIT ?`).all(t.project,t.providerId,t.modelId,t.schemaVersion,t.limit).map(Cr)}function ds(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 ic(e){return{...Qe(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
|
|
158
|
+
AND m.scope_project = ?`).get(t.providerId,t.modelId,t.schemaVersion,t.project);return ps(r)}function us(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 ic(e){return{...Qe(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
|
|
171
|
+
WHERE m.status IN ('active', 'candidate')`).get(t.providerId,t.modelId,t.schemaVersion);return ps(r)}function ps(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=Ve(e,t.id);if(!r)throw new Error(`Work item not found after insert: ${t.id}`);return r}function Ve(e,t){if(!
|
|
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(!oo(e))return null;let r=e.prepare("SELECT * FROM work_items WHERE id = ?").get(t);return r?Or(r):null}function Zr(e,t){if(!oo(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,hs(t.limit)).map(Or)}function eo(e,t){if(!oo(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,l=t.metadata!==void 0?t.metadata:r.metadata,c=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(
|
|
177
|
+
WHERE id = ?`).run(o,n,s,a,JSON.stringify(i),JSON.stringify(l),c,u,t.updatedAt,t.id),t.event&&ms(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 to(e,t){ms(e,t);let r=bl(e,t.id);if(!r)throw new Error(`Work item event not found after insert: ${t.id}`);return r}function ro(e,t,r){return gs(e)?e.prepare("SELECT * FROM work_item_events WHERE work_item_id = ? ORDER BY created_at DESC, id DESC LIMIT ?").all(t,hs(r)).map(Nr):[]}function ms(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
|
|
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 bl(e,t){if(!gs(e))return null;let r=e.prepare("SELECT * FROM work_item_events WHERE id = ?").get(t);return r?Nr(r):null}function oo(e){return fs(e,"work_items")}function gs(e){return fs(e,"work_item_events")}function fs(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 hs(e){return!e||!Number.isFinite(e)?50:Math.min(Math.max(Math.trunc(e),1),500)}import{createRequire as kl}from"node:module";var Rl=kl(import.meta.url),Ft=null;function ys(){if(Ft)return Ft;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 Ft=Rl("node:sqlite"),Ft}finally{process.emitWarning=e}}function _s(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 bs(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 ic(e){return{...Qe(e),coun
|
|
|
214
214
|
|
|
215
215
|
CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts
|
|
216
216
|
USING fts5(id UNINDEXED, summary, content);
|
|
217
|
-
`),
|
|
217
|
+
`),Te(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 ic(e){return{...Qe(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
|
-
`),
|
|
237
|
+
`),Te(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 ic(e){return{...Qe(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
|
-
`),
|
|
360
|
+
`),Te(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 ic(e){return{...Qe(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
|
-
`),
|
|
376
|
+
`),Te(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 ic(e){return{...Qe(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),
|
|
407
|
+
WHERE p IS NOT NULL AND p <> ''`).run(t,t,t),Te(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 ic(e){return{...Qe(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
|
-
`),
|
|
441
|
+
`),Te(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 ic(e){return{...Qe(e),coun
|
|
|
454
454
|
);
|
|
455
455
|
|
|
456
456
|
CREATE INDEX IF NOT EXISTS idx_approvals_status ON approvals(status);
|
|
457
|
-
`),
|
|
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(
|
|
457
|
+
`),Te(e,7,"approvals","sha256:approvals")}function Te(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 vs=["hosts","sessions","memory_edges","commitments","standing_orders","capability_sources","capability_experience","schedules","leases","runs","work_items","work_item_events"];var Ut=class{path;db;constructor(t,r={}){this.path=t,r.readOnly||Sl(wl.dirname(t),{recursive:!0,mode:448});let{DatabaseSync:o}=ys(),n=r.readOnly?Al(t):t;this.db=new o(n,r.readOnly?{readOnly:!0}:{}),_s(this.db,{readOnly:r.readOnly}),r.readOnly||bs(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(vs.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(Xn)}createApproval(t){return Lr(this.db,t)}createDecidedApproval(t){return Dr(this.db,t)}getApproval(t){return Ie(this.db,t)}listApprovals(t){return Hr(this.db,t)}findPendingApprovalMatch(t){return $r(this.db,t)}decideApproval(t,r){return Fr(this.db,t,r)}insertWorkItem(t){return Qr(this.db,t)}getWorkItem(t){return Ve(this.db,t)}listWorkItems(t){return Zr(this.db,t)}updateWorkItem(t){return eo(this.db,t)}insertWorkItemEvent(t){return to(this.db,t)}listWorkItemEvents(t,r){return ro(this.db,t,r)}insertMemory(t){Qn(this.db,t)}getMemory(t){return Ur(this.db,t)}updateMemoryStatus(t,r){return Zn(this.db,t,r)}listMemories(t){return es(this.db,t)}upsertProject(t){return Br(this.db,t)}getProject(t){return Y(this.db,t)}listProjects(t){return Wr(this.db,t)}listProjectsWithCounts(t={}){return zr(this.db,t)}getProjectDetail(t){return Yr(this.db,t)}renameProject(t,r,o){return Jr(this.db,t,r,o)}archiveProject(t,r){return Kr(this.db,t,r)}reactivateProject(t,r){return qr(this.db,t,r)}countProjectMemories(t){return Gr(this.db,t)}forgetProjectMemories(t,r,o){return Xr(this.db,t,r,o)}searchMemories(t,r,o){return ts(this.db,t,r,o)}listActiveMemoriesForProject(t,r){return rs(this.db,t,r)}recentMemories(t,r){return Vr(this.db,t,r)}listSemanticIndexableMemories(t){return os(this.db,t)}upsertSemanticIndex(t){is(this.db,t)}getSemanticIndex(t){return ls(this.db,t)}listCurrentSemanticIndexesForProject(t){return cs(this.db,t)}semanticIndexStatsForProject(t){return ds(this.db,t)}semanticIndexStats(t){return us(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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -472,18 +472,18 @@ LEFT JOIN activity a ON a.project_id = p.id`;function ic(e){return{...Qe(e),coun
|
|
|
472
472
|
healthy = excluded.healthy,
|
|
473
473
|
allowed = excluded.allowed,
|
|
474
474
|
ready = excluded.ready,
|
|
475
|
-
last_seen_at = excluded.last_seen_at`),o=this.db.prepare("DELETE FROM capability_fts WHERE uid = ?"),n=this.db.prepare("INSERT INTO capability_fts (uid, host, native_kind, normalized_kind, source) VALUES (?, ?, ?, ?, ?)");this.db.exec("BEGIN IMMEDIATE");try{for(let s of t)r.run(s.uid,s.host,s.native_kind,s.normalized_kind,s.source,s.schema_hash,oe(s.installed),oe(s.enabled),oe(s.active),oe(s.authenticated),oe(s.healthy),oe(s.allowed),oe(s.ready),s.last_seen_at),o.run(s.uid),n.run(s.uid,s.host,s.native_kind,s.normalized_kind,s.source);this.db.exec("COMMIT")}catch(s){throw this.db.exec("ROLLBACK"),s}}listCapabilities(t){let r=[],o=[];t.host&&(t.includeShared===!1?r.push("host = ?"):r.push("(host = ? OR host = 'all')"),o.push(t.host)),t.readyOnly&&r.push("ready = 1");let n=r.length?`WHERE ${r.join(" AND ")}`:"";return this.db.prepare(`SELECT * FROM capabilities ${n} ORDER BY last_seen_at DESC, uid ASC LIMIT ?`).all(...o,t.limit).map(
|
|
475
|
+
last_seen_at = excluded.last_seen_at`),o=this.db.prepare("DELETE FROM capability_fts WHERE uid = ?"),n=this.db.prepare("INSERT INTO capability_fts (uid, host, native_kind, normalized_kind, source) VALUES (?, ?, ?, ?, ?)");this.db.exec("BEGIN IMMEDIATE");try{for(let s of t)r.run(s.uid,s.host,s.native_kind,s.normalized_kind,s.source,s.schema_hash,oe(s.installed),oe(s.enabled),oe(s.active),oe(s.authenticated),oe(s.healthy),oe(s.allowed),oe(s.ready),s.last_seen_at),o.run(s.uid),n.run(s.uid,s.host,s.native_kind,s.normalized_kind,s.source);this.db.exec("COMMIT")}catch(s){throw this.db.exec("ROLLBACK"),s}}listCapabilities(t){let r=[],o=[];t.host&&(t.includeShared===!1?r.push("host = ?"):r.push("(host = ? OR host = 'all')"),o.push(t.host)),t.readyOnly&&r.push("ready = 1");let n=r.length?`WHERE ${r.join(" AND ")}`:"";return this.db.prepare(`SELECT * FROM capabilities ${n} ORDER BY last_seen_at DESC, uid ASC LIMIT ?`).all(...o,t.limit).map(Lt)}searchCapabilities(t){let r=$t(t.query);if(!r)return this.listCapabilities({host:t.host,readyOnly:t.readyOnly,limit:t.limit,includeShared:t.includeShared});let o=["capability_fts MATCH ?"],n=[r];return t.host&&(t.includeShared===!1?o.push("c.host = ?"):o.push("(c.host = ? OR c.host = 'all')"),n.push(t.host)),t.readyOnly&&o.push("c.ready = 1"),this.db.prepare(`SELECT c.*
|
|
476
476
|
FROM capability_fts f
|
|
477
477
|
JOIN capabilities c ON c.uid = f.uid
|
|
478
478
|
WHERE ${o.join(" AND ")}
|
|
479
479
|
ORDER BY rank
|
|
480
|
-
LIMIT ?`).all(...n,t.limit).map(
|
|
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=
|
|
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(
|
|
480
|
+
LIMIT ?`).all(...n,t.limit).map(Lt)}getCapability(t){let r=this.db.prepare("SELECT * FROM capabilities WHERE uid = ?").get(t);return r?Lt(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?Ht(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=ks(t.summary),n=this.listCommitments({project:t.project_id,status:"open",includeExpired:!1,limit:200,now:r,skipExpire:!0}).find(a=>ks(a.summary)===o);if(n)return this.db.exec("COMMIT"),{created:!1,commitment:n};this.db.prepare(`INSERT INTO commitments (id, project_id, summary, status, due_at, ttl_expires_at, source_json, created_at, updated_at)
|
|
482
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.project_id,t.summary,t.status,t.due_at,t.ttl_expires_at,JSON.stringify(t.source),t.created_at,t.updated_at);let s=this.getCommitment(t.id);if(!s)throw new Error(`Commitment not found after insert: ${t.id}`);return this.db.exec("COMMIT"),{created:!0,commitment:s}}catch(o){throw this.db.exec("ROLLBACK"),o}}listCommitments(t){t.skipExpire||this.expireCommitments(t.now);let r=[],o=[];t.project&&(r.push("project_id = ?"),o.push(t.project)),t.status?(r.push("status = ?"),o.push(t.status)):t.includeExpired||r.push("status != 'expired'");let n=r.length?`WHERE ${r.join(" AND ")}`:"";return this.db.prepare(`SELECT * FROM commitments ${n} ORDER BY updated_at DESC, id DESC LIMIT ?`).all(...o,t.limit).map(Ht)}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
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
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({...
|
|
486
|
+
VALUES (?, 'heartbeat', ?, ?, 'completed', ?, ?, ?, ?, ?)`).run(t.runId,r.holder,t.project,JSON.stringify(Fe(t.cost)),JSON.stringify(t.result),JSON.stringify({...zn(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:${Yn(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 ic(e){return{...Qe(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(
|
|
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(Mr)}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?et(o):null}getSchedule(t){let r=this.db.prepare("SELECT * FROM schedules WHERE id = ?").get(t);return r?
|
|
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?Mr(r):null}getCommitment(t){let r=this.db.prepare("SELECT * FROM commitments WHERE id = ?").get(t);return r?Ht(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 Pl(this.db,t)?this.db.prepare(`SELECT COUNT(*) as count FROM ${t}`).get()?.count??0:0}};function f(e,t={}){return new Ut(e,t)}function Al(e){return`${El(e).href}?mode=ro&immutable=1`}function ks(e){return e.trim().replace(/\s+/gu," ").toLocaleLowerCase()}function Pl(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 Fl,mkdir as Ul}from"node:fs/promises";import Vl from"node:os";import Bl from"node:path";import{createHash as xl,randomUUID as Il}from"node:crypto";function P(e){return`${e}_${Il()}`}function $(e){return`sha256:${xl("sha256").update(e).digest("hex")}`}function no(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(r=>no(r)).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${no(e[r]??null)}`).join(",")}}`}function je(e){return $(no(e))}import{existsSync as Qg}from"node:fs";import ef from"node:os";var Rs=[{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 jl=Rs.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 jl)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 O(e){if(typeof e=="string")return N(e).value;if(Array.isArray(e))return e.map(t=>O(t));if(e&&typeof e=="object"){let t={};for(let[r,o]of Object.entries(e))t[r]=O(o);return t}return e}import{mkdir as Es,readFile as Cl,writeFile as so}from"node:fs/promises";import{constants as Ol,existsSync as As}from"node:fs";import{access as Nl}from"node:fs/promises";import Ml from"node:os";import se from"node:path";var Vt={"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
|
-
`},
|
|
797
|
+
`},Ss=`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
|
|
807
|
+
`;function ws(e){return`# Daily notes \u2014 ${e}
|
|
808
808
|
|
|
809
809
|
_Running context for today. Promote durable facts to curated memory later._
|
|
810
810
|
|
|
@@ -819,27 +819,28 @@ _Running context for today. Promote durable facts to curated memory later._
|
|
|
819
819
|
## Follow-ups
|
|
820
820
|
|
|
821
821
|
-
|
|
822
|
-
`}var
|
|
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
|
|
825
|
-
${d.content}`)])),
|
|
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
|
|
828
|
-
|
|
822
|
+
`}var Ll=["memory/daily","memory/projects","memory/archive","commitments","standing-orders","capabilities/cards","generated","state","logs","backups","proposals"],Dl=Vt;function Ps(e){return se.resolve(e??process.env.NATIVESOUL_HOME??se.join(Ml.homedir(),".nativesoul"))}function p(e){let t=Ps(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 Nl(e,Ol.F_OK),!0}catch{return!1}}async function _(e){let t=p(e),r=[],o=[],n=[];As(t.home)||(await Es(t.home,{recursive:!0,mode:448}),r.push(t.home));for(let i of Ll){let l=se.join(t.home,i);As(l)||(await Es(l,{recursive:!0,mode:448}),r.push(l))}let s=await y(se.join(t.home,"state","onboarding.complete"));for(let[i,l]of Object.entries(Dl)){if(i==="BOOTSTRAP.md"&&s)continue;let c=se.join(t.home,i);if(await y(c)){n.push(c);continue}try{await so(c,l,{encoding:"utf8",mode:384,flag:"wx"}),o.push(c)}catch(u){if(Hl(u)){n.push(c);continue}throw u}}let a=await $l(t.home);return o.push(...a.createdFiles),n.push(...a.preservedFiles),{home:t.home,database:t.database,createdDirectories:r,createdFiles:o,preservedFiles:n}}function Hl(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}async function $l(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 so(n,ws(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 so(s,Ss,{encoding:"utf8",mode:384,flag:"wx"}),t.push(s)),{createdFiles:t,preservedFiles:r}}async function Q(e,t){let r=se.join(e,t);return await y(r)?Cl(r,"utf8"):""}async function m(e){let t=p(e.home),r=new Date().toISOString(),o=io(O(e.details??{}),t.home),n={id:P("evt"),type:e.type,actor:e.actor??"cli",origin:e.origin??"nativesoul",result:e.result??"ok",details:o,created_at:r,hash:je({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 Ul(Bl.dirname(t.auditLog),{recursive:!0,mode:448}),await Fl(t.auditLog,`${JSON.stringify(n)}
|
|
823
|
+
`,{encoding:"utf8",mode:384}),n}function io(e,t){if(typeof e=="string")return Wl(e,t);if(Array.isArray(e))return e.map(r=>io(r,t));if(e&&typeof e=="object"){let r={};for(let[o,n]of Object.entries(e))r[o]=io(n,t);return r}return e}function Wl(e,t){return[[new RegExp(ao(t),"gu"),"[REDACTED_NATIVESOUL_HOME]"],[new RegExp(ao(process.cwd()),"gu"),"[REDACTED_WORKSPACE]"],[new RegExp(ao(Vl.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 ao(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}import ge from"node:path";import{existsSync as gu}from"node:fs";import{mkdir as yy,readdir as kd,readFile as Rd,writeFile as _y}from"node:fs/promises";import{existsSync as vy}from"node:fs";import Ma from"node:path";Ce();W();pe();W();import{readdir as ec}from"node:fs/promises";import K from"node:path";var Z="antigravity",tc="~/.gemini/GEMINI.md",rc="~/.antigravity",co="official:antigravity-plugin-config:v1",Cs="official:antigravity-hooks-config:v1",Os="official:antigravity-mcp-config:v1",Ns="official:antigravity-command-config:v1",oc="official:antigravity-context-config:v1",nc="official:antigravity-features:v1",sc=[{uid:"antigravity:plugins",nativeKind:"plugins",normalizedKind:"package",relativePath:"plugins"}];function uo(){let e=process.env.NATIVESOUL_ANTIGRAVITY_INVENTORY_ROOT?.trim();return e?K.resolve(e):v(rc)}function ac(){let e=uo();return{root:e,globalInstruction:process.env.NATIVESOUL_ANTIGRAVITY_INVENTORY_ROOT?.trim()?K.join(e,"GEMINI.md"):v(tc)}}async function Ms(){let e=[],t=ac();await b(t.globalInstruction)&&e.push({uid:"antigravity:global-gemini-md",host:Z,nativeKind:"global_context",normalizedKind:"instruction",source:t.globalInstruction,schemaHash:oc}),await ic(t.root,e),await lc(t.root,e);for(let r of sc){let o=K.join(t.root,r.relativePath);await T(o)&&e.push({uid:r.uid,host:Z,nativeKind:r.nativeKind,normalizedKind:r.normalizedKind,source:o,schemaHash:co})}return e}async function ic(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,l,c]=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:Z,nativeKind:"plugin",normalizedKind:"extension",source:r,schemaHash:co})}if(i){let u=R(i,["name","id"])??"unknown";t.push({uid:`antigravity:package:${E(u)}`,host:Z,nativeKind:"native_plugin_package",normalizedKind:"package",source:o,schemaHash:co});let d=w(i.nativeSoul)?i.nativeSoul:{};for(let A of Wt(d.commands))t.push({uid:`antigravity:command:${E(A)}`,host:Z,nativeKind:"command",normalizedKind:"command",source:`${o}:nativeSoul.commands.${A}`,schemaHash:Ns});let g=w(d.mcpServer)?d.mcpServer:null,h=R(g,["name"]);h&&t.push({uid:`antigravity:mcp:${E(h)}`,host:Z,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${o}:nativeSoul.mcpServer.${h}`,schemaHash:Os})}if(l){t.push({uid:"antigravity:hooks:manifest",host:Z,nativeKind:"hooks",normalizedKind:"lifecycle_hooks",source:n,schemaHash:Cs});let u=w(l.hooks)?l.hooks:{};for(let d of Object.keys(u))t.push({uid:`antigravity:hook:${E(d)}`,host:Z,nativeKind:"hook",normalizedKind:"lifecycle_hook",source:`${n}:hooks.${d}`,schemaHash:Cs})}if(c)for(let u of _e(c.mcpServers))t.push({uid:`antigravity:mcp:${E(u)}`,host:Z,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${s}:mcpServers.${u}`,schemaHash:Os});await cc(K.join(e,"commands"),t)}async function lc(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:Z,nativeKind:"product_feature",normalizedKind:"feature_evidence",source:`${r}:${s}`,schemaHash:nc})}async function cc(e,t){if(!await T(e))return;let r=await ec(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:Z,nativeKind:"command",normalizedKind:"command",source:K.join(e,o.name),schemaHash:Ns})}}W();pe();import Jt from"node:path";async function Ls(e){let t=await dc(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 dc(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 Jt.join(Jt.resolve(r),"scheduler-proof.json");let o=e??v("~/.antigravity"),n=[Jt.join(o,"scheduler-proof.json"),Jt.join(o,"native-scheduler-proof.json")];for(let s of n)if(await b(s))return s;return null}function Ds(e){if(!e)return!1;let t=Date.parse(e);return Number.isFinite(t)?Date.now()-t>10080*60*1e3:!0}var Be="antigravity",po="~/.gemini/GEMINI.md",mo=class{async detect(){let t=v(po),r=uo(),[o,n,s]=await Promise.all([b(t),T(r),de("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 Ms()}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 Ls(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(Ds(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(po),o=await L(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&&!F(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(po),r=await L(t);return{host:Be,targetPath:t,startMarker:"<!-- nativesoul:antigravity:start v1 -->",endMarker:"<!-- nativesoul:antigravity:end -->",content:ae(Be),wouldCreate:r===null,wouldUpdate:r!==null&&!F(r,Be)}}};function Hs(){return new mo}Ce();pe();W();import We from"node:path";import{readFile as na}from"node:fs/promises";pe();import{readFile as Ys}from"node:fs/promises";import Rc from"node:path";var ea="life:heartbeat";function ta(e){if(!e||typeof e!="object"||Array.isArray(e))return{kind:"unknown",mode:"leader",apply:!1,skill:ea};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:Ac(t),surface:Zs(t.surface)??Zs(w(t.desired)?t.desired.surface:void 0)}}async function ra(e={}){let t=process.env.NATIVESOUL_CLAUDE_SCHEDULED_TASKS_FIXTURES;if(t)try{return Qs(await Ys(Rc.join(t,"scheduled-tasks.json"),"utf8"))}catch{return null}let r=process.env.NATIVESOUL_CLAUDE_SCHEDULED_TASKS_MANIFEST;if(r)try{return Qs(await Ys(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(()=>(zs(),Xs));return o({apply:e.apply,surface:e.surface,hostConfigRoot:e.hostConfigRoot})}function oa(e,t){return!e||e==="default"||!t?!0:e===t}function Qs(e){let t=ue(e);if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,o=Sc(r.surface),n=wc(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:Ec(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 Zs(e){return e==="default"||e==="claude-code"||e==="claude-desktop"?e:void 0}function Sc(e){return e==="claude-code"||e==="claude-desktop"||e==="cloud"?e:void 0}function wc(e){return e==="local_scheduled_task"||e==="cloud_routine"||e==="ui_only"?e:"unknown"}function Ec(e){return e==="official_machine_readable"||e==="ui_only"||e==="unknown"?e:void 0}function Ac(e){return w(e.desired)&&typeof e.desired.skill=="string"&&e.desired.skill.trim().length>0?e.desired.skill.trim():ea}var J="claude",Kt="~/.claude/CLAUDE.md",sa="CLAUDE.md",aa=".claude/CLAUDE.md",ia="life:heartbeat",ca="official:claude-cli-hot-scan:v1",fo=class{async detect(){let t=v(Kt),r=We.resolve(sa),o=We.resolve(aa),[n,s,a,i]=await Promise.all([b(t),b(r),b(o),Bt("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(Kt),r=We.resolve(sa),o=We.resolve(aa),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 l=await Pc(o,r);if(l.status==="ready")return l}let[n,s]=await Promise.all([lo("claude",["mcp","list","--json"],1200),lo("claude",["plugin","list","--json"],1200)]),a=[],i=[];return n.status==="ok"?i.push(...da(n.stdout)):a.push(la("CLAUDE_HOT_SCAN_JSON_UNSUPPORTED","claude mcp list --json",n.stderr)),s.status==="ok"?i.push(...ua(s.stdout)):a.push(la("CLAUDE_HOT_SCAN_JSON_UNSUPPORTED","claude plugin list --json",s.stderr)),{host:J,checkedAt:r,status:a.length===0?"ready":"degraded",warnings:a.map(l=>l.code),remediation:a.length===0?void 0:"Upgrade Claude Code CLI if JSON hot-scan commands are unavailable.",capabilities:i.map(l=>({...l,installed:l.installed??!0,enabled:l.enabled??!0,active:l.active??!0,authenticated:l.authenticated??!1,healthy:l.healthy??!0,allowed:!0,ready:l.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=ta(t),o=await ra({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!==ia?{status:"error",code:"CLAUDE_HEARTBEAT_SKILL_MISMATCH",message:`Claude heartbeat Scheduled Task must invoke ${ia}.`}: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."}:oa(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(Kt),o=await L(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&&!F(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(Kt),r=await L(t);return{host:J,targetPath:t,startMarker:"<!-- nativesoul:claude:start v1 -->",endMarker:"<!-- nativesoul:claude:end -->",content:ae(J),wouldCreate:r===null,wouldUpdate:r!==null&&!F(r,J)}}};async function Pc(e,t){try{let[r,o]=await Promise.all([na(We.join(e,"mcp-list.json"),"utf8"),na(We.join(e,"plugin-list.json"),"utf8")]),n=[...da(r),...ua(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 da(e){let t=ue(e);return be(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:ca,enabled:s,active:s,authenticated:V(r,["authenticated"])??a,healthy:s,ready:pa(n)}]})}function ua(e){let t=ue(e);return be(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=V(r,["enabled"])??n!=="disabled",a=V(r,["installed"])??!0;return[{uid:`claude:plugin:${xc(o)}`,host:J,nativeKind:"plugin",normalizedKind:"extension",source:`claude plugin list --json:${o}`,schemaHash:ca,installed:a,enabled:s,active:s,authenticated:V(r,["authenticated"])??s,healthy:a,ready:s&&(n===null||pa(n)||V(r,["enabled"])===!0)}]})}function la(e,t,r){let o=Ic(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 pa(e){return e==="ready"||e==="enabled"||e==="active"||e==="ok"||e==="authenticated"||e==="connected"}function xc(e){return E(e,{allowSlash:!0})}function Ic(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 ma(){return new fo}Ce();pe();W();import bo from"node:path";var B="codex",Gt="~/.codex/AGENTS.md",ya="AGENTS.md",qc=1e3,_a="life:heartbeat",zt="official:codex-app-server:v1",vo=class{async detect(){let t=v(Gt),r=bo.resolve(ya),[o,n,s]=await Promise.all([b(t),b(r),de("codex")]);return{host:B,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(Gt),r=bo.resolve(ya),o=[];return await b(t)&&o.push({uid:"codex:global-agents-md",host:B,nativeKind:"global_context",normalizedKind:"instruction",source:t}),await b(r)&&o.push({uid:"codex:project-agents-md",host:B,nativeKind:"project_context",normalizedKind:"instruction",source:r}),o}async hotProbe(t){let r=new Date().toISOString(),o=Zc(t);if(o){let i=await _o(o,r);if(i.status==="ready")return i}let n=process.env.NATIVESOUL_CODEX_APP_SERVER_FIXTURES?.trim();if(n){let i=await _o(td(n),r);if(i.status==="ready")return i}let s=ed(t);if(s){let i=await _o(rd(s),r);if(i.status==="ready")return i}let a=await this.coldScan();return{host:B,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(()=>(ha(),fa)),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!==_a?{status:"error",code:"CODEX_HEARTBEAT_SKILL_MISMATCH",message:`Codex heartbeat Automation must invoke ${_a}.`}: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(Gt),o=await L(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&&!F(o,B)&&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(Gt),r=await L(t);return{host:B,targetPath:t,startMarker:"<!-- nativesoul:codex:start v1 -->",endMarker:"<!-- nativesoul:codex:end -->",content:ae(B),wouldCreate:r===null,wouldUpdate:r!==null&&!F(r,B)}}};async function _o(e,t){let[r,o,n,s]=await Promise.all([Xt(e,"mcpServerStatus/list"),Xt(e,"plugin/list"),Xt(e,"skills/list"),Xt(e,"app/list")]);if([r,o,n,s].some(l=>l===null))return{host:B,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=[...Xc(r),...zc(o),...Yc(n),...Qc(s)];return{host:B,checkedAt:t,status:"ready",warnings:[],capabilities:i.map(l=>({...l,installed:l.installed??!0,enabled:l.enabled??!0,active:l.active??!0,authenticated:l.authenticated??!1,healthy:l.healthy??!0,allowed:!0,ready:l.ready??!1}))}}async function Xt(e,t){try{return await e.call(t)}catch{return null}}async function Gc(e,t){let r=new AbortController,o=setTimeout(()=>r.abort(),qc);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 Xc(e){return be(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=Yt(t,o);return[{uid:`codex:mcp:${E(r)}`,host:B,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`codex app server mcpServerStatus/list:${r}`,schemaHash:zt,...n}]})}function zc(e){return be(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=Yt(t,o);return[{uid:`codex:plugin:${ko(r)}`,host:B,nativeKind:"plugin",normalizedKind:"extension",source:`codex app server plugin/list:${r}`,schemaHash:zt,...n}]})}function Yc(e){return be(e,["skills","items"]).flatMap(t=>{let r=R(t,["id","name","path"]);if(!r)return[];let o=R(t,["status","state"]),n=Yt(t,o);return[{uid:`codex:skill:${ko(r)}`,host:B,nativeKind:"skill",normalizedKind:"skill",source:`codex app server skills/list:${r}`,schemaHash:zt,...n}]})}function Qc(e){return be(e,["apps","items"]).flatMap(t=>{let r=R(t,["id","name","app"]);if(!r)return[];let o=R(t,["status","state"]),n=Yt(t,o);return[{uid:`codex:app:${ko(r)}`,host:B,nativeKind:"app_server_app",normalizedKind:"app",source:`codex app server app/list:${r}`,schemaHash:zt,...n}]})}function Yt(e,t){let r=V(e,["installed"])??!0,o=t==="disabled"||t==="unavailable",n=t==="error"||t==="unhealthy",s=V(e,["enabled"])??!o,a=V(e,["active"])??s,i=V(e,["healthy"])??(!o&&!n),l=V(e,["authenticated"])??V(e,["auth"])??!1,c=V(e,["ready"])??(r&&s&&a&&i);return{installed:r,enabled:s,active:a,authenticated:l,healthy:i,ready:c}}function Zc(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 ed(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 td(e){return{async call(t){try{let{readFile:r}=await import("node:fs/promises"),o=t.replace(/\//gu,"-");return JSON.parse(await r(bo.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 rd(e){return{call:t=>Gc(e,t)}}function ko(e){return E(e,{allowSlash:!0})}function ba(){return new vo}Ce();pe();W();import{readdir as ka}from"node:fs/promises";import ee from"node:path";var U="gemini",So="~/.gemini/GEMINI.md",od="~/.gemini/extensions",nd="~/.gemini/settings.json",nt="official:gemini-extension-config:v1",Ro="official:gemini-settings-config:v1",sd="official:gemini-memory-config:v1",wo=class{async detect(){let t=va(),r=t.globalInstruction,o=t.extensionsDirectory,[n,s,a]=await Promise.all([b(r),T(o),Bt("gemini",["--version"])]);return{host:U,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=va(),o=r.globalInstruction;await b(o)&&t.push({uid:"gemini:global-gemini-md",host:U,nativeKind:"global_context",normalizedKind:"memory",source:o,schemaHash:sd}),await ad(r.settingsFile,t);let n=r.extensionsDirectory;if(await T(n)){t.push({uid:"gemini:extensions",host:U,nativeKind:"extensions",normalizedKind:"package",source:n,schemaHash:nt});let s=await ka(n,{withFileTypes:!0});for(let a of s)a.isDirectory()&&await id(ee.join(n,a.name),a.name,t)}return t}async hotProbe(){let t=await this.coldScan();return{host:U,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(So),o=await L(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&&!F(o,U)&&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(So),r=await L(t);return{host:U,targetPath:t,startMarker:"<!-- nativesoul:gemini:start v1 -->",endMarker:"<!-- nativesoul:gemini:end -->",content:ae(U),wouldCreate:r===null,wouldUpdate:r!==null&&!F(r,U)}}};function va(){let e=process.env.NATIVESOUL_GEMINI_INVENTORY_ROOT?.trim();if(e){let t=ee.resolve(e);return{globalInstruction:ee.join(t,"GEMINI.md"),settingsFile:ee.join(t,"settings.json"),extensionsDirectory:ee.join(t,"extensions")}}return{globalInstruction:v(So),settingsFile:v(nd),extensionsDirectory:v(od)}}async function ad(e,t){let r=await H(e);if(r){t.push({uid:"gemini:settings",host:U,nativeKind:"settings",normalizedKind:"config",source:e,schemaHash:Ro});for(let o of _e(r.mcpServers))t.push({uid:`gemini:mcp:${E(o)}`,host:U,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${e}:mcpServers.${o}`,schemaHash:Ro});for(let o of Ra(r.tools))t.push({uid:`gemini:tool:${E(o)}`,host:U,nativeKind:"tool",normalizedKind:"tool",source:`${e}:tools.${o}`,schemaHash:Ro})}}async function id(e,t,r){let o=ee.join(e,"gemini-extension.json"),n=await H(o),s=R(n,["name","id"])??t;if(r.push({uid:`gemini:extension:${E(s)}`,host:U,nativeKind:"extension",normalizedKind:"package",source:n?o:e,schemaHash:n?nt:void 0}),n){for(let a of _e(n.mcpServers))r.push({uid:`gemini:mcp:${E(a)}`,host:U,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${o}:mcpServers.${a}`,schemaHash:nt});for(let a of Ra(n.tools))r.push({uid:`gemini:tool:${E(a)}`,host:U,nativeKind:"tool",normalizedKind:"tool",source:`${o}:tools.${a}`,schemaHash:nt})}await ld(ee.join(e,"commands"),r)}async function ld(e,t){if(!await T(e))return;let r=await ka(e,{withFileTypes:!0});for(let o of r){if(!o.isFile()||![".toml",".md"].includes(ee.extname(o.name)))continue;let n=ee.basename(o.name,ee.extname(o.name));t.push({uid:`gemini:command:${E(n,{allowSlash:!0})}`,host:U,nativeKind:"command",normalizedKind:"command",source:ee.join(e,o.name),schemaHash:nt})}}function Ra(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):_e(e)}function Sa(){return new wo}Ce();pe();W();import{readdir as xa}from"node:fs/promises";import C from"node:path";var j="grok",Qt="~/.grok/Agents.md",wa="AGENTS.md",Ea="Agents.md",Aa="CLAUDE.md",cd="~/.grok",Eo="official:grok-plugin-config:v1",Pa="official:grok-hooks-config:v1",Ao="official:grok-mcp-config:v1",Ia="official:grok-command-config:v1",dd="official:grok-context-config:v1",ud=[{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"}],Po=class{async detect(){let t=v(Qt),r=C.resolve(wa),o=C.resolve(Ea),n=C.resolve(Aa),s=Ta(),[a,i,l,c,u,d]=await Promise.all([b(t),b(r),b(o),b(n),T(s),de("grok")]),g=i||l;return{host:j,detected:a||g||c||u||d!==null,path:a?t:l?o:i?r:c?n:d??void 0,capabilities:{installed:a||g||c||u||d!==null,enabled:a||g||c||u,active:g||c,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=pd(),o=r.globalInstruction;await b(o)&&t.push({uid:"grok:global-agents-md",host:j,nativeKind:"global_context",normalizedKind:"instruction",source:o,schemaHash:dd});let n=C.resolve(wa);await b(n)&&t.push({uid:"grok:project-agents-md",host:j,nativeKind:"project_context",normalizedKind:"instruction",source:n});let s=C.resolve(Ea);await b(s)&&t.push({uid:"grok:project-agents-titlecase-md",host:j,nativeKind:"project_context",normalizedKind:"instruction",source:s});let a=C.resolve(Aa);await b(a)&&t.push({uid:"grok:project-claude-md",host:j,nativeKind:"project_context",normalizedKind:"instruction",source:a});let i=r.root;await ja(r.root,t),await md(i,t);for(let l of ud){let c=C.join(i,l.relativePath);await T(c)&&t.push({uid:l.uid,host:j,nativeKind:l.nativeKind,normalizedKind:l.normalizedKind,source:c,schemaHash:l.relativePath==="mcps"?Ao:Eo})}return fd(t)}async hotProbe(){let t=await this.coldScan();return{host:j,checkedAt:new Date().toISOString(),capabilities:t.map(r=>({...r,installed:!0,enabled:!0,active:r.uid.includes("project"),authenticated:!1,healthy:!0,allowed:!0,ready:r.schemaHash?.startsWith("official:")===!0}))}}async bootstrap(){return{tier:"A",mechanism:"hook",supported:!0}}async reload(t){return{status:"unsupported",reason:"Grok reload is host-driven; use the installed NativeSoul command package or restart the host if needed."}}async update(t){return{status:"unsupported",reason:"Grok package updates are handled by the NativeSoul install orchestrator."}}async scheduleReconcile(t){return{status:"unsupported",reason:"Grok has no documented native scheduler or recurring task surface for NativeSoul; headless grok -p, cron, GitHub Actions, systemd, and Windows Task Scheduler are external schedulers and do not satisfy full-native capability."}}async doctor(){let t=await this.detect(),r=v(Qt),o=await L(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&&!F(o,j)&&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(Qt),r=await L(t);return{host:j,targetPath:t,startMarker:"<!-- nativesoul:grok:start v1 -->",endMarker:"<!-- nativesoul:grok:end -->",content:ae(j),wouldCreate:r===null,wouldUpdate:r!==null&&!F(r,j)}}};function Ta(){let e=process.env.NATIVESOUL_GROK_INVENTORY_ROOT?.trim();return e?C.resolve(e):v(cd)}function pd(){let e=Ta();return{root:e,globalInstruction:process.env.NATIVESOUL_GROK_INVENTORY_ROOT?.trim()?C.join(e,"Agents.md"):v(Qt)}}async function ja(e,t){let r=C.join(e,"plugin.json"),o=C.join(e,"nativesoul-package.json"),n=C.join(e,"hooks","hooks.json"),s=C.join(e,".mcp.json"),[a,i,l,c]=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:j,nativeKind:"plugin",normalizedKind:"extension",source:r,schemaHash:Eo})}if(i){let u=R(i,["name","id"])??"unknown";t.push({uid:`grok:package:${E(u)}`,host:j,nativeKind:"native_plugin_package",normalizedKind:"package",source:o,schemaHash:Eo});let d=w(i.nativeSoul)?i.nativeSoul:{};for(let A of Wt(d.commands))t.push({uid:`grok:command:${E(A)}`,host:j,nativeKind:"command",normalizedKind:"command",source:`${o}:nativeSoul.commands.${A}`,schemaHash:Ia});let g=w(d.mcpServer)?d.mcpServer:null,h=R(g,["name"]);h&&t.push({uid:`grok:mcp:${E(h)}`,host:j,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${o}:nativeSoul.mcpServer.${h}`,schemaHash:Ao})}if(l){t.push({uid:"grok:hooks:manifest",host:j,nativeKind:"hooks",normalizedKind:"lifecycle_hooks",source:n,schemaHash:Pa});let u=w(l.hooks)?l.hooks:{};for(let d of Object.keys(u))t.push({uid:`grok:hook:${E(d)}`,host:j,nativeKind:"hook",normalizedKind:"lifecycle_hook",source:`${n}:hooks.${d}`,schemaHash:Pa})}if(c)for(let u of _e(c.mcpServers))t.push({uid:`grok:mcp:${E(u)}`,host:j,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${s}:mcpServers.${u}`,schemaHash:Ao});await gd(C.join(e,"commands"),t)}async function md(e,t){let r=C.join(e,"plugins");if(!await T(r))return;let o=await xa(r,{withFileTypes:!0});for(let n of o)n.isDirectory()&&await ja(C.join(r,n.name),t)}async function gd(e,t){if(!await T(e))return;let r=await xa(e,{withFileTypes:!0});for(let o of r){if(!o.isFile()||C.extname(o.name)!==".md")continue;let n=C.basename(o.name,".md");t.push({uid:`grok:command:${E(n,{allowSlash:!0})}`,host:j,nativeKind:"command",normalizedKind:"command",source:C.join(e,o.name),schemaHash:Ia})}}function fd(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 Ca(){return new Po}import{mkdir as Xh,readFile as hd,rm as zh,writeFile as Yh}from"node:fs/promises";import{existsSync as yd}from"node:fs";import ey from"node:path";import{lstatSync as Uh,realpathSync as Vh,statSync as Bh}from"node:fs";import Jh from"node:path";var Kh=process.platform!=="win32";function _d(e){return{start:`<!-- nativesoul:${e}:start v1 -->`,end:`<!-- nativesoul:${e}:end -->`}}async function Oa(e){let t=yd(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 hd(e.targetPath,"utf8"),n=_d(e.host),s=o.indexOf(n.start),a=o.indexOf(n.end),i=s>=0,l=a>=0,c=i&&l&&a>s;return!i&&!l?r.push({code:"MANAGED_BLOCK_MISSING",severity:"warn",message:"NativeSoul managed block is not configured.",remediation:"Run nativesoul install --host <host> --apply"}):c||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:c,markers_valid:c,issues:r}}var bd=["codex","claude","grok","antigravity","gemini"],vd={codex:ba,claude:ma,grok:Ca,antigravity:Hs,gemini:Sa};function Je(e){return e==="all"?bd:[e]}function Na(e){return Je(e)}function xo(e){return vd[e]()}async function Io(e){let t=[];for(let r of Na(e)){let o=xo(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=Ha(e.limit);try{return r.listCapabilities({host:e.host,readyOnly:e.readyOnly,limit:o,includeShared:e.includeShared})}finally{r.close()}}async function To(e){let t=await _(e.home),r=f(t.database),o=Ha(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 jo(e){let t=await _(e.home),r=f(t.database);try{return r.getCapability(e.uid)}finally{r.close()}}async function Co(e){let t=e.readOnly?p(e.home):await _(e.home),r=Ma.join(t.home,"capabilities","cards"),o=[];if(!await y(r))return{cards:[],warnings:o};let n=(await kd(r)).filter(c=>c.endsWith(".json")).sort(),s=xd(e.query??""),a=[];for(let c of n){let u=Ma.join(r,c),d;try{d=await Rd(u,"utf8")}catch{o.push(`CAPABILITY_CARD_UNREADABLE:${c}`);continue}let g=wd(d);if(!g){o.push(`CAPABILITY_CARD_MALFORMED:${c}`);continue}let h=Ed(g,e.host);a.push({card:h,score:Ad(g,e.host,s)})}let i=Id(e.limit),l=a.sort((c,u)=>u.score-c.score||c.card.uid.localeCompare(u.card.uid));return{cards:Sd(l,i).map(c=>c.card),warnings:o}}function Sd(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 wd(e){let t;try{t=JSON.parse(e)}catch{return null}if(!La(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)||!Pd(r)?null:t}function Ed(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:at(e.use_when).slice(0,2),requires:at(e.requires).slice(0,4),approval:e.approval,alternative_host:r,available_on_other_host:o}}function Ad(e,t,r){let o=Da([e.uid,e.host,e.native_kind,e.normalized_kind,e.source,e.schema_hash,...at(e.use_when),...at(e.requires),e.approval,...at(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 at(e){return e.filter(t=>typeof t=="string")}function La(e){return typeof e=="object"&&e!==null}function Pd(e){return La(e)?["installed","enabled","active","authenticated","healthy","allowed","ready"].every(t=>typeof e[t]=="boolean"):!1}function xd(e){return Da(e).split(/\s+/u).map(t=>t.trim()).filter(t=>t.length>=2)}function Da(e){return e.toLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/gu,"")}function Ha(e){return Math.min(Math.max(e??50,1),100)}function Id(e){return Math.min(Math.max(e??5,1),8)}async function Oo(e){let t=await _(e.home),r=N(e.summary).value,o=new Date,n=e.ttlSeconds?new Date(o.getTime()+jd(e.ttlSeconds)*1e3).toISOString():null,s=O(e.source??{host:"cli",session_id:"local"}),a=f(t.database),i;try{i=a.createOpenCommitmentIfMissing({id:P("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 No(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 Mo(e,t){return Td(e,t,"completed","commitment_completed")}async function Td(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 jd(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),365*24*60*60):1440*60}import{createHash as Cd}from"node:crypto";import{existsSync as Zt,mkdirSync as Od,realpathSync as Nd,readFileSync as Fa,writeFileSync as Md}from"node:fs";import{spawnSync as Ua}from"node:child_process";import ie from"node:path";function me(e,t){let r=Lo(e),o=$d(r),n=o?Fd(o):null,s=n?$a(n):o??r,a=Ud(s),i=n?"git-remote":o?"git-root":"path",l=Dd(a,s),c=Ld(r),u=c?Va(c):null,d=Wa(t),g=[u,l,n?$a(n):null,o,r].find(h=>h&&d[h]);if(g){let h=u??l;return{id:d[g]??h,source:"alias",cwd:r,git_root:o,remote:n,base_id:h,alias_key:g,marker_path:c}}return u?{id:u,source:"marker",cwd:r,git_root:o,remote:n,base_id:u,alias_key:null,marker_path:c}:{id:l,source:i,cwd:r,git_root:o,remote:n,base_id:l,alias_key:null,marker_path:null}}function Va(e){if(!Zt(e))return null;let t=Fa(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?Hd(o):null}function Ba(e,t){let r=ie.join(e,".nativesoul","project");return Od(ie.dirname(r),{recursive:!0,mode:448}),Md(r,`${t}
|
|
824
|
+
`,{encoding:"utf8",mode:384}),r}async function er(e){let t=me(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}:(Ba(r,t.base_id),{written:!0,marker_path:o,base_id:t.base_id})}function Ld(e){let t=Lo(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 Dd(e,t){let r=Cd("sha256").update(t).digest("hex").slice(0,10);return`${Vd(e)}-${r}`}function Hd(e){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"workspace"}function Lo(e){try{return Nd(ie.resolve(e))}catch{return ie.resolve(e)}}function $d(e){let t=Ua("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?Lo(r):null}function Fd(e){let t=Ua("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 $a(e){return e.trim().replace(/^git@([^:]+):/,"https://$1/").replace(/^ssh:\/\/git@([^/]+)\//,"https://$1/").replace(/^https?:\/\/([^/]+)\//,"https://$1/").replace(/\.git$/u,"").toLowerCase()}function Ud(e){let t=e.replace(/\/+$/u,"");return ie.basename(t)||"workspace"}function Vd(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"workspace"}function Wa(e){if(!e)return{};let t=ie.join(ie.resolve(e),"config.yaml");if(!Zt(t))return{};let r=Fa(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 l=i.match(/^([ \t]+)aliases:\s*(?:\{\}\s*)?$/u);if(n&&l?.[1]){s=!0,a=l[1];continue}if(s){if(i.trim().length===0||i.trim().startsWith("#"))continue;let c=i.match(/^([ \t]+)(?:"([^"]+)"|'([^']+)'|([^:]+)):\s*(?:"([^"]+)"|'([^']+)'|(.+))\s*$/u);(c?.[1]??"").length<=a.length&&(s=!1);let d=c?.[2]??c?.[3]??c?.[4],g=c?.[5]??c?.[6]??c?.[7];s&&d&&g?o[d.trim()]=g.trim():/^[ \t]+\S/u.test(i)&&i.trim().length>0&&(s=!1)}}return o}import{readFile as By,writeFile as Wy}from"node:fs/promises";import Ky from"node:path";import s_ from"node:path";var Bd={minLength:1,removeStopwords:!1,normalizeDiacritics:!1};function tr(e,t={}){let r={...Bd,...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||!Wd.has(n))??[]))}function Ja(e,t={}){return new Set(tr(e,t))}function Do(e,t){let r=tr(e);if(r.length===0)return 0;let o=Ja(t),n=r.filter(s=>o.has(s)).length;return Number((n/r.length).toFixed(6))}function Ka(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 Wd=new Set(["the","and","for","with","this","that","uma","com","para","por","que","deve","esta","este","essa","isso"]);var rr=1,or="local-hash",nr="local-hash-bow-v1";function Ga(e){let t=f(e,{readOnly:!0});try{let r=t.semanticIndexStats({providerId:or,modelId:nr,schemaVersion:rr});return{provider_id:or,model_id:nr,schema_version:rr,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 sr(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:or,modelId:nr,schemaVersion:rr});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:qa(o.length>0?o:t.recentMemories(e.project,r),e.query)};let s=t.listCurrentSemanticIndexesForProject({project:e.project,providerId:or,modelId:nr,schemaVersion:rr,limit:1e3}),a=t.listActiveMemoriesForProject(e.project,1e3),i=new Map(a.map(d=>[d.id,d])),l=new Map(o.map(d=>[d.id,Do(e.query,`${d.summary}
|
|
825
|
+
${d.content}`)])),c=Jd(e.query),u=s.map(d=>{let g=i.get(d.memory_id);if(!g)return null;let h=l.get(g.id)??0,A=Ka(c,d.embedding);return{memory:g,ftsScore:h,semanticScore:A,score:Number((h*.55+A*.45).toFixed(6))}}).filter(d=>d!==null).filter(d=>d.ftsScore>0||d.semanticScore>0).sort((d,g)=>g.score-d.score||g.semanticScore-d.semanticScore||d.memory.id.localeCompare(g.memory.id)).slice(0,r).map((d,g)=>({...d.memory,recall:{mode:"hybrid",fts_score:d.ftsScore,semantic_score:d.semanticScore,final_rank:g+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:qa(o,e.query)}}finally{t.close()}}function Jd(e){let r=Array.from({length:32},()=>0);for(let n of tr(e)){let s=Kd(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 qa(e,t){return e.map((r,o)=>({...r,recall:{mode:"fts",fts_score:Do(t,`${r.summary}
|
|
826
|
+
${r.content}`),semantic_score:0,final_rank:o+1,reason:"fts_fallback"}}))}function Kd(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 it(e,t=160){let r=e.replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-3)}...`}function lt(e){return Math.ceil(e.length/4)}function ar(e,t){return e.length<=t?e:`${e.slice(0,Math.max(t-3,0))}...`}var Oe=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}},qd=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 ve(e,t){let r=await _(e),o=await Gd(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 dt(e,t){return lr(e,t,"active","memory_promoted")}async function ut(e,t){return lr(e,t,"rejected","memory_rejected")}async function pt(e,t){return lr(e,t,"forgotten","memory_forgotten")}async function Ho(e,t){return lr(e,t,"expired","memory_expired")}async function ir(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 Gd(e,t,r){let o=N(t.content),n=new Date().toISOString(),s=it(o.value),a={id:P("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:je({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 lr(e,t,r,o){let n=await _(e),s=f(n.database),a,i;try{if(a=s.getMemory(t),a&&!$o(a.status,r))throw new Oe({id:t,from:a.status,to:r});i=a?s.updateMemoryStatus(t,r):null}catch(l){throw l instanceof Oe&&await Xd({home:n.home,id:l.id,from:l.from,to:l.to}),l}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 $o(e,t){return qd.get(e)?.has(t)??!1}async function Xd(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 mt(e,t,r,o=5){let n=await _(e),s=sr({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 Fo(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:Xa(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:Xa(e.resolution)}}),{touched:!0,inserted:o.inserted,degraded:!1,warning:null}}catch(o){return{touched:!1,inserted:!1,degraded:!0,warning:`PROJECT_REGISTRY_UNAVAILABLE:${zd(o)}`}}finally{r?.close()}}function Xa(e){return e.remote??e.git_root??e.cwd}function zd(e){return(e instanceof Error?e.message:String(e)).replace(/[^a-zA-Z0-9_.:-]+/g,"_").slice(0,120)}var Yd=/^-\s*\*\*([^:*]+):\*\*\s*(.*)$/u;function Ne(e,t){let r=Qd(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(Yd);if(!a||a[1]?.trim()!==t)continue;let i=a[2]?.trim()??"";if(i.length>0&&!i.startsWith("_("))return i;for(let l=n+1;l<o.length;l+=1){let c=o[l]?.trim()??"";if(!c||c.startsWith("#")||c.startsWith("- **"))break;if(!c.startsWith("_("))return c}}return null}function za(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 Ya(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 Qd(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}import{copyFile as C_,mkdir as O_,readFile as lu,rename as N_,stat as cu,writeFile as M_}from"node:fs/promises";import{existsSync as du}from"node:fs";import Qa from"node:path";import{mkdir as Zd,readFile as eu,rename as tu,writeFile as ru}from"node:fs/promises";import gt from"node:path";var ou=1440*60*1e3;async function Me(e){let t=p(e.home),r=await Uo(t.home),o={host:e.host,outcome:e.outcome,tier:e.tier,cwd:e.cwd?gt.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:iu(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:au(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 nu();let o=JSON.parse(await eu(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>ou}}function nu(){return{schema:1,hosts:{}}}async function su(e,t){let r=Bo(e);await Zd(gt.dirname(r),{recursive:!0,mode:448});let o=gt.join(gt.dirname(r),`.last-handshake-${P("tmp")}.tmp`);await ru(o,`${JSON.stringify(t,null,2)}
|
|
827
|
+
`,{encoding:"utf8",mode:384}),await tu(o,r)}function Bo(e){return gt.join(e,"state","last-handshake.json")}function au(e){return`handshake_${e}`}function iu(e){if(e==null)return null;let t=e instanceof Error?e.message:String(e);return N(t).value.slice(0,500)}async function Wo(e){let t=p(e.home),r=Za(t.home,e.host);if(!du(r))return uu({home:t.home,host:e.host,targetPath:r,recordTelemetry:e.recordTelemetry});let o=await lu(r,"utf8"),n=await cu(r),s=e.ttlDays??7,a=Date.now()-n.mtimeMs>s*24*60*60*1e3,i=new Date().toISOString(),l=a?["BOOTSTRAP_CACHE_STALE"]:[],c=["---","nativesoul: bootstrap-context-cache",`host: ${e.host}`,`generated_at: ${i}`,"degraded: true",l.length>0?`warnings: ${l.join(", ")}`:"warnings: none","---","",o].join(`
|
|
828
|
+
`),u={host:e.host,generated_at:i,degraded:!0,warnings:l,tokens_used:ti(c),tokens_max:1900,content:c,targetPath:r,stale:a};if(e.recordTelemetry!==!1){await m({home:t.home,type:"bootstrap_context_cache_read",details:{...u,content:"[omitted]"}});let d=pu(o);await Me({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:l})}return u}async function Jo(e){let t=await Wo({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 Wo({home:ei(e.projectCwd),host:e.host,ttlDays:e.ttlDays,recordTelemetry:!1});return r.warnings.includes("BOOTSTRAP_CACHE_MISSING")?t:r}function Za(e,t){return Qa.join(e,"generated",t,"last-context.md")}function ei(e){return Qa.join(e,".nativesoul-cache")}async function uu(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(`
|
|
829
|
+
`),n={host:e.host,generated_at:t,degraded:!0,warnings:r,tokens_used:ti(o),tokens_max:1900,content:o,targetPath:e.targetPath,stale:!1};return e.recordTelemetry!==!1&&(await m({home:e.home,type:"bootstrap_context_cache_missing",details:{...n,content:"[omitted]"}}),await Me({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 ti(e){return Math.ceil(e.length/4)}function pu(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 fu=3e3,hu=new WeakMap;async function ht(e){let t=e.readOnly?p(e.home):await _(e.home),r=await ku(t.home),o=Math.min(Math.max(e.tokensMax??r.defaultTokens,1),fu),n=[];e.readOnly!==!0&&await er({cwd:e.cwd,home:t.home});let s=me(e.cwd,t.home),a=s.id;if(e.readOnly!==!0){let M=await Fo({home:t.home,resolution:s});M.warning&&n.push(M.warning)}let i=Ru({explicitQuery:e.query,project:a,host:e.host,cwd:e.cwd,seed:r.memoryQuerySeed}),l=await yu({database:t.database,readOnly:e.readOnly===!0,memoryQuery:i,project:a,limit:r.recallLimit,warnings:n}),c=l.memories,u=await Ke({home:t.home,host:e.host,readyOnly:!0,limit:8,readOnly:e.readOnly}),d=await Eu(t.home,e.host,e.readOnly===!0),g=await Co({home:t.home,host:e.host,query:e.query??`${ge.basename(e.cwd)} ${e.host}`,limit:8,readOnly:e.readOnly}),h=await No({home:t.home,project:a,status:"open",limit:8,readOnly:e.readOnly}),A=await Q(t.home,"IDENTITY.md"),X=await Q(t.home,"SOUL.md"),ce=await Q(t.home,"AGENTS.md"),z=await Q(t.home,"USER.md"),Ae=await Q(t.home,"BOOTSTRAP.md"),$e=new Date().toISOString().slice(0,10),Nt=ge.join(t.home,"memory","daily",`${$e}.md`);n.push(...d?[]:[`HOST_ADAPTER_UNAVAILABLE:${e.host}`,"CAPABILITY_REFRESH_STALE"],...g.warnings),!await y(ge.join(t.home,"state","onboarding.complete"))&&Ae.trim().length>0&&n.push("BOOTSTRAP_RITUAL_PENDING"),await y(Nt)&&n.push(`DAILY_MEMORY_AVAILABLE:${Nt}`),r.warnEmptyMemories&&c.length===0&&n.push("PROJECT_MEMORY_EMPTY");let k={bootstrap_schema:2,identity:{name:Ne(A,"Name")??"NativeSoul",mission:Ne(A,"Mission")??"Provide local continuity across native coding-agent hosts.",creature:Ne(A,"Creature"),role:Ne(A,"Role"),vibe:Ne(A,"Vibe"),emoji:Ne(A,"Emoji")},soul_summary:za(X||"Continuity, clarity, and safe local-first operation.",500),agents_operating_summary:Ya(ce||"Load NativeSoul context before continuity-sensitive work. Use MCP when available and CLI fallback when needed."),tool_hints:Su(),user:{preferences_summary:wu(z)},project:{id:a,cwd:ge.resolve(e.cwd),state:"local-bootstrap"},commitments:h.map(M=>({id:M.id,status:M.status,summary:M.summary,due_at:M.due_at,ttl_expires_at:M.ttl_expires_at})),relevant_memories:c.map(M=>({id:M.id,summary:M.summary,scope:M.scope})),capabilities:u.map(M=>({uid:M.uid,host:M.host,ready:M.ready,source:M.source})),capability_cards:g.cards,policy:{mode:"safe",approval_required:["external_write","destructive","identity_policy_change"]},warnings:n},Wn=Au(k,o),Jn=lt(JSON.stringify(Wn)),Tr={...Wn,context_budget:{tokens_used:Jn,tokens_max:o}};return hu.set(Tr,{files:_u({home:t.home,identityText:A,soulText:X,agentsText:ce,userText:z,bootstrapText:Ae,payload:Tr}),memoryRecall:{query:i,limit:r.recallLimit,returned:c.length,mode:l.mode},cache:bu(t.home,e.host)}),e.readOnly||await m({home:t.home,type:"bootstrap_created",details:{host:e.host,cwd:ge.resolve(e.cwd),project:a,tokens:Jn}}),Tr}async function yu(e){if(!await y(e.database))return e.warnings.push("BOOTSTRAP_DATABASE_MISSING"),{memories:[],mode:"disabled"};let t=null;try{t=f(e.database,{readOnly:e.readOnly});let r=sr({database:e.database,query:e.memoryQuery,project:e.project,limit:e.limit,readOnly:e.readOnly});return{memories:r.memories.length===0?t.recentMemories(e.project,e.limit):r.memories,mode:r.mode}}catch(r){return e.warnings.push(`BOOTSTRAP_DATABASE_UNAVAILABLE:${vu(r)}`),{memories:[],mode:"disabled"}}finally{t?.close()}}function _u(e){return[ft({home:e.home,relativePath:"IDENTITY.md",role:"identity",rawText:e.identityText,injectedText:Object.values(e.payload.identity).filter(t=>typeof t=="string").join(`
|
|
830
|
+
`),fallbackReason:"missing; default identity fields injected"}),ft({home:e.home,relativePath:"SOUL.md",role:"soul_summary",rawText:e.soulText,injectedText:e.payload.soul_summary,fallbackReason:"missing; default soul summary injected"}),ft({home:e.home,relativePath:"AGENTS.md",role:"agents_operating_summary",rawText:e.agentsText,injectedText:e.payload.agents_operating_summary,fallbackReason:"missing; default agent operating summary injected"}),ft({home:e.home,relativePath:"USER.md",role:"user_preferences",rawText:e.userText,injectedText:e.payload.user.preferences_summary,fallbackReason:"missing; empty user-preferences fallback injected"}),ft({home:e.home,relativePath:"BOOTSTRAP.md",role:"onboarding_bootstrap",rawText:e.bootstrapText,injectedText:"",fallbackReason:"missing; no onboarding bootstrap warning",presentReason:"omitted; used only to emit BOOTSTRAP_RITUAL_PENDING"})]}function ft(e){let t=e.rawText.length,r=e.injectedText.length,o=t>0,n=r>0,s=o?e.presentReason??(r<t?"included; summarized to fit budget":"included"):e.fallbackReason;return{path:ge.join(e.home,e.relativePath),role:e.role,included:n,reason:s,rawChars:t,injectedChars:r,truncated:o&&n&&r<t,hash:o?$(e.rawText):null}}function bu(e,t){let r=ge.join(e,"generated",t,"last-context.md");return{hit:gu(r),key:r}}function vu(e){return(e instanceof Error?e.message:String(e)).replace(/[^a-zA-Z0-9_.:-]+/g,"_").slice(0,120)}async function ku(e){let t=await Q(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 Ru(e){return[e.explicitQuery,e.project,e.host,ge.basename(ge.resolve(e.cwd)),e.seed].filter(t=>typeof t=="string"&&t.trim().length>0).join(" ")}function Su(){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 wu(e){let t=e.trim();return t.length===0?"No curated user preferences yet.":t.length<=160?t:`${t.slice(0,157)}...`}async function Eu(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 Au(e,t){let r=[e,ke(e,1200,420,150),ke(e,900,320,130),ke(e,650,240,110),ke(e,420,180,90),ke(e,240,120,80),Ko(ke(e,240,120,80),8,8),Ko(ke(e,240,120,80),5,5),Ko(ke(e,240,120,80),3,3)];return r.find(o=>lt(JSON.stringify(o))<=t)??r[r.length-1]??e}function Ko(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 ke(e,t,r,o){return{...e,soul_summary:ar(e.soul_summary,r),agents_operating_summary:ar(e.agents_operating_summary,t),user:{...e.user,preferences_summary:ar(e.user.preferences_summary,o)}}}import{existsSync as fn}from"node:fs";import Di from"node:path";import{mkdir as sb,readFile as Pu,writeFile as ab}from"node:fs/promises";import ri from"node:path";var qo={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 oi(e,t){let r=await qe(e),o=await y(yt(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:qo,apply_defaults:{dry_run:!0,user_confirmed:!1,reset:!1}}}function xu(e){return ri.join(e,"state","activation-profile.json")}function yt(e){return ri.join(e,"state","activation.complete")}async function qe(e){try{let t=JSON.parse(await Pu(xu(e),"utf8"));return Iu(t)?t:null}catch{return null}}function Iu(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 Go(e){let t={bootstrap:Tu(e),mcp:ju(e),plugins_hooks:Cu(e),heartbeat:Ou(e),recall_auto_trigger:Nu(e),memory_candidate_hooks:Mu(e),memory_promotion_policy:Lu(e),cross_host_verification:Du(e)},r=Object.values(t),o=Hu(r),n=r.flatMap(a=>a.plan_actions),s=$u(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 ni(e){return Go(e).summary}function Tu(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},[Le("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 ju(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(q),checked_hosts:e.hosts.map(q)})}return x("mcp","not_configured","No MCP registration was detected for the selected host scope.",{checked_hosts:e.hosts.map(q)},[Le("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 Cu(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(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 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(q)},[Le("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 Ou(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(q),heartbeat_modes:Object.fromEntries(e.hosts.map(r=>[q(r),r.provider_parity.heartbeat]))},[Le("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(q)}):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(q)}):x("heartbeat","approval_required","Heartbeat profile is enabled, but no scheduler desired state is active yet.",{checked_hosts:e.hosts.map(q)},[Le("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 Nu(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},[Le("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 Mu(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=>[q(r),r.provider_parity.hooks]))})}function Lu(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 Du(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},[Le("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 Le(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 Hu(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 $u(e,t,r){return{overall_status:t,profile:e?.profile??null,active:_t(r,"active"),not_configured:_t(r,"not_configured"),approval_required:_t(r,"approval_required"),blocked_by_host:_t(r,"blocked_by_host"),degraded:_t(r,"degraded"),full_native_claimed:!1}}function _t(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 Fu}from"node:fs";import Uu from"node:path";async function Xo(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(Uu.join(t.home,s))||r.push({code:"MISSING_HUMAN_FILE",severity:"warn",message:`${s} is missing`,remediation:"Run nativesoul init"});if(!Fu(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(...Vu(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 Vu(e,t){let r=me(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 te from"node:os";import D from"node:path";function si(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 ai(e){return e==="claude"?".claude.json":e==="gemini"?"settings.json":e==="antigravity"?"mcp_config.json":"mcp.json"}function cr(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 bt(e,t){return t&&t!=="default"?[cr(e,t)]:e==="claude"?["claude-code","claude-desktop"]:["default"]}function vt(e,t){return t==="default"?e:t}function ii(e){switch(e){case"codex":return D.join(te.homedir(),".codex","AGENTS.md");case"claude":return D.join(te.homedir(),".claude","CLAUDE.md");case"grok":return D.join(te.homedir(),".grok","Agents.md");case"antigravity":case"gemini":return D.join(te.homedir(),".gemini","GEMINI.md")}}function dr(e){switch(e){case"codex":return D.join(te.homedir(),".codex","mcp.json");case"claude":return D.join(te.homedir(),".claude.json");case"grok":return D.join(te.homedir(),".grok","mcp.json");case"antigravity":return D.join(te.homedir(),".gemini","antigravity-cli","mcp_config.json");case"gemini":return D.join(te.homedir(),".gemini","settings.json")}}function li(){return ci({platform:process.platform,home:te.homedir(),env:process.env})}function ci(e){let t=e.platform==="win32"?D.win32:D.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 di(e,t){if(e!=="claude")return null;if(!t)return D.join(te.homedir(),".claude","mcp.json");let r=D.resolve(t),o=D.dirname(r);return D.basename(o)==="claude"?D.join(o,"mcp.json"):D.join(o,".claude","mcp.json")}import{mkdir as ui,rename as Bu,writeFile as mi}from"node:fs/promises";import G from"node:path";var Wu=["entity","soul","human","collaboration","continuity"],Ju=["SOUL.md","POLICY.md"],gi=new Set(["IDENTITY.md","SOUL.md","USER.md","AGENTS.md"]),Ge=64*1024,Ku="<!-- nativesoul:start v1 -->",pi="<!-- nativesoul:end -->",qu={"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 zo(e){let t=await _(e),o=(await Q(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:[...Ju],writable_files:[...gi],interview_themes:[...Wu],instruction_doc:"llm-install.txt",apply_defaults:{dry_run:!0,user_confirmed:!1},file_generation_rules:qu,activation:await oi(t.home,o)}}async function Yo(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 l=a.trim(),c=l.toUpperCase();if(c==="POLICY.MD"){n.push({file:l,action:"rejected",before_hash:null,after_hash:null,warning:"POLICY_VIOLATION: POLICY.md requires proposal flow"});continue}if(!gi.has(l)){n.push({file:l,action:"rejected",before_hash:null,after_hash:null,warning:`UNSUPPORTED_FILE: ${l}`});continue}if(c==="SOUL.MD"&&!o){n.push({file:l,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:l,action:"rejected",before_hash:null,after_hash:null,warning:`FILE_TOO_LARGE: ${l} exceeds ${Ge} bytes`});continue}let d=G.join(t.home,l),g=await Q(t.home,l),h=l==="AGENTS.md"?Gu(g,u):u,A=g.length>0?$(g):null,X=$(h);if(A===X){n.push({file:l,action:"noop",before_hash:A,after_hash:X});continue}let ce=g.length===0?"create":"update";n.push({file:l,action:ce,before_hash:A,after_hash:X}),r||await mi(d,h,{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 Qo(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 ui(a,{recursive:!0,mode:448});let i=new Date().toISOString().replace(/[:.]/gu,"-");n=G.join(a,`bootstrap-${i}.md`),await Bu(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 ui(G.join(t.home,"state"),{recursive:!0,mode:448}),await mi(s,`${new Date().toISOString()}
|
|
831
|
+
`,{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 ur(e){return G.join(e,"state","onboarding.complete")}function Gu(e,t){let r=t.trim();if(!e.trim())return`${r}
|
|
832
|
+
`;if(e.includes(r))return e;let o=Xu(e);if(o){let s=o.after.trimEnd(),a=s.length>0?`${s}
|
|
829
833
|
|
|
830
834
|
${r}
|
|
831
835
|
`:`${r}
|
|
832
|
-
`;return`${o.before}${o.block}${a}`}let n
|
|
836
|
+
`;return`${o.before}${o.block}${a}`}let n=Vt["AGENTS.md"]??"";return e.trim()===n.trim()?`${r}
|
|
833
837
|
`:`${e.trimEnd()}
|
|
834
838
|
|
|
835
839
|
## Onboarding Update
|
|
836
840
|
|
|
837
841
|
${r}
|
|
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
|
-
|
|
841
|
-
`)
|
|
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);
|
|
842
|
+
`}function Xu(e){let t=e.indexOf(Ku),r=e.indexOf(pi);if(t<0||r<0||r<t)return null;let o=r+pi.length;return{before:e.slice(0,t),block:e.slice(t,o),after:e.slice(o)}}function fi(e,t){return t?Ga(e):zu()}function zu(){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 hi(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 yi(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 pr(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 Ap}from"node:fs";import{readFile as Pp,stat as xp}from"node:fs/promises";import Mi from"node:path";import St from"node:path";import{existsSync as pk}from"node:fs";import{cp as gk,mkdir as fk,rm as hk}from"node:fs/promises";import _k from"node:path";import{existsSync as Se}from"node:fs";import{readFile as _r}from"node:fs/promises";import he from"node:path";import Yu from"node:path";function mr(e){return e.split(/[\\/]/u).join("/")}function kt(e,t){return mr(Yu.relative(e,t))}import{existsSync as _i}from"node:fs";import Zo from"node:path";function en(e){if(Zo.isAbsolute(e))return _i(e)?e:null;let t=(process.env.PATH??"").split(Zo.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=Zo.join(o,`${e}${n}`);if(_i(s))return s}return null}import{spawnSync as qb}from"node:child_process";import{existsSync as hr}from"node:fs";import{mkdir as zb,readFile as yr,writeFile as Yb}from"node:fs/promises";import Qu from"node:os";import fe from"node:path";import{existsSync as Fb}from"node:fs";import Rt from"node:os";import re from"node:path";import{fileURLToPath as Wb}from"node:url";function Re(e,t,r){return gr(e,t)?r?re.join(re.resolve(r),e,"plugins","nativesoul"):e==="claude"?re.join(Rt.homedir(),".claude","plugins","nativesoul"):e==="codex"?re.join(Rt.homedir(),".codex","plugins","nativesoul"):e==="gemini"?re.join(Rt.homedir(),".gemini","extensions","nativesoul"):e==="grok"?re.join(Rt.homedir(),".grok","plugins","nativesoul"):e==="antigravity"?re.join(Rt.homedir(),".antigravity","plugins","nativesoul"):null:null}function gr(e,t){return e==="codex"||e==="gemini"||e==="grok"||e==="antigravity"||e==="claude"&&(t==="claude-code"||t==="claude-desktop")}function fr(e,t){return e==="claude"?re.join(t,".claude-plugin","plugin.json"):e==="gemini"?re.join(t,"gemini-extension.json"):e==="grok"||e==="antigravity"?re.join(t,"plugin.json"):re.join(t,".codex-plugin","plugin.json")}var bi="nativesoul",vi="nativesoul";async function Si(e){let t=e?rp(e):fe.join(Qu.homedir(),".grok","config.toml");if(!hr(t))return null;let r=await yr(t,"utf8");return ki(r,"disabled",bi)?!1:ki(r,"enabled",bi)?!0:null}async function wi(e){let t=tp(e);if(!hr(t))return!1;let r=JSON.parse(await yr(t,"utf8"));return Zu(r)}async function Ei(e){let t=Ai(e),r=fe.join(t,"agents",`${vi}.md`),o=fe.join(t,"config.toml");if(!hr(r)||!hr(o))return!1;let[n,s]=await Promise.all([yr(r,"utf8"),yr(o,"utf8")]);return n.includes("NativeSoul continuity agent")&&op(s)===vi}function ki(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 Zu(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])=>ep(t,o,n))}function ep(e,t,r){let o=e[t];return Array.isArray(o)?o.some(n=>np(n)?.includes(r)===!0):!1}function tp(e){return fe.join(Ai(e),"hooks","nativesoul.json")}function Ai(e){return fe.resolve(e,"..","..")}function rp(e){let t=fe.resolve(e),r=fe.basename(t);return r==="grok"||r===".grok"?fe.join(t,"config.toml"):fe.join(t,".grok","config.toml")}function op(e){return e.match(/\[agent\][\s\S]*?(?=\n\[|$)/u)?.[0]?.match(/\bname\s*=\s*["']([^"']+)["']/u)?.[1]??null}function np(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 sp from"node:path";var tn=[{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"}],ap={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 rn(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 ip(e){return e==="grok"||e==="gemini"||e==="antigravity"?ap[e]:tn}function on(e){return e==="grok"||e==="gemini"?["hooks/hooks.json"]:e==="antigravity"?["hooks.json"]:[...new Set(tn.map(t=>t.fileName).filter(t=>!!t))].map(t=>sp.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 xi(e,t){return nn(e,t).length===0}function nn(e,t){return ip(e).filter(({event:r,commandFragment:o})=>!lp(t,r,o)).map(({event:r})=>r)}function sn(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 an(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 lp(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 l=i.command;return typeof l=="string"&&mr(l).includes(r)})})}async function Xe(e){if(!e.targetPath||!gr(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=rn(e.host,e.surface),r=Se(e.targetPath),o=fr(e.host,e.targetPath),n=Se(o),s=t.nativeHooksSupported&&e.targetPath?on(e.host).filter(z=>!Se(he.join(e.targetPath,z))):on(e.host),a=t.nativeHooksSupported?s.length===0:!0,i=[],l=!1,c=!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 z=JSON.parse(await _r(o,"utf8")),Ae=t.nativeHooksSupported?await cp(e.host,e.targetPath,z):z;if(l=t.nativeHooksSupported?e.host==="grok"?await wi(e.targetPath):xi(e.host,Ae):Pi(z,t.packageKind),c=!t.nativeHooksSupported||await dp({host:e.host,targetPath:e.targetPath,manifest:z}),u=e.host==="grok"?await Ei(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&&!c&&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"}),!l&&t.nativeHooksSupported){let $e=nn(e.host,Ae);i.push({code:"PLUGIN_HOOK_MISSING",severity:"error",message:$e.length>0?`NativeSoul plugin manifest is missing required hook registrations: ${$e.join(", ")}.`:"NativeSoul plugin manifest does not register required continuity hooks.",remediation:"Reinstall the NativeSoul plugin"})}!l&&!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?he.join(e.targetPath,"shared","hooks","lib.cjs"):null;r&&t.nativeHooksSupported&&(!d||!Se(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 g=e.targetPath?he.resolve(he.dirname(he.dirname(e.targetPath))):void 0,h=!t.nativeHooksSupported||d!==null&&Se(d),A=t.nativeHooksSupported?a&&h:!0,X=r&&n&&l&&A&&c&&u,ce=e.host==="grok"?await Si(g):null;return e.host==="grok"&&X&&ce===!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:X&&ce!==!1,hook_registered:t.nativeHooksSupported?l&&a:!1,package_kind:t.packageKind,native_hooks_supported:t.nativeHooksSupported,native_scheduler_supported:!1,issues:i}}async function cp(e,t,r){let o=an(e);if(o.length===0)return r;let n=kt(t,fr(e,t)),s=o[0];if(!s||s===n)return r;let a=he.join(t,s);return Se(a)?JSON.parse(await _r(a,"utf8")):{}}async function dp(e){let t=sn(e.host),r=kt(e.targetPath,fr(e.host,e.targetPath));if(t.length>0&&!t.includes(r)){for(let o of t){let n=he.join(e.targetPath,o);if(Se(n)&&ln(JSON.parse(await _r(n,"utf8"))))return!0}return!1}if(e.host==="codex"){let o=he.join(e.targetPath,".mcp.json");return Se(o)?ln(JSON.parse(await _r(o,"utf8"))):!1}return ln(e.manifest)}function ln(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"||en(o)||o===process.execPath?!0:Array.isArray(n)&&n.some(s=>typeof s=="string"&&he.isAbsolute(s))}import{cp as yv,mkdir as _v,readFile as bv,readdir as vv}from"node:fs/promises";import Rv from"node:path";import{existsSync as Dv}from"node:fs";import{cp as $v,mkdir as Fv,readFile as Uv,writeFile as Vv}from"node:fs/promises";import Wv from"node:path";import{fileURLToPath as Kv}from"node:url";import{spawnSync as Pv}from"node:child_process";import{accessSync as Iv,constants as Tv,existsSync as jv}from"node:fs";import Ov from"node:path";function br(e,t,r){let o=cr(e,r);if(e==="claude"&&o==="claude-desktop")return{surface:o,managedBlock:null,mcpRegistration:t?St.join(St.resolve(t,e),"claude_desktop_config.json"):li(),plugin:Re(e,o,t)};if(!t)return{surface:o,managedBlock:ii(e),mcpRegistration:dr(e),plugin:Re(e,o)};let n=St.resolve(t,e);return{surface:o,managedBlock:St.join(n,si(e)),mcpRegistration:St.join(n,ai(e)),plugin:Re(e,o,t)}}import{accessSync as pp,constants as mp,existsSync as wt}from"node:fs";import{mkdir as $k,readFile as cn,rm as Fk,writeFile as Uk}from"node:fs/promises";import le from"node:path";async function pn(e){let t=le.resolve(e.targetPath??Ci(e.host)),r=di(e.host,e.targetPath),o=wt(t),n=[],s=await gp(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=dn(await cn(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?un(a):null,l=typeof i?.command=="string"?i.command:null,c=Array.isArray(i?.args)?i.args.filter(d=>typeof d=="string"):[];i?l||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=l?e.checkCommand===!1?{ok:!0,issues:[]}:fp(l,c,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:l,command_ok:u.ok,issues:n}}function Ci(e){return dr(e)}function dn(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 un(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 gp(e,t,r){if(e!=="claude"||r===null||le.resolve(r)===t||!wt(r))return null;try{let o=dn(await cn(r,"utf8")),n=un(o);if(!n)return null;if(wt(t)){let s=dn(await cn(t,"utf8")),a=un(s);if(a&&JSON.stringify(Ti(a))===JSON.stringify(Ti(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 Ti(e){return{command:typeof e.command=="string"?e.command:null,args:Array.isArray(e.args)?e.args.filter(t=>typeof t=="string"):[]}}function fp(e,t,r){let o=[],n=hp(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(yp(e,n)){let s=t[0],a=s?le.isAbsolute(s)?s:le.resolve(le.dirname(r),s):null;if(!a||!wt(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 hp(e){if(le.isAbsolute(e))return ji(e)?e:null;let t=(process.env.PATH??"").split(le.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=le.join(o,`${e}${n}`);if(ji(s))return s}return null}function ji(e){if(process.platform==="win32"&&wt(e))return!0;try{return pp(e,mp.X_OK),!0}catch{return!1}}function yp(e,t){let r=le.basename(e).toLowerCase(),o=le.basename(t).toLowerCase();return r==="node"||r==="node.exe"||o==="node"||o==="node.exe"}async function mn(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 gn(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(h=>bp(h,t)),a=Sp(e.capabilities,e.adapterDiagnostics),i=[Et("native_package",r,t,e.plugin.targetPath??e.plugin.package_kind,"Native package/extension is not installed or enabled."),Et("native_hooks",o,t,e.plugin.targetPath??e.plugin.package_kind,"Native lifecycle hook registration is missing."),Et("mcp",n,t,e.mcpRegistration.targetPath,"MCP registration is missing or invalid."),Et("native_scheduler",s,t,kp(e.schedules),wp(e.host,e.schedules)),Et("official_inventory",a,t,Rp(e.capabilities),"Official non-degraded capability inventory evidence is missing.")],l=i.filter(h=>!h.satisfied).map(h=>h.requirement),c=r&&o&&n,u=!a,d=l.includes("native_scheduler")&&Ni(e.host),g=l.length===0;return{schema_version:1,host:e.host,surface:e.surface,status:Ep({fullNative:g,blockedByHost:d,degradedScan:u,ready:c}),ready:c,full_native:g,blocked_by_host:d,degraded_scan:u,generated_at:t,requirements:i,missing_requirements:l}}function Et(e,t,r,o,n){return{requirement:e,satisfied:t,evidence:t?[{source_kind:"doctor",reference:o,observed_at:r,confidence:_p(o)}]:[],missing_reason:t?null:n}}function _p(e){return e.startsWith("not-applicable:")||e==="missing"?"low":"medium"}function bp(e,t){return e.enabled&&e.native_schedule_supported&&e.native_id!==null&&!vp(e.updated_at,t)}function vp(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 kp(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 Rp(e){return e.find(t=>t.ready)?.source??"missing"}function Sp(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 wp(e,t){return Ni(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 Ni(e){return e==="codex"||e==="claude"||e==="grok"||e==="gemini"||e==="antigravity"}function Ep(e){return e.fullNative?"full_native":e.blockedByHost?"blocked_by_host":e.degradedScan?"degraded_scan":e.ready?"ready_fallback":"ready"}async function Li(e){let t=br(e.host,e.targetRoot,e.surface),r=t.managedBlock??`not-applicable:${vt(e.host,e.surface)}`,o=t.managedBlock?await Oa({host:e.host,targetPath:r}):Lp(e.host,e.surface),n=await pn({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 Vo({home:e.home,host:e.host}),l=(e.databaseExists?await mn({home:e.home,host:e.host,limit:200,readOnly:!0}):[]).filter(k=>Ip(e.host,e.surface,k)),c=e.databaseExists?await Ke({home:e.home,host:e.host,limit:100,readOnly:!0}):[],u=e.databaseExists?pr(p(e.home).database):[],d=e.targetRoot!==void 0,g=d?[]:(await Io(e.host))[0]?.diagnostics??[],h=l.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"}]:[],A=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`}]:[],X=await Cp({host:e.host,managedBlock:o,handshake:a}),ce=await Op(e.host),z=l.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`})),Ae=l.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`})),$e=jp({managedBlock:o,mcpRegistration:n,plugin:s,schedules:l,capabilities:c}),Nt=gn({host:e.host,surface:e.surface,mcpRegistration:n,plugin:s,schedules:l,capabilities:c,adapterDiagnostics:g}),Ir=[...o.issues,...n.issues,...s.issues,...g,...h,...A,...X,...ce,...z,...Ae];return{host:e.host,surface:e.surface,status:Ir.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:g,managed_block:o,mcp_registration:n,plugin:s,provider_parity:$e,full_native_evidence:Nt,handshake:a,schedule_count:l.length,enabled_schedule_count:l.filter(k=>k.enabled).length,native_schedule_mappings:l.map(k=>({id:k.id,native_schedule_supported:k.native_schedule_supported,native_id:k.native_id})),capability_count:c.length,ready_capability_count:c.filter(k=>k.ready).length,cross_host_inventory_summary:{current_host:c.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:Ir}}function Ip(e,t,r){return e!=="claude"?!0:Tp(r.desired)===t}function Tp(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 jp(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",l=e.plugin.package_kind==="unsupported-native"?"unsupported-native":t?"ready":"degraded",c=e.capabilities.length===0||e.capabilities.some(d=>d.ready);return{level:o&&r&&l==="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:l,hooks:i,memory_recall:r?"ready":"degraded",policy_guard:o?"ready":"degraded",capability_scan:c?"ready":"degraded",heartbeat:a}}async function Cp(e){if(!e.managedBlock.configured||e.managedBlock.targetPath.startsWith("not-applicable:"))return[];let t=10080*60*1e3,r=await Mp(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 Op(e){let t=Np(e).map(r=>Mi.resolve(process.cwd(),r));for(let r of t){if(!Ap(r))continue;let o=await Pp(r,"utf8"),n=lt(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 Np(e){switch(e){case"claude":return["CLAUDE.md",Mi.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 Mp(e){try{let t=await xp(e);return Math.max(Date.now()-t.mtimeMs,0)}catch{return null}}function Lp(e,t){return{host:e,targetPath:`not-applicable:${vt(e,t)}`,target_exists:!1,configured:!0,markers_valid:!0,issues:[]}}async function At(e){let t=p(e.home),r=await Xo(e.home),o=fn(t.database),n=Je(e.host),s=[],a=o?pr(t.database):[],i=fi(t.database,o),l=await qe(t.home),c=fn(ur(t.home)),u=fn(yt(t.home));for(let h of n)for(let A of bt(h,e.surface))s.push(await Li({home:t.home,host:h,surface:A,targetRoot:e.targetRoot,databaseExists:o}));let d=[...r.issues,...hi(i),...s.flatMap(h=>h.issues)],g=r.healthy&&!d.some(h=>h.severity==="error");return{home:t.home,healthy:g,status:d.some(h=>h.severity==="error"||h.severity==="warn")?"degraded":"ready",workspace:r,target_root:e.targetRoot?Di.resolve(e.targetRoot):null,cross_host_inventory:yi(a),activation_summary:ni({home:t.home,targetRoot:e.targetRoot?Di.resolve(e.targetRoot):null,host:e.host,profile:l,onboardingComplete:c,activationComplete:u,hosts:s}),full_native_matrix:Dp(s),semantic_index:i,hosts:s,issues:d}}function Dp(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 $R}from"node:fs";import{mkdir as UR,readdir as VR,readFile as BR,writeFile as WR}from"node:fs/promises";import KR from"node:path";import{lstat as nS,readdir as sS,readFile as aS}from"node:fs/promises";import lS from"node:path";import{lstat as _S,readFile as bS}from"node:fs/promises";import kS 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 Hp,mkdir as $p,readFile as Fp,rm as CS,writeFile as Up}from"node:fs/promises";import{randomUUID as Vp}from"node:crypto";import Hi from"node:path";function hn(e){return Hi.join(p(e).home,"license.json")}async function He(e){let t=hn(e);if(!await y(t))return null;try{let r=JSON.parse(await Fp(t,"utf8"));return Bp(r)?r:null}catch{return null}}async function vr(e,t){let r=hn(e);return await $p(Hi.dirname(r),{recursive:!0,mode:448}),await Up(r,`${JSON.stringify(t,null,2)}
|
|
843
|
+
`,{encoding:"utf8",mode:384}),await Hp(r,384),t}async function yn(e){let t=await He(e);if(t?.instance_id)return t.instance_id;let r=Vp();return await vr(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 Bp(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 $i={name:"nativesoul",version:"1.0.0",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 Fi=$i.version;var Kp="https://api.dodopayments.com",qp=1440*60*1e3,Gp=14;async function _n(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 Pt(t,"license_validate_missing",null,"INVALID_KEY","blocked"),{ok:!1,reason:"INVALID_KEY",license:o?kr(o):De};if(o?.state==="licensed"&&Xp(o.last_checked_at,r))return await Pt(t,"license_validate_cache_hit",n,null,"ok"),{ok:!0,license:kr(o)};let a=await Yp(e,"/licenses/validate",{license_key:n});if(a.ok){let i=await vr(t,{state:"licensed",license_key:n,instance_id:s??await yn(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 Pt(t,"license_validated",n,null,"ok"),{ok:!0,license:kr(i)}}return a.reason==="NETWORK"&&o?.state==="licensed"&&zp(o.last_checked_at,r,e.graceDays)?(await Pt(t,"license_validate_grace_served",n,"NETWORK","ok"),{ok:!0,license:kr(o)}):(await Pt(t,"license_validate_failed",n,a.reason,"blocked"),{ok:!1,reason:a.reason,license:{...De,instance_id:s}})}function kr(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 Xp(e,t){return e?t.getTime()-new Date(e).getTime()<qp:!1}function zp(e,t,r=Gp){return e?t.getTime()-new Date(e).getTime()<=r*24*60*60*1e3:!1}async function Yp(e,t,r){let o=e.fetch??globalThis.fetch;try{let n=await o(new URL(t,Qp(e.endpointBaseUrl)).toString(),{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(r)}),s=await Zp(n);return n.ok?t==="/licenses/validate"&&s.valid!==!0?{ok:!1,reason:Ui(s)}:{ok:!0,license_key_instance_id:em(s),purchased_at:tm(s)}:{ok:!1,reason:Ui(s)}}catch{return{ok:!1,reason:"NETWORK"}}}function Qp(e=process.env.NATIVESOUL_DODO_LICENSE_API_BASE_URL??Kp){return e.endsWith("/")?e:`${e}/`}async function Zp(e){try{let t=await e.json();return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function em(e){let r=[e.license_key_instance_id,e.licenseKeyInstanceId,e.id,xt(e.data)?e.data.license_key_instance_id:null,xt(e.data)?e.data.id:null].find(o=>typeof o=="string"&&o.length>0);return typeof r=="string"?r:null}function tm(e){let t=xt(e.data)?e.data:{},r=xt(e.license_key)?e.license_key:xt(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 Ui(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 xt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}async function Pt(e,t,r,o,n){await m({home:e,type:t,result:n,details:{provider:"dodo",license_key_ref:r?rm(r):null,reason:o}})}function rm(e){return e.length<=8?"[REDACTED_LICENSE_KEY]":`${e.slice(0,4)}\u2026${e.slice(-4)}`}var Rr="https://docs.nativesoul.dev/account/licensing";async function Sr(e){let t=om(e),r=p(t.home).home;try{let o=await He(r),n=await _n(t);if(n.ok)return{ok:!0,license:n.license};let s=n.reason==="NETWORK"&&o?.state==="licensed"?"GRACE_EXPIRED":"UNLICENSED",a=t.activateUrl??Rr;return{ok:!1,reason:s,activate_url:a,message:bn({reason:s,activate_url:a}),license:n.license}}catch{let o=t.activateUrl??Rr;return{ok:!1,reason:"UNLICENSED",activate_url:o,message:bn({reason:"UNLICENSED",activate_url:o}),license:De}}}function bn(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 om(e){return typeof e=="string"?{home:e}:e??{}}import{readdir as ZS,readFile as ew,stat as tw}from"node:fs/promises";import ow from"node:path";var Bi={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 vn(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:P("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:O(e.tags??[]),metadata:O(e.metadata??{}),created_at:r,updated_at:r,claimed_at:null,completed_at:null},a=Wi({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),l;try{l=i.insertWorkItem(s),i.insertWorkItemEvent(a)}finally{i.close()}return await Ji(t.home,"work_item_created",l,{redacted:o!==e.title||e.description!==void 0&&e.description!==null&&n!==e.description,event_id:a.id}),l}async function kn(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:am(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 Rn(e){return En({home:e.home,id:e.id,actor:e.host,eventType:"claimed",auditType:"work_item_claimed",mutate:(t,r)=>{if(An(t.status))throw new Error(`Work item already terminal: ${t.id} (${t.status})`);return wr(t.status,"in_progress"),{status:"in_progress",assignedHost:e.host,claimedAt:t.claimed_at??r,updatedAt:r,details:{assigned_host:e.host}}}})}async function Sn(e){return En({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&&wr(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:O(e.tags),metadata:e.metadata===void 0?void 0:lm(t.metadata,O(e.metadata)),completedAt:An(o)?r:void 0,updatedAt:r,details:{priority:e.priority??null,assigned_host:e.assignedHost??null,fields:sm(e),redacted:e.description!==void 0&&e.description!==null&&n!==e.description}}}})}async function wn(e){let t=e.status??"done";return En({home:e.home,id:e.id,actor:"cli",eventType:"completed",auditType:"work_item_completed",mutate:(r,o)=>{if(An(r.status))throw new Error(`Work item already terminal: ${r.id} (${r.status})`);return wr(r.status,t),{status:t,completedAt:o,updatedAt:o,details:{terminal_status:t}}}})}function wr(e,t){if(e!==t&&!Bi[e].includes(t))throw new Error(`Illegal work item transition: ${e} -> ${t}`)}async function En(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=Wi({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 Ji(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 Wi(e){return{id:P("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 Ji(e,t,r,o){await m({home:e,type:t,details:{id:r.id,project:r.project_id,status:r.status,...im(o)}})}function sm(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 An(e){return e==="done"||e==="failed"}function am(e){return!e||!Number.isFinite(e)?50:Math.min(Math.max(Math.trunc(e),1),200)}function im(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e}}function lm(e,t){return Vi(e)&&Vi(t)?{...e,...t}:t}function Vi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}import{readdir as Ww,readFile as Jw}from"node:fs/promises";import qw from"node:path";import{existsSync as yw}from"node:fs";import{mkdir as Aw,readdir as dm,readFile as um,writeFile as Pw}from"node:fs/promises";import It from"node:path";var pm=new Set(["SOUL.MD","POLICY.MD"]),mm=5e3,Ki=new Map;async function Tt(e){let t=p(e),r=Ki.get(t.home);if(r&&r.expiresAt>Date.now())return r.orders;let o=It.join(t.home,"standing-orders"),n;try{n=await dm(o)}catch{return[]}let s=[];for(let a of n.filter(i=>i.endsWith(".yaml")||i.endsWith(".yml")).sort()){let i=It.join(o,a),l=await um(i,"utf8");s.push(gm(l,i))}return Ki.set(t.home,{expiresAt:Date.now()+mm,orders:s}),s}async function jt(e){let t=await Tt(e.home),r=e.target??null,o=r?fm(r):null,n=t.filter(i=>Pn(i,e)),s=n.find(i=>i.allowed.includes(e.action)),a=n.find(i=>i.approval_required.includes(e.action));if(o&&pm.has(o))return we(e,"proposal_required",["PROTECTED_HUMAN_FILE"],null);if(e.className==="identity_policy_change")return we(e,"proposal_required",["IDENTITY_POLICY_CHANGE"],null);if(e.className==="destructive")return we(e,"denied",["DESTRUCTIVE_DENIED_BY_DEFAULT"],s?.id??a?.id??null);if(a)return we(e,"approval_required",["STANDING_ORDER_REQUIRES_APPROVAL"],a.id);if(s)return we(e,"allowed",["STANDING_ORDER_ALLOWED"],s.id);switch(e.className){case"read_local":case"probe_external":case"write_local":return we(e,"allowed",["DEFAULT_ALLOWED"],null);case"write_project":return we(e,"approval_required",["PROJECT_WRITE_REQUIRES_APPROVAL"],null);case"external_write":return we(e,"approval_required",["EXTERNAL_WRITE_REQUIRES_APPROVAL"],null)}}function we(e,t,r,o){return{action:e.action,class:e.className,target:e.target??null,decision:t,reasons:r,matched_standing_order:o}}function gm(e,t){return{id:hm(e,"id")??It.basename(t,It.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 Pn(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 fm(e){return It.basename(e.replaceAll("\\","/")).toUpperCase()}function hm(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 l=i.trim();if(!s){let u=i.match(new RegExp(`^(\\s*)${t}:\\s*$`,"u"));u&&(s=!0,a=u[1]?.length??0);continue}let c=i.length-i.trimStart().length;if(l&&c<=a&&!l.startsWith("-"))break;l.startsWith("-")&&n.push(l.slice(1).trim().replace(/^["']|["']$/gu,""))}return n.filter(Boolean)}import{mkdir as oE,writeFile as nE}from"node:fs/promises";import aE from"node:path";import{readFile as Sm}from"node:fs/promises";import wm from"node:path";var Er=1500;async function In(e){let t=await _(e.home),r=await Pm(t.home),o=new Date,n=Em(e.ttlSeconds??r.ttlSeconds),s=new Date(o.getTime()+n*1e3).toISOString(),a=jn(e.project,e.slot),i=f(t.database),l;try{l=i.claimHeartbeatLease({id:P("lease"),slot:e.slot,holder:e.host,idempotencyKey:a,now:o.toISOString(),expiresAt:s})}finally{i.close()}return await m({home:t.home,type:l.claimed?"heartbeat_claimed":"heartbeat_skipped",details:{slot:e.slot,host:e.host,project:e.project,lease_id:l.lease.id,reason:l.reason}}),{slot:e.slot,host:e.host,project:e.project,claimed:l.claimed,reason:l.reason,silent_ack:l.claimed||l.reason==="LEASE_OCCUPIED"&&!r.skipWhenBusy?null:"HEARTBEAT_OK",lease:l.lease}}async function Tn(e){let t=await _(e.home),r=new Date().toISOString(),o=jn(e.project,e.slot),n=O(e.result??"HEARTBEAT_OK"),s=O(Am(e.evidence??{},e.workItemId)),a=O(e.cost??{}),i=Fe(a),l=f(t.database),c;try{c=l.completeHeartbeatLease({idempotencyKey:o,host:e.host,project:e.project,result:n,evidence:s,cost:i,completedAt:r,runId:P("run")})}finally{l.close()}return await m({home:t.home,type:c.completed?"heartbeat_completed":"heartbeat_completion_replayed",details:{slot:e.slot,host:e.host,project:e.project,lease_id:c.lease.id,run_id:c.run?.id??null}}),{slot:e.slot,project:e.project,completed:c.completed,silent_ack:"HEARTBEAT_OK",lease:c.lease,run:c.run}}function jn(e,t){return`heartbeat:${e}:${t}`}function Em(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),1440*60):Er}function Am(e,t){return t?{...e&&typeof e=="object"&&!Array.isArray(e)?e:{},work_item_id:t}:e}async function Pm(e){let t;try{t=await Sm(wm.join(e,"config.yaml"),"utf8")}catch{return{ttlSeconds:Er,skipWhenBusy:!0}}return{ttlSeconds:xm(t),skipWhenBusy:Im(t,"skip_when_busy",!0)}}function xm(e){let t=xn(e,"ttl_seconds"),r=xn(e,"lease_ttl"),o=Tm(e,"heartbeat_ttl_seconds"),n=jm(t??r??o);return Number.isFinite(n)?n:Er}function Im(e,t,r){let o=xn(e,t);return o?/^(true|yes|1)$/i.test(o)?!0:/^(false|no|0)$/i.test(o)?!1:r:r}function xn(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 Tm(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.match(new RegExp(`^\\s*${r}:\\s*([^#\\n]+)`,"mu"))?.[1]?.trim().replace(/^["']|["']$/g,"")??null}function jm(e){if(!e)return Er;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 CE from"node:path";import{rm as NE}from"node:fs/promises";async function On(e){let t=p(e.home),r=f(t.database),o;try{let n=r.findPendingApprovalMatch(Cn(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:P("approval"),...Cn(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:Ln(o.approval)}),o}async function Nn(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:Ln(o.approval)}),o}async function Mn(e){let t=p(e.home),r=f(t.database),o;try{let n=r.createDecidedApproval({id:P("approval"),...Cn(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:{...Ln(o.approval),standing_order:e.standingOrderId}}),o}function Cn(e){return{action:e.action,class:e.class,target:e.target??null,project:e.project??null,host:e.host??null}}function Ln(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 Ct(e){let t=await jt(e),r=await Fm(e,t);if(r){let n=await Mn({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 On({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 Fm(e,t){return t.decision!=="allowed"||!t.matched_standing_order||!Um(e.className)?null:(await Tt(e.home)).find(o=>o.id===t.matched_standing_order&&o.allowed.includes(e.action)&&Pn(o,e))??null}function Um(e){return e==="write_project"||e==="external_write"}var zi={"memory.promote":{action:"memory.promote",className:"write_local"},"memory.forget":{action:"memory.forget",className:"write_local"},"memory.reject":{action:"memory.reject",className:"write_local"},"work_item.create":{action:"work_item.create",className:"write_local"},"work_item.claim":{action:"work_item.claim",className:"write_local"},"work_item.complete":{action:"work_item.complete",className:"write_local"},"install.apply":{action:"install.apply",className:"write_local"},"policy_pack.apply":{action:"policy_pack.apply",className:"write_local"}};async function Dn(e,t={}){let r=zi[e],o={home:t.home,action:r.action,className:r.className,target:t.target??void 0,project:t.project??void 0,host:t.host??void 0},n,s,a,i;try{let l=await Ct(o);n=l.evaluation,s=l.approval?.id??null,a=l.approval_created,i=l.warning}catch(l){return await Xi(r,t,["POLICY_GATE_UNAVAILABLE"],"error"),{status:"deny",decision:"denied",reason:`policy gate unavailable (fail-closed): ${l.message}`,evaluation:null}}return n.decision==="allowed"?{status:"allow",decision:"allowed",evaluation:n}:n.decision==="approval_required"?{status:"approval_required",decision:"approval_required",approvalId:s,approvalCreated:a,warning:i,evaluation:n}:(await Xi(r,t,n.reasons,"blocked"),{status:"deny",decision:n.decision,reason:`${r.action} ${n.decision}: ${n.reasons.join(", ")}`,evaluation:n})}async function Xi(e,t,r,o){try{let n=await _(t.home);await m({home:n.home,type:"policy_blocked",result:"blocked",details:{boundary:"sensitive_operation",action:e.action,class:e.className,target:t.target??null,project:t.project??null,host:t.host??null,outcome:o,reasons:r}})}catch{}}import{existsSync as kA}from"node:fs";import{mkdir as SA,readFile as wA,rm as EA,writeFile as AA}from"node:fs/promises";import xA from"node:path";import{existsSync as dA}from"node:fs";import{readdir as pA,readFile as mA}from"node:fs/promises";import fA from"node:path";import{fileURLToPath as yA}from"node:url";import nA from"node:path";var Yi=["AGENTS.md","CLAUDE.md","GEMINI.md","Agents.md",".claude/CLAUDE.md"],sA=new Set(Yi);import Bm from"node:path";async function Ar(e={}){let t=p(e.home),r=e.host??"all",[o,n,s,a]=await Promise.all([qe(t.home),y(ur(t.home)),y(yt(t.home)),At({home:t.home,host:r,surface:e.surface,targetRoot:e.targetRoot})]);return Go({home:t.home,targetRoot:e.targetRoot?Bm.resolve(e.targetRoot):null,host:r,profile:o,onboardingComplete:n,activationComplete:s,hosts:a.hosts})}async function Hn(e={}){let t=await Ar(e);if(!e.profile||t.profile?.profile===e.profile)return t;let r={...t.profile??qo,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 Wm}from"node:crypto";import Jm from"node:path";var Km="NativeSoul activation verification marker";async function Fn(e={}){let t=zm(e),r=me(t.projectCwd,e.home),o=await At({home:e.home,host:e.host??"all",surface:e.surface,targetRoot:e.targetRoot}),n=[];for(let c of o.hosts)n.push(await qm({home:o.home,inputHost:c,testCwd:t.projectCwd}));let s=await Xm({home:e.home,testProject:`${r.id}-${Wm()}`,apply:e.apply===!0,userConfirmed:e.userConfirmed===!0,retainTestData:e.retainTestData===!0}),a=[...new Set([...n.flatMap(c=>c.recommendations),...s.status==="failed"?["Review memory persistence and rerun verification."]:[]])],i=n.map(c=>c.status),l=Qm(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:l,memory_recall:s,hosts:n,recommendations:a}}async function qm(e){let t=[],r=await Gm({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=Ym(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 Gm(e){let t=[...e.warnings],r=[],o="ready",n=!1,s="",a="ready";try{let i=await ht({home:e.home,host:e.host,cwd:e.cwd,readOnly:!0});t.push(...i.warnings),i.warnings.some(l=>l.startsWith("HOST_ADAPTER_UNAVAILABLE")||l==="PROJECT_MEMORY_EMPTY")&&(a="degraded")}catch(i){t.push(`bootstrap_injection_failed:${$n(i)}`),a="failed"}try{let i=await Jo({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(l=>l==="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 Xm(e){let t=[],r=null,o=!1,n=!1;try{let s=`verify-${e.testProject}`,a=`${Km} ${e.testProject}`;r=await ve(e.home,{project:s,content:a,confidence:.91,source:{host:"activation-verification",session_id:`verification-${e.testProject}`}});let i=await mt(e.home,a,s,8),l=await ir({home:e.home,project:s,status:"candidate",limit:8}),c=i.some(u=>u.id===r?.id)||l.some(u=>u.id===r?.id);if(e.apply&&e.userConfirmed&&r){let u=await dt(e.home,r.id);r=u,n=r.id===u.id&&r.status==="active"}if(!e.retainTestData&&r)try{r.status==="candidate"?await ut(e.home,r.id):await pt(e.home,r.id),o=!0}catch(u){t.push(`memory_cleanup_failed:${$n(u)}`)}return{test_project:e.testProject,candidate_id:r?.id??"",candidate_status:r?.status??"candidate",recalled:c,promoted:n,status:c?"passed":"failed",warnings:t,cleanup_performed:o}}catch(s){return t.push(`memory_recall_check_failed:${$n(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 zm(e){return{projectCwd:Jm.resolve(e.projectCwd??process.cwd())}}function Ym(e){return e==="native"?"native":e==="official-fallback"?"official_fallback":"unsupported"}function Qm(e,t){return e.includes("blocked_by_host")?"blocked_by_host":e.includes("degraded")||t==="failed"?"degraded":e.length>0?"ready":"degraded"}function $n(e){return e instanceof Error?e.message:String(e)}function Zi(e){let t=p(e);if(!Zm(t.database))return{home:t.home,initialized:!1,database:t.database,migrations:0,memories:0,events:0,capabilities:0,ledger:eg()};let r=f(t.database,{readOnly:!0});try{return{home:t.home,initialized:!0,database:t.database,...r.counts()}}finally{r.close()}}function eg(){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 el={life_activation_status:async(e,t)=>await Ar({home:t,host:Un(e.host),targetRoot:Ee(e.target_root)??Ee(e.targetRoot)}),life_activation_plan:async(e,t)=>await Hn({home:t,host:Un(e.host),targetRoot:Ee(e.target_root)??Ee(e.targetRoot),profile:tg(e.profile)}),life_activation_verify:async(e,t)=>await Fn({home:t,host:Un(e.host),surface:rg(e.surface),targetRoot:Ee(e.target_root)??Ee(e.targetRoot),projectCwd:Ee(e.project_cwd)??Ee(e.projectCwd),apply:Vn(e.apply),userConfirmed:Vn(e["user-confirmed"]),retainTestData:Vn(e["retain-test-data"])})},tl=[{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 Un(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 tg(e){if(e!==void 0){if(e==="quickstart"||e==="advanced")return e;throw new Error("Invalid activation profile")}}function rg(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 Ee(e){return typeof e=="string"?e:void 0}function Vn(e){return e===!0}var og=["2025-11-25","2024-11-05","2024-10-07"],al={...el,life_status:(e,t)=>Zi(t),life_bootstrap:async(e,t)=>await dg({home:t,host:S(e.host,"codex"),cwd:S(e.cwd,process.cwd()),query:I(e.query)}),life_recall:async(e,t)=>await mt(t,S(e.query,""),S(e.project,"default"),xr(e.limit,5)),life_remember_propose:async(e,t)=>await ve(t,{project:S(e.project,"default"),content:S(e.content,""),type:I(e.type),confidence:rl(e.confidence),source:{host:"mcp",session_id:"local"}}),life_memory_promote:async(e,t)=>await dt(t,S(e.id,"")),life_memory_reject:async(e,t)=>await ut(t,S(e.id,"")),life_memory_forget:async(e,t)=>await pt(t,S(e.id,"")),life_memory_expire:async(e,t)=>await Ho(t,S(e.id,"")),life_capability_search:async(e,t)=>await To({home:t,query:S(e.query,""),host:mg(e)?void 0:I(e.host)??"codex",readyOnly:Ye(e.readyOnly,!1),limit:xr(e.limit,8)}),life_capability_status:async(e,t)=>{let r=S(e.uid,""),o=r?await jo({home:t,uid:r}):null;if(!o)throw new Error(`Capability not found: ${r}`);return o},life_policy_evaluate:async(e,t)=>await jt({home:t,action:S(e.action,""),className:sl(e.class),target:I(e.target)}),life_approval_request:async(e,t)=>await yg({home:t,action:S(e.action,""),className:sl(e.class),target:I(e.target),project:I(e.project),host:I(e.host)}),life_approval_decide:async(e,t)=>{let r=S(e.id,""),o=await Nn({home:t,id:r,status:hg(e.status),reviewer:S(e.host,"mcp"),reason:I(e.reason)??null});if(!o.approval)throw new Error(`Approval not found: ${r}`);return o},life_commitment_create:async(e,t)=>await Oo({home:t,project:S(e.project,"default"),summary:S(e.summary,""),dueAt:I(e.due_at),ttlSeconds:rl(e.ttl_seconds),source:{host:"mcp",session_id:"local"}}),life_commitment_complete:async(e,t)=>await Mo(t,S(e.id,"")),life_work_item_create:async(e,t)=>await vn({home:t,project:S(e.project,"default"),title:S(e.title,""),description:I(e.description),priority:Bn(e.priority),source:"mcp",tags:ol(e.tags),host:I(e.host)}),life_work_item_list:async(e,t)=>await kn({home:t,project:I(e.project),status:nl(e.status),priority:Bn(e.priority),assignedHost:I(e.host),limit:xr(e.limit,50)}),life_work_item_claim:async(e,t)=>await Rn({home:t,id:S(e.id,""),host:S(e.host,"mcp")}),life_work_item_update:async(e,t)=>await Sn({home:t,id:S(e.id,""),status:nl(e.status),priority:Bn(e.priority),assignedHost:I(e.host),description:I(e.description),tags:e.tags===void 0?void 0:ol(e.tags)}),life_work_item_complete:async(e,t)=>await wn({home:t,id:S(e.id,""),status:pg(e.status)}),life_heartbeat_claim:async(e,t)=>await In({home:t,slot:S(e.slot,""),host:S(e.host,"codex"),project:S(e.project,"default"),ttlSeconds:xr(e.ttl_seconds,1500)}),life_heartbeat_complete:async(e,t)=>await Tn({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:I(e.work_item_id)}),life_onboarding_status:async(e,t)=>await zo(t),life_onboard_apply:async(e,t)=>await Yo({home:t,dry_run:Ye(e.dry_run,!0),user_confirmed:Ye(e.user_confirmed,!1),files:gg(e.files),config_patch:fg(e.config_patch)}),life_onboard_complete:async(e,t)=>await Qo({home:t,archive:e.archive===void 0?!0:Ye(e.archive,!0)})},ng=new Set(Object.keys(al));function sg(e){return e.method?.startsWith("notifications/")?!0:!Object.prototype.hasOwnProperty.call(e,"id")}async function ag(e,t){if(sg(e))return null;let r=e.id??null;try{if(e.method==="initialize"){let o=Ot(e.params),n=I(o.protocolVersion),s=n&&og.includes(n)?n:"2024-11-05";return ye(r,{protocolVersion:s,serverInfo:{name:"nativesoul",version:"0.1.0"},capabilities:{tools:{}}})}if(e.method==="ping")return ye(r,{});if(e.method==="resources/list")return ye(r,{resources:[]});if(e.method==="prompts/list")return ye(r,{prompts:[]});if(e.method==="tools/list")return ye(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"}},...tl,{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 Sr(t);if(!o.ok)return ye(r,o);let n=ug(e.params);return ye(r,await lg(n.name??"",n.arguments??{},t))}if(ng.has(e.method)){let o=await Sr(t);return o.ok?ye(r,await ll(e.method,Ot(e.params),t)):ye(r,o)}return Pr(r,-32601,`Unknown method: ${e.method}`)}catch(o){return o instanceof Oe?Pr(r,-32010,o.message,{code:o.code,id:o.id,from:o.from,to:o.to}):o instanceof ne?Pr(r,-32011,o.message,{code:o.code,id:o.id,status:o.status}):Pr(r,-32603,o instanceof Error?o.message:"Unknown MCP error")}}async function il(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&&ig(s,e).catch(a=>{process.stderr.write(`NativeSoul MCP response error: ${_g(a)}
|
|
844
|
+
`)})}})}async function ig(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"}})}
|
|
845
|
+
`);return}let o=await ag(r,t);o&&process.stdout.write(`${JSON.stringify(o)}
|
|
846
|
+
`)}async function lg(e,t,r){let o=await ll(e,t,r);return{content:[{type:"text",text:JSON.stringify(o)}]}}var cg={life_memory_promote:"memory.promote",life_memory_reject:"memory.reject",life_memory_forget:"memory.forget",life_work_item_create:"work_item.create",life_work_item_claim:"work_item.claim",life_work_item_complete:"work_item.complete"};async function ll(e,t,r){let o=al[e];if(!o)throw new Error(`Unknown tool: ${e}`);let n=cg[e];if(n){let s=await Dn(n,{home:r,target:I(t.id)??I(t.title)??null,project:I(t.project),host:I(t.host)});if(s.status==="deny")throw new Error(`Blocked by policy gate: ${s.reason}`);if(s.status==="approval_required")return{blocked:!0,allowed:!1,decision:"approval_required",approval_id:s.approvalId,approval_created:s.approvalCreated,wait:"human",instruction:s.approvalId?`approval ${s.approvalId} pending - run: nativesoul approvals approve ${s.approvalId} --confirm`:"approval pending but unavailable - inspect NativeSoul approval storage",warning:s.warning}}return await o(t,r)}async function dg(e){try{let t=await ht({...e,readOnly:!0});try{await Me({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 Me({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 ye(e,t){return{jsonrpc:"2.0",id:e,result:t}}function Pr(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 ug(e){return Ot(e)}function Ot(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function S(e,t){return typeof e=="string"?e:t}function I(e){return typeof e=="string"?e:void 0}function xr(e,t){return typeof e=="number"?e:t}function rl(e){return typeof e=="number"?e:void 0}function ol(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function nl(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 pg(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 Bn(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 mg(e){return Ye(e.allHosts,!1)||Ye(e.all_hosts,!1)}function gg(e){let t=Ot(e),r={};for(let[o,n]of Object.entries(t))typeof n=="string"&&(r[o]=n);return r}function fg(e){let r=Ot(e).hosts;if(!Array.isArray(r))return;let o=r.filter(n=>typeof n=="string");return o.length>0?{hosts:o}:void 0}function sl(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 hg(e){if(e==="approved"||e==="rejected")return e;throw new Error("life_approval_decide status must be approved or rejected")}async function yg(e){let t=await Ct(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 _g(e){return e instanceof Error?e.message:"Unknown MCP response error"}var cl=process.argv.indexOf("--home"),bg=cl>=0?process.argv[cl+1]:void 0;await il(bg);
|